code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
space = None variants = { # to be expanded once addtional spaces are supported 'space1': ['fsaverage5', 'MNI152NLin2009cAsym'], 'space2': ['fsaverage6', 'MNI152NLin2009cAsym'], } for sp, targets in variants.items(): if all(target i...
def _define_variant(self)
Assign arbitrary label to combination of CIFTI spaces
4.373242
3.908627
1.118869
if (self.inputs.surface_target == "fsnative" or self.inputs.volume_target != "MNI152NLin2009cAsym"): # subject space is not support yet raise NotImplementedError annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir, ...
def _fetch_data(self)
Converts inputspec to files
4.604553
4.357285
1.056748
''' generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ''' self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file self._seg_files = [self._mask_file]...
def _post_run_hook(self, runtime)
generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid
8.91142
4.452518
2.001434
''' generates a report showing slices from each axis ''' brain_extraction_mask = self.aggregate_outputs(runtime=runtime).BrainExtractionMask if isdefined(self.inputs.keep_temporary_files) and self.inputs.keep_temporary_files == 1: self._anat_file = self.aggregate_outputs(runtime=ru...
def _post_run_hook(self, runtime)
generates a report showing slices from each axis
6.353986
5.279508
1.203519
''' generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ''' self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file self._seg_files = [self._mask_file]...
def _post_run_hook(self, runtime)
generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid
8.269335
4.219032
1.960008
''' generates a report showing slices from each axis ''' assert len(self.inputs.mask_files) == 1, \ "ACompCorRPT only supports a single input mask. " \ "A list %s was found." % self.inputs.mask_files self._anat_file = self.inputs.realigned_file self._mask_file = ...
def _post_run_hook(self, runtime)
generates a report showing slices from each axis
6.057389
4.898936
1.23647
''' generates a report showing slices from each axis ''' high_variance_masks = self.aggregate_outputs(runtime=runtime).high_variance_masks assert not isinstance(high_variance_masks, list),\ "TCompCorRPT only supports a single output high variance mask. " \ "A list %s wa...
def _post_run_hook(self, runtime)
generates a report showing slices from each axis
7.202376
5.976713
1.205073
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verb...
def get_versions()
Get version information or return default if unable to do so.
4.396214
4.362468
1.007736
out_file = fname_presuffix(in_file, suffix='_ras', newpath=newpath) nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file) return out_file
def reorient(in_file, newpath=None)
Reorient Nifti files to RAS
2.60884
2.247648
1.160698
# Let nibabel convert from affine to quaternions, and recover xform tmp_header = img.header.copy() tmp_header.set_qform(img.affine) xform = tmp_header.get_qform() xform_code = 2 # Check desired codes qform, qform_code = img.get_qform(coded=True) sform, sform_code = img.get_sform(co...
def normalize_xform(img)
Set identical, valid qform and sform matrices in an image Selects the best available affine (sform > qform > shape-based), and coerces it to be qform-compatible (no shears). The resulting image represents this same affine as both qform and sform, and is marked as NIFTI_XFORM_ALIGNED_ANAT, indicating t...
2.750549
2.694984
1.020618
import os import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_file = fname_presuffix(in_file, suffix='_demeaned', newpath=os.getcwd()) nii = nb.load(in_file) msk = nb.load(in_mask).get_data() data = nii.get_d...
def demean(in_file, in_mask, only_mask=False, newpath=None)
Demean ``in_file`` within the mask defined by ``in_mask``
1.754064
1.772482
0.989609
import os import numpy as np import nibabel as nb nii = nb.load(in_file) data = np.ones(nii.shape, dtype=float) * value out_file = os.path.join(newpath or os.getcwd(), "filled.nii.gz") nii = nb.Nifti1Image(data, nii.affine, nii.header) nii.set_data_dtype(dtype) nii.to_filename...
def nii_ones_like(in_file, value, dtype, newpath=None)
Create a NIfTI file filled with ``value``, matching properties of ``in_file``
1.894142
1.910428
0.991475
workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_file']), name='outputnode') deoblique = pe.Node(afni.Refit(deoblique=True), name='deoblique')...
def reorient_wf(name='ReorientWorkflow')
A workflow to reorient images to 'RPI' orientation
1.546337
1.539241
1.00461
desc = [] if self.__desc__: desc += [self.__desc__] for node in pe.utils.topological_sort(self._graph)[0]: if isinstance(node, LiterateWorkflow): add_desc = node.visit_desc() if add_desc not in desc: desc.appe...
def visit_desc(self)
Builds a citation boilerplate by visiting all workflows appending their ``__desc__`` field
5.392745
4.461732
1.208666
if out_file is None: out_file = fname_presuffix(fixed_image, suffix='_reference', newpath=os.getcwd()) # Moving images may not be RAS/LPS (more generally, transverse-longitudinal-axial) reoriented_moving_img = nb.as_closest...
def _gen_reference(fixed_image, moving_image, fov_mask=None, out_file=None, message=None, force_xform_code=None)
Generates a sampling reference, and makes sure xform matrices/codes are correct
3.061691
3.046823
1.00488
import pandas as pd # Adapted from https://dev.to/rrampage/snake-case-to-camel-case-and- ... # back-using-regular-expressions-and-python-m9j re_to_camel = r'(.*?)_([a-zA-Z0-9])' re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)' def snake(match): return '{}_{}'.format(...
def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None, drop_columns=None, enforce_case=True)
Convert metadata from TSV format to JSON format. Parameters ---------- in_tsv: str Path to the metadata in TSV format. out_json: str Path where the metadata should be saved in JSON format after conversion. If this is None, then a dictionary is returned instead. index_column:...
2.785429
2.785978
0.999803
tpm_img = nb.load(in_tpm) roi_mask = (tpm_img.get_data() >= pthres).astype(np.uint8) eroded_mask_file = None erode_in = (mask_erosion_mm is not None and mask_erosion_mm > 0 or mask_erosion_prop is not None and mask_erosion_prop < 1) if erode_in: eroded_mask_file = fname...
def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None, mask_erosion_prop=None, erosion_prop=None, pthres=0.95, newpath=None)
Generate a mask from a tissue probability map
1.796648
1.791842
1.002682
report = Report(Path(reportlets_dir), out_dir, run_uuid, config=config, subject_id=subject_label, packagename=packagename) return report.generate_report()
def run_reports(reportlets_dir, out_dir, subject_label, run_uuid, config=None, packagename=None)
Runs the reports .. testsetup:: >>> from shutil import copytree >>> from tempfile import TemporaryDirectory >>> new_path = Path(__file__).resolve().parent.parent >>> test_data_path = new_path / 'data' / 'tests' / 'work' >>> tmpdir = TemporaryDirectory() >>> os.chdir(tmpdir.name) #noqa ...
3.242139
5.461984
0.593583
reports_dir = str(Path(work_dir) / 'reportlets') report_errors = [ run_reports(reports_dir, output_dir, subject_label, run_uuid, config, packagename=packagename) for subject_label in subject_list ] errno = sum(report_errors) if errno: import logging ...
def generate_reports(subject_list, output_dir, work_dir, run_uuid, config=None, packagename=None)
A wrapper to run_reports on a given ``subject_list``
4.129618
4.105053
1.005984
for subrep_cfg in config: # First determine whether we need to split by some ordering # (ie. sessions / tasks / runs), which are separated by commas. orderings = [s for s in subrep_cfg.get('ordering', '').strip().split(',') if s] queries = [] ...
def index(self, config)
Traverse the reports config definition and instantiate reportlets. This method also places figures in their final location.
4.641042
4.520357
1.026698
logs_path = self.out_dir / 'logs' boilerplate = [] boiler_idx = 0 if (logs_path / 'CITATION.html').exists(): text = (logs_path / 'CITATION.html').read_text(encoding='UTF-8') text = '<div class="boiler-html">%s</div>' % re.compile( '<body...
def generate_report(self)
Once the Report has been indexed, the final HTML can be generated
2.272565
2.255641
1.007503
import nibabel as nb from nipype.utils.filemanip import fname_presuffix from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms in_file, in_xform, ifargs, index, newpath = args out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index, ...
def _applytfms(args)
Applies ANTs' antsApplyTransforms to the input image. All inputs are zipped in one tuple to make it digestible by multiprocessing's map
2.981967
2.94735
1.011745
base_xform = ['#Insight Transform File V1.0', '#Transform 0'] # Initialize the transforms matrix xfms_T = [] for i, tf_file in enumerate(transforms): # If it is a deformation field, copy to the tfs_matrix directly if guess_type(tf_file)[0] != 'text/plain': xfms_T.append(...
def _arrange_xfms(transforms, num_files, tmp_folder)
Convenience method to arrange the list of transforms that should be applied to each input file
3.799871
3.764827
1.009308
img = nb.load(in_file) transform = load_transform(transform_file) pointset = img.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0] coords = pointset.data.T c_ras_keys = ('VolGeomC_R', 'VolGeomC_A', 'VolGeomC_S') ras = np.array([[float(pointset.metadata[key])] for key i...
def normalize_surfs(in_file, transform_file, newpath=None)
Re-center GIFTI coordinates to fit align to native T1 space For midthickness surfaces, add MidThickness metadata Coordinate update based on: https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91 and https://github.com/Washington-Univ...
4.054125
3.778632
1.072908
if fname is None: return np.eye(4) if fname.endswith('.mat'): return np.loadtxt(fname) elif fname.endswith('.lta'): with open(fname, 'rb') as fobj: for line in fobj: if line.startswith(b'1 4 4'): break lines = fobj.rea...
def load_transform(fname)
Load affine transform from file Parameters ---------- fname : str or None Filename of an LTA or FSL-style MAT transform file. If ``None``, return an identity transform Returns ------- affine : (4, 4) numpy.ndarray
3.731141
3.230267
1.155057
def normalize_v3(arr): ''' Normalize a numpy array of 3 component vectors shape=(n,3) ''' lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2) arr /= lens[:, np.newaxis] tris = vertices[faces] facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) ...
def vertex_normals(vertices, faces)
Calculates the normals of a triangular mesh
2.108995
2.124116
0.992881
from pathlib import Path import pandas as pd from pyntcloud import PyntCloud df = pd.DataFrame(np.hstack((vertices, normals))) df.columns = ['x', 'y', 'z', 'nx', 'ny', 'nz'] cloud = PyntCloud(df) if out_file is None: out_file = Path('pointcloud.ply').resolve() cloud.to_fil...
def pointcloud2ply(vertices, normals, out_file=None)
Converts the file to PLY format
2.118778
2.100948
1.008487
from pathlib import Path from numpy import eye from nibabel.gifti import ( GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray, ) from pyntcloud import PyntCloud in_file = Path(in_file) surf = PyntCloud.from_file(str(in_file)) # Update centroid metadata metadat...
def ply2gii(in_file, metadata, out_file=None)
Convert from ply to GIfTI
3.002446
2.969859
1.010972
import os from nipype.utils.filemanip import filename_to_list base, in_file = os.path.split(filename_to_list(in_files)[0]) subject_label = in_file.split("_", 1)[0].split("-")[1] return os.path.join(base, "sub-%s_T1w.nii.gz" % subject_label)
def fix_multi_T1w_source_name(in_files)
Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz'
2.463247
2.40072
1.026045
import os.path as op from nipype.utils.filemanip import fname_presuffix, filename_to_list return op.basename(fname_presuffix(filename_to_list(in_files)[0], suffix=suffix))
def add_suffix(in_files, suffix)
Wrap nipype's fname_presuffix to conveniently just add a prefix >>> add_suffix([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz'], '_test') 'sub-045_ses-test_T1w_test.nii.gz'
2.92731
3.1749
0.922016
from pathlib import Path lines = Path(path).read_text().splitlines() data = {'file': str(path)} traceback_start = 0 if lines[0].startswith('Node'): data['node'] = lines[0].split(': ', 1)[1].strip() data['node_dir'] = lines[1].split(': ', 1)[1].strip() inputs = [] ...
def _read_txt(path)
Read a txt crashfile >>> new_path = Path(__file__).resolve().parent.parent >>> test_data_path = new_path / 'data' / 'tests' >>> info = _read_txt(test_data_path / 'crashfile.txt') >>> info['node'] # doctest: +ELLIPSIS '...func_preproc_task_machinegame_run_02_wf.carpetplot_wf.conf_plot' >>> info...
3.177927
3.025209
1.050482
from pathlib import Path basename = str(Path(fname).name) stem = Path(basename.rstrip('.gz')).stem return stem, basename[len(stem):]
def splitext(fname)
Splits filename and extension (.gz safe) >>> splitext('some/file.nii.gz') ('file', '.nii.gz') >>> splitext('some/other/file.nii') ('file', '.nii') >>> splitext('otherext.tar.gz') ('otherext', '.tar.gz') >>> splitext('text.txt') ('text', '.txt')
5.251011
6.155988
0.852992
sns.set_style("whitegrid") sns.set_context("paper", font_scale=0.8) if figure is None: figure = plt.gcf() nconfounds = len(self.confounds) nspikes = len(self.spikes) nrows = 1 + nconfounds + nspikes # Create grid grid = mgs.GridSpec...
def plot(self, figure=None)
Main plotter
3.985959
3.927922
1.014775
from niworkflows.viz.utils import plot_registration NIWORKFLOWS_LOG.info('Generating visual report') fixed_image_nii = load_img(self._fixed_image) moving_image_nii = load_img(self._moving_image) contour_nii = load_img(self._contour) if self._contour is not None else Non...
def _generate_report(self)
Generates the visual report
2.815573
2.736114
1.029041
from niworkflows.viz.utils import plot_registration NIWORKFLOWS_LOG.info('Generating visual report') anat = load_img(self._anat_file) contour_nii = load_img(self._contour) if self._contour is not None else None if self._mask_file: anat = unmask(apply_mask(a...
def _generate_report(self)
Generates the visual report
4.458096
4.27102
1.043801
from pathlib import Path import nibabel as nb from nipype.utils.filemanip import fname_presuffix ref = nb.load(in_reference) nii = nb.load(in_mask) hdr = nii.header.copy() hdr.set_data_dtype('int16') hdr.set_slope_inter(1, 0) qform, qcode = ref.header.get_qform(coded=True) ...
def _conform_mask(in_mask, in_reference)
Ensures the mask headers make sense and match those of the T1w
2.481216
2.435782
1.018652
warn(DEPRECATION_MSG) file_id, md5 = OSF_RESOURCES[dataset_name] if url is None: url = '{}/{}'.format(OSF_PROJECT_URL, file_id) return fetch_file(dataset_name, url, data_dir, dataset_prefix=dataset_prefix, filetype='tar', resume=resume, verbose=verbose, md5sum=md5)
def get_dataset(dataset_name, dataset_prefix=None, data_dir=None, url=None, resume=True, verbose=1)
Download and load the BIDS-fied brainweb 1mm normal :param str data_dir: path of the data directory. Used to force data storage in a non-standard location. :param str url: download URL of the dataset. Overwrite the default URL.
4.047349
4.948656
0.817868
warn(DEPRECATION_MSG) if template_name.startswith('tpl-'): template_name = template_name[4:] # An aliasing mechanism. Please avoid template_name = TEMPLATE_ALIASES.get(template_name, template_name) return get_dataset(template_name, dataset_prefix='tpl-', data_dir=data_dir, ...
def get_template(template_name, data_dir=None, url=None, resume=True, verbose=1)
Download and load a template
4.474999
4.443446
1.007101
warn(DEPRECATION_MSG) return get_dataset('brainweb', data_dir=data_dir, url=url, resume=resume, verbose=verbose)
def get_brainweb_1mm_normal(data_dir=None, url=None, resume=True, verbose=1)
Download and load the BIDS-fied brainweb 1mm normal :param str data_dir: path of the data directory. Used to force data storage in a non-standard location. :param str url: download URL of the dataset. Overwrite the default URL.
3.386086
6.829307
0.495817
warn(DEPRECATION_MSG) variant = 'BIDS-examples-1-1.0.0-rc3u5' if variant not in BIDS_EXAMPLES else variant if url is None: url = BIDS_EXAMPLES[variant][0] md5 = BIDS_EXAMPLES[variant][1] return fetch_file(variant, url, data_dir, resume=resume, verbose=verbose, md5s...
def get_bids_examples(data_dir=None, url=None, resume=True, verbose=1, variant='BIDS-examples-1-1.0.0-rc3u5')
Download BIDS-examples-1
2.861348
2.829586
1.011225
''' takes an image as created by nilearn.plotting and returns a blob svg. Performs compression (can be disabled). A bit hacky. ''' # Check availability of svgo and cwebp has_compress = all((which('svgo'), which('cwebp'))) if compress is True and not has_compress: raise RuntimeError('Compres...
def svg_compress(image, compress='auto')
takes an image as created by nilearn.plotting and returns a blob svg. Performs compression (can be disabled). A bit hacky.
3.83689
3.325856
1.153655
from io import StringIO image_buf = StringIO() display_object.frame_axes.figure.savefig( image_buf, dpi=dpi, format='svg', facecolor='k', edgecolor='k') return image_buf.getvalue()
def svg2str(display_object, dpi=300)
Serializes a nilearn display object as a string
3.486459
3.426224
1.017581
image_svg = svg2str(display_object, dpi) if compress is True or compress == 'auto': image_svg = svg_compress(image_svg, compress) image_svg = re.sub(' height="[0-9]+[a-z]*"', '', image_svg, count=1) image_svg = re.sub(' width="[0-9]+[a-z]*"', '', image_svg, count=1) image_svg = re.sub('...
def extract_svg(display_object, dpi=300, compress='auto')
Removes the preamble of the svg files generated with nilearn
3.60663
3.569006
1.010542
from nibabel.affines import apply_affine mask_data = mask_nii.get_data() > 0.0 # First, project the number of masked voxels on each axes ijk_counts = [ mask_data.sum(2).sum(1), # project sagittal planes to transverse (i) axis mask_data.sum(2).sum(0), # project coronal planes to ...
def cuts_from_bbox(mask_nii, cuts=3)
Finds equi-spaced cuts for presenting images
4.566057
4.559087
1.001529
''' if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file ''' in_file = filemanip.filename_to_list(in_file)[0] try: in_file = nb.load(i...
def _3d_in_file(in_file)
if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file
5.139257
2.444416
2.102448
plot_params = {} if plot_params is None else plot_params image_nii = _3d_in_file(image_nii) data = image_nii.get_data() plot_params = robust_set_limits(data, plot_params) bbox_nii = nb.load(image_nii if bbox_nii is None else bbox_nii) if masked: bbox_nii = nlimage.threshold_img(b...
def plot_segs(image_nii, seg_niis, out_file, bbox_nii=None, masked=False, colors=None, compress='auto', **plot_params)
plot segmentation as contours over the image (e.g. anatomical). seg_niis should be a list of files. mask_nii helps determine the cut coordinates. plot_params will be passed on to nilearn plot_* functions. If seg_niis is a list of size one, it behaves as if it was plotting the mask.
3.896513
3.890539
1.001536
plot_params = {} if plot_params is None else plot_params # Use default MNI cuts if none defined if cuts is None: raise NotImplementedError # TODO out_files = [] if estimate_brightness: plot_params = robust_set_limits(anat_nii.get_data().reshape(-1), ...
def plot_registration(anat_nii, div_id, plot_params=None, order=('z', 'x', 'y'), cuts=None, estimate_brightness=False, label=None, contour=None, compress='auto')
Plots the foreground and background views Default order is: axial, coronal, sagittal
3.566437
3.629044
0.982748
import svgutils.transform as svgt if fg_svgs is None: fg_svgs = [] # Merge SVGs and get roots svgs = bg_svgs + fg_svgs roots = [f.getroot() for f in svgs] # Query the size of each sizes = [] for f in svgs: viewbox = [float(v) for v in f.root.get("viewBox").split("...
def compose_view(bg_svgs, fg_svgs, ref=0, out_file='report.svg')
Composes the input svgs into one standalone svg and inserts the CSS code for the flickering animation
3.518538
3.439302
1.023038
import numpy as np # get the shape of the array we are projecting to new_shape = list(data.shape) del new_shape[max_axis] # generate a 3D indexing array that points to max abs value in the # current projection a1, a2 = np.indices(new_shape) inds = [a1, a2] inds.insert(max_axis,...
def transform_to_2d(data, max_axis)
Projects 3d data cube along one axis using maximum intensity with preservation of the signs. Adapted from nilearn.
5.067584
4.555455
1.112421
from os import path as op from inspect import getfile, currentframe from setuptools import setup, find_packages from niworkflows.__about__ import ( __packagename__, __author__, __email__, __maintainer__, __license__, __description__, __longdes...
def main()
Install entry-point
2.186432
2.153685
1.015205
workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['bias_corrected', 'out_file', 'out_mask', 'bias_image']), name='outputnode') inu_n4 = pe.Node( ...
def afni_wf(name='AFNISkullStripWorkflow', unifize=False, n4_nthreads=1)
Skull-stripping workflow Originally derived from the `codebase of the QAP <https://github.com/preprocessed-connectomes-project/\ quality-assessment-protocol/blob/master/qap/anatomical_preproc.py#L105>`_. Now, this workflow includes :abbr:`INU (intensity non-uniformity)` correction using the N4 algorith...
1.80834
1.784328
1.013457
data = u'{0}'.format(data) # We put data as a argument for log.error() so error tracking systems such # as Sentry will properly group errors together by msg only log.error(u'{0}: %s'.format(msg), data) raise cls(u'{0}: {1}'.format(msg, data))
def _log_and_raise_exception(msg, data, cls=FoursquareException)
Calls log.error() then raises an exception of class cls
9.539396
8.496726
1.122714
param_string = _foursquare_urlencode(params) for i in xrange(NUM_REQUEST_RETRIES): try: try: response = requests.get(url, headers=headers, params=param_string, verify=VERIFY_SSL) return _process_response(response) except requests.exceptions.Re...
def _get(url, headers={}, params=None)
Tries to GET data from an endpoint using retries
4.807091
4.621552
1.040147
try: response = requests.post(url, headers=headers, data=data, files=files, verify=VERIFY_SSL) return _process_response(response) except requests.exceptions.RequestException as e: _log_and_raise_exception('Error connecting with foursquare API', e)
def _post(url, headers={}, data=None, files=None)
Tries to POST data to an endpoint
3.019049
3.147531
0.95918
# Read the response as JSON try: data = response.json() except ValueError: _log_and_raise_exception('Invalid response', response.text) # Default case, Got proper response if response.status_code == 200: return { 'headers': response.headers, 'data': data } return _ra...
def _process_response(response)
Make the request and handle exception processing
4.987516
4.655517
1.071313
# Check the meta-data for why this request failed meta = data.get('meta') if meta: # Account for foursquare conflicts # see: https://developer.foursquare.com/overview/responses if meta.get('code') in (200, 409): return data exc = error_types.get(meta.get('errorType')) ...
def _raise_error_from_response(data)
Processes the response data
5.003201
5.10445
0.980165
# Original doc: http://docs.python.org/2/library/urllib.html#urllib.urlencode # Works the same way as urllib.urlencode except two differences - # 1. it uses `quote()` instead of `quote_plus()` # 2. it takes an extra parameter called `safe_chars` which is a string # having the characters whic...
def _foursquare_urlencode(query, doseq=0, safe_chars="&/,+")
Gnarly hack because Foursquare doesn't properly handle standard url encoding
2.735785
2.728538
1.002656
for name, endpoint in inspect.getmembers(self): if inspect.isclass(endpoint) and issubclass(endpoint, self._Endpoint) and (endpoint is not self._Endpoint): endpoint_instance = endpoint(self.base_requester) setattr(self, endpoint_instance.endpoint, endpoint_in...
def _attach_endpoints(self)
Dynamically attach endpoint callables to this client
3.457282
3.123193
1.10697
permissions = [permission() for permission in self.permission_classes] for permission in permissions: if not permission.has_permission(request): raise PermissionDenied()
def check_permissions(self, request)
Check if the request should be permitted. Raises an appropriate exception if the request is not permitted.
2.869801
2.978936
0.963364
self.registry.append((widget, basename, parameters))
def register(self, widget, basename, **parameters)
Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"...
5.542313
7.183408
0.771544
return HttpResponse( self.convert_context_to_json(context), content_type='application/json', **response_kwargs )
def render_to_json_response(self, context, **response_kwargs)
Returns a JSON response, transforming 'context' to make the payload.
2.568584
2.053806
1.250646
for obj in (self.execute().json().get("items") or []): yield self.api_obj_class(self.api, obj)
def iterator(self)
Execute the API request and return an iterator over the objects. This method does not use the query cache.
11.0207
6.764718
1.629144
response = self.get(version="", base="/version") response.raise_for_status() data = response.json() return (data["major"], data["minor"])
def version(self)
Get Kubernetes API version
5.616045
4.505897
1.246377
version = kwargs.pop("version", "v1") if version == "v1": base = kwargs.pop("base", "/api") elif "/" in version: base = kwargs.pop("base", "/apis") else: if "base" not in kwargs: raise TypeError("unknown API version; base kwarg...
def get_kwargs(self, **kwargs)
Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API endpoint
3.706887
3.670803
1.00983
return self.session.request(*args, **self.get_kwargs(**kwargs))
def request(self, *args, **kwargs)
Makes an API request based on arguments. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
5.601411
8.944571
0.626236
return self.session.get(*args, **self.get_kwargs(**kwargs))
def get(self, *args, **kwargs)
Executes an HTTP GET. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
5.863813
8.392553
0.698692
return self.session.options(*args, **self.get_kwargs(**kwargs))
def options(self, *args, **kwargs)
Executes an HTTP OPTIONS. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
8.144148
11.111175
0.732969
return self.session.head(*args, **self.get_kwargs(**kwargs))
def head(self, *args, **kwargs)
Executes an HTTP HEAD. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
6.41939
10.030725
0.639973
return self.session.post(*args, **self.get_kwargs(**kwargs))
def post(self, *args, **kwargs)
Executes an HTTP POST. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
6.590245
9.408467
0.700459
return self.session.put(*args, **self.get_kwargs(**kwargs))
def put(self, *args, **kwargs)
Executes an HTTP PUT. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
6.052427
9.451118
0.640393
return self.session.patch(*args, **self.get_kwargs(**kwargs))
def patch(self, *args, **kwargs)
Executes an HTTP PATCH. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
6.507771
9.624771
0.676148
return self.session.delete(*args, **self.get_kwargs(**kwargs))
def delete(self, *args, **kwargs)
Executes an HTTP DELETE. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments
6.506244
8.964755
0.725758
filename = os.path.expanduser(filename) if not os.path.isfile(filename): raise exceptions.PyKubeError("Configuration file {} not found".format(filename)) with open(filename) as f: doc = yaml.safe_load(f.read()) self = cls(doc, **kwargs) self.filen...
def from_file(cls, filename, **kwargs)
Creates an instance of the KubeConfig class from a kubeconfig file. :Parameters: - `filename`: The full path to the configuration file
2.671562
3.132702
0.852798
doc = { "clusters": [ { "name": "self", "cluster": { "server": url, }, }, ], "contexts": [ { "name": "self", ...
def from_url(cls, url, **kwargs)
Creates an instance of the KubeConfig class from a single URL (useful for interacting with kubectl proxy).
3.097856
2.236976
1.384841
if not hasattr(self, "_clusters"): cs = {} for cr in self.doc["clusters"]: cs[cr["name"]] = c = copy.deepcopy(cr["cluster"]) if "server" not in c: c["server"] = "http://localhost" BytesOrFile.maybe_set(c, "certi...
def clusters(self)
Returns known clusters by exposing as a read-only property.
6.495685
5.869808
1.106626
if not hasattr(self, "_users"): us = {} if "users" in self.doc: for ur in self.doc["users"]: us[ur["name"]] = u = copy.deepcopy(ur["user"]) BytesOrFile.maybe_set(u, "client-certificate") BytesOrFile.mayb...
def users(self)
Returns known users by exposing as a read-only property.
4.635858
4.279012
1.083394
if not hasattr(self, "_contexts"): cs = {} for cr in self.doc["contexts"]: cs[cr["name"]] = copy.deepcopy(cr["context"]) self._contexts = cs return self._contexts
def contexts(self)
Returns known contexts by exposing as a read-only property.
4.473895
3.935567
1.136785
return self.users.get(self.contexts[self.current_context].get("user", ""), {})
def user(self)
Returns the current user set by current context
12.732038
8.380587
1.51923
if self._filename: with open(self._filename, "rb") as f: return f.read() else: return self._bytes
def bytes(self)
Returns the provided data as bytes.
3.36892
2.872238
1.172925
if self._filename: return self._filename else: with tempfile.NamedTemporaryFile(delete=False) as f: f.write(self._bytes) return f.name
def filename(self)
Returns the provided data as a file location.
3.249624
2.720655
1.194427
resource_list = api.resource_list(api_version) resource = next((resource for resource in resource_list["resources"] if resource["kind"] == kind), None) base = NamespacedAPIObject if resource["namespaced"] else APIObject return type(kind, (base,), { "version": api_version, "endpoint"...
def object_factory(api, api_version, kind)
Dynamically builds a Python class for the given Kubernetes object in an API. For example: api = pykube.HTTPClient(...) NetworkPolicy = pykube.object_factory(api, "networking.k8s.io/v1", "NetworkPolicy") This enables construction of any Kubernetes object kind without explicit support from ...
3.721412
4.125898
0.901964
if target_revision is None: revision = {} else: revision = { "revision": target_revision } params = { "kind": "DeploymentRollback", "apiVersion": self.version, "name": self.name, "rollba...
def rollout_undo(self, target_revision=None)
Produces same action as kubectl rollout undo deployment command. Input variable is revision to rollback to (in kubectl, --to-revision)
3.210568
3.040935
1.055783
log_call = "log" params = {} if container is not None: params["container"] = container if pretty is not None: params["pretty"] = pretty if previous: params["previous"] = "true" if since_seconds is not None and since_time is Non...
def logs(self, container=None, pretty=None, previous=False, since_seconds=None, since_time=None, timestamps=False, tail_lines=None, limit_bytes=None)
Produces the same result as calling kubectl logs pod/<pod-name>. Check parameters meaning at http://kubernetes.io/docs/api-reference/v1/operations/, part 'read log of the specified Pod'. The result is plain text.
1.883352
1.88621
0.998485
while self.running['restart_thread']: try: endpoint = self.restart_q.get(timeout=.5) except TimeoutError: continue log.info("_restart_thread(): Restarting Thread for endpoint %s", endpoint) self.unsubsc...
def _restart_thread(self)
Restarts subscription threads if their connection drops. :return:
5.87137
5.813797
1.009903
try: conn = create_connection(self.addr + endpoint, timeout=5) except WebSocketTimeoutException: self.restart_q.put(endpoint) return while self.threads_running[endpoint]: try: msg = conn.recv() except WebSocket...
def _subscription_thread(self, endpoint)
Thread Method, running the connection for each endpoint. :param endpoint: :return:
5.323078
5.208319
1.022034
log.info("WSSAPI.start(): Starting Basic Facilities") self.running = True if self._controller_thread is None or not self._controller_thread.is_alive(): self._controller_thread = Thread(target=self._controller, daemon=True, ...
def start(self)
Starts threads. Extend this in your child class. :return:
5.26883
5.160657
1.020961
while self.running: try: cmd = self._controller_q.get(timeout=1) except (TimeoutError, Empty): continue log.debug("WSSAPI._controller(): Received command: %s", cmd) Thread(target=self.eval_command, args=(cmd,)).start()
def _controller(self)
This method runs in a dedicated thread, calling self.eval_command(). :return:
5.196097
4.340761
1.197048
if cmd == 'restart': self.restart() elif cmd == 'stop': self.stop() else: raise ValueError("Unknown Command passed to controller! %s" % cmd)
def eval_command(self, cmd)
Evaluates commands issued by internal threads. Extend this as necessary. :param cmd: :return:
5.180481
5.459244
0.948937
def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: r = func(*args, **kwargs) except Exception: log.exception("return_api_response(): Error during call to %s(%s, %s)", func.__name__, args, kwa...
def return_api_response(formatter=None)
Decorator, which Applies the referenced formatter (if available) to the function output and adds it to the APIResponse Object's `formatted` attribute. :param formatter: bitex.formatters.Formatter() obj :return: bitex.api.response.APIResponse()
2.971254
2.888549
1.028632
# There are some exceptions from the general formatting rule # see https://api.kraken.com/0/public/AssetPairs format_exceptions = ['BCHEUR', 'BCHUSD', 'BCHXBT', 'DASHEUR', 'DASHUSD', 'DASHXBT', 'EOSETH', 'EOSXBT', 'GNOETH', 'GNOXBT', 'USDTZUSD'] if input_pair.upper() in format_e...
def format_pair(input_pair)
Formats input to conform with kraken pair format. The API expects one of two formats: XBTXLT or XXBTXLTC Where crypto currencies have an X prepended, and fiat currencies have a Z prepended. Since the API returns the 8 character format, that's what we will format ...
2.662906
2.063657
1.290382
nonce = str(int(time.time() * 1000)) package = {'apikey': self.key, 'message': {'nonce': nonce, 'payload': payload}} signature = hmac.new(self.secret, json.dumps(payload).hexdigest, hashlib.sha512).hexdigest() package['signature']...
def sign(self, payload)
Signature method which wraps signature and nonce parameters around a payload dictionary. :param payload: :return:
3.872504
4.135823
0.936332
super(BitstampWSS, self).start() self.pusher = pusherclient.Pusher(self.addr, **self.__pusher_options) self.pusher.connection.bind('pusher:connection_established', self._register_bindings) self.pusher.connect()
def start(self)
Extension of Pusher.connect() method, which registers all callbacks with the relevant channels, before initializing a connection. :return:
5.320473
5.354642
0.993619
self._register_diff_order_book_channels() self._register_live_orders_channels() self._register_live_trades_channels() self._register_order_book_channels()
def _register_bindings(self, data)
connection_handler method which is called when we connect to pusher. Responsible for binding callbacks to channels before we connect. :return:
5.275407
4.425334
1.192092
for channel_name in channels: if channel_name in self.channels: channel = self.pusher.subscribe(channel_name) if isinstance(events, list): for event in events: channel.bind(event, channels[channel_name]) ...
def _bind_channels(self, events, channels)
Binds given channel events to callbacks. :param events: str or list :param channels: dict of channel_name: callback_method() pairs :return:
2.34468
2.237894
1.047717
channels = {'live_trades': self.btcusd_lt_callback, 'live_trades_btceur': self.btceur_lt_callback, 'live_trades_eurusd': self.eurusd_lt_callback, 'live_trades_xrpusd': self.xrpusd_lt_callback, 'live_trades_xrpeur': self.xr...
def _register_live_trades_channels(self)
Registers the binding for the live_trades_channels channels. :return:
2.331412
2.267457
1.028206
channels = {'order_book': self.btcusd_ob_callback, 'order_book_btceur': self.btceur_ob_callback, 'order_book_eurusd': self.eurusd_ob_callback, 'order_book_xrpusd': self.xrpusd_ob_callback, 'order_book_xrpeur': self.xrpeur_o...
def _register_order_book_channels(self)
Registers the binding for the order_book channels. :return:
2.523975
2.492804
1.012505
channels = {'diff_order_book': self.btcusd_dob_callback, 'diff_order_book_btceur': self.btceur_dob_callback, 'diff_order_book_eurusd': self.eurusd_dob_callback, 'diff_order_book_xrpusd': self.xrpusd_dob_callback, 'diff_orde...
def _register_diff_order_book_channels(self)
Registers the binding for the diff_order_book channels. :return:
2.4277
2.379951
1.020063
with open(path, 'r') as f: self.key = f.readline().strip() self.secret = f.readline().strip()
def load_key(self, path)
Load key and secret from file. :param path: path to file with first two lines are key, secret respectively
2.680023
2.269225
1.18103
r = requests.request(*args, **kwargs) return APIResponse(r)
def api_request(*args, **kwargs)
Wrapper which converts a requests.Response into our custom APIResponse object :param args: :param kwargs: :return:
5.809351
4.499496
1.291112
url = self.uri return url, {'params': {'test_param': "authenticated_chimichanga"}}
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs)
Dummy Signature creation method. Override this in child. URL is required to be returned, as some Signatures use the url for sig generation, and api calls made must match the address exactly. param url: self.uri + self.version + endpoint (i.e https://api.kraken/0/Depth) param endpoint: ap...
54.724823
58.995899
0.927604