Dataset Viewer
Auto-converted to Parquet Duplicate
sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def __msgc_step3_discontinuity_localization(self): """ Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution """ import scipy start = self._start_time seg = 1 - self.segmentation.astype(np.int8) sel...
Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution
entailment
def __multiscale_gc_lo2hi_run(self): # , pyed): """ Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There...
Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties`
entailment
def __multiscale_gc_hi2lo_run(self): # , pyed): """ Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. The...
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties`
entailment
def __ordered_values_by_indexes(self, data, inds): """ Return values (intensities) by indexes. Used for multiscale graph cut. data = [[0 1 1], [0 2 2], [0 2 2]] inds = [[0 1 2], [3 4 4], [5 4 4]] return: [...
Return values (intensities) by indexes. Used for multiscale graph cut. data = [[0 1 1], [0 2 2], [0 2 2]] inds = [[0 1 2], [3 4 4], [5 4 4]] return: [0, 1, 1, 0, 2, 0] If the data are not consistent, it will take...
entailment
def __hi2lo_multiscale_indexes(self, mask, orig_shape): # , zoom): """ Function computes multiscale indexes of ndarray. mask: Says where is original resolution (0) and where is small resolution (1). Mask is in small resolution. orig_shape: Original shape of input data. ...
Function computes multiscale indexes of ndarray. mask: Says where is original resolution (0) and where is small resolution (1). Mask is in small resolution. orig_shape: Original shape of input data. zoom: Usually number greater then 1 result = [[0 1 2], [3 4 ...
entailment
def interactivity(self, min_val=None, max_val=None, qt_app=None): """ Interactive seed setting with 3d seed editor """ from .seed_editor_qt import QTSeedEditor from PyQt4.QtGui import QApplication if min_val is None: min_val = np.min(self.img) if max...
Interactive seed setting with 3d seed editor
entailment
def set_seeds(self, seeds): """ Function for manual seed setting. Sets variable seeds and prepares voxels for density model. :param seeds: ndarray (0 - nothing, 1 - object, 2 - background, 3 - object just hard constraints, no model training, 4 - background just hard cons...
Function for manual seed setting. Sets variable seeds and prepares voxels for density model. :param seeds: ndarray (0 - nothing, 1 - object, 2 - background, 3 - object just hard constraints, no model training, 4 - background just hard constraints, no model training)
entailment
def run(self, run_fit_model=True): """ Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the model is prepared before :return: """ if run_fit_model: self.fit_model(self.img, self.voxelsize, self...
Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the model is prepared before :return:
entailment
def __set_hard_hard_constraints(self, tdata1, tdata2, seeds): """ it works with seed labels: 0: nothing 1: object 1 - full seeds 2: object 2 - full seeds 3: object 1 - not a training seeds 4: object 2 - not a training seeds """ seeds_mask = (seeds ...
it works with seed labels: 0: nothing 1: object 1 - full seeds 2: object 2 - full seeds 3: object 1 - not a training seeds 4: object 2 - not a training seeds
entailment
def __similarity_for_tlinks_obj_bgr( self, data, voxelsize, # voxels1, voxels2, # seeds, otherfeatures=None ): """ Compute edge values for graph cut tlinks based on image intensity and texture. """ # self.fit_model(data, voxelsize, seed...
Compute edge values for graph cut tlinks based on image intensity and texture.
entailment
def __create_nlinks(self, data, inds=None, boundary_penalties_fcn=None): """ Compute nlinks grid from data shape information. For boundary penalties are data (intensities) values are used. ins: Default is None. Used for multiscale GC. This are indexes of multiscale pixels. Next ...
Compute nlinks grid from data shape information. For boundary penalties are data (intensities) values are used. ins: Default is None. Used for multiscale GC. This are indexes of multiscale pixels. Next example shows one superpixel witn index 2. inds = [ [1 2 2], ...
entailment
def debug_get_reconstructed_similarity( self, data3d=None, voxelsize=None, seeds=None, area_weight=1, hard_constraints=True, return_unariesalt=False, ): """ Use actual model to calculate similarity. If no input is given the last image is used. ...
Use actual model to calculate similarity. If no input is given the last image is used. :param data3d: :param voxelsize: :param seeds: :param area_weight: :param hard_constraints: :param return_unariesalt: :return:
entailment
def debug_show_reconstructed_similarity( self, data3d=None, voxelsize=None, seeds=None, area_weight=1, hard_constraints=True, show=True, bins=20, slice_number=None, ): """ Show tlinks. :param data3d: ndarray with input d...
Show tlinks. :param data3d: ndarray with input data :param voxelsize: :param seeds: :param area_weight: :param hard_constraints: :param show: :param bins: histogram bins number :param slice_number: :return:
entailment
def debug_inspect_node(self, node_msindex): """ Get info about the node. See pycut.inspect_node() for details. Processing is done in temporary shape. :param node_seed: :return: node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds """ return ins...
Get info about the node. See pycut.inspect_node() for details. Processing is done in temporary shape. :param node_seed: :return: node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds
entailment
def debug_interactive_inspect_node(self): """ Call after segmentation to see selected node neighborhood. User have to select one node by click. :return: """ if ( np.sum( np.abs( np.asarray(self.msinds.shape) - np.asarray(sel...
Call after segmentation to see selected node neighborhood. User have to select one node by click. :return:
entailment
def _ssgc_prepare_data_and_run_computation( self, # voxels1, voxels2, hard_constraints=True, area_weight=1, ): """ Setting of data. You need set seeds if you want use hard_constraints. """ # from PyQt4.QtCore import pyqtRemoveInputHook ...
Setting of data. You need set seeds if you want use hard_constraints.
entailment
def resize_to_shape(data, shape, zoom=None, mode="nearest", order=0): """ Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest' """ # @TODO remove...
Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest'
entailment
def seed_zoom(seeds, zoom): """ Smart zoom for sparse matrix. If there is resize to bigger resolution thin line of label could be lost. This function prefers labels larger then zero. If there is only one small voxel in larger volume with zeros it is selected. """ # import scipy # loseeds...
Smart zoom for sparse matrix. If there is resize to bigger resolution thin line of label could be lost. This function prefers labels larger then zero. If there is only one small voxel in larger volume with zeros it is selected.
entailment
def zoom_to_shape(data, shape, dtype=None): """ Zoom data to specific shape. """ import scipy import scipy.ndimage zoomd = np.array(shape) / np.array(data.shape, dtype=np.double) import warnings datares = scipy.ndimage.interpolation.zoom(data, zoomd, order=0, mode="reflect") if da...
Zoom data to specific shape.
entailment
def crop(data, crinfo): """ Crop the data. crop(data, crinfo) :param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]] """ crinfo = fix_crinfo(crinfo) return data[ __int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]), __int_or_none(crinfo[...
Crop the data. crop(data, crinfo) :param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]]
entailment
def combinecrinfo(crinfo1, crinfo2): """ Combine two crinfos. First used is crinfo1, second used is crinfo2. """ crinfo1 = fix_crinfo(crinfo1) crinfo2 = fix_crinfo(crinfo2) crinfo = [ [crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]], [crinfo1[1][0] + crinfo2[1][0],...
Combine two crinfos. First used is crinfo1, second used is crinfo2.
entailment
def crinfo_from_specific_data(data, margin=0): """ Create crinfo of minimum orthogonal nonzero block in input data. :param data: input data :param margin: add margin to minimum block :return: """ # hledáme automatický ořez, nonzero dá indexy logger.debug("crinfo") logger.debug(str(m...
Create crinfo of minimum orthogonal nonzero block in input data. :param data: input data :param margin: add margin to minimum block :return:
entailment
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0): """ Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input im...
Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0]. If crinfo is just series of three numbers, it is used as an...
entailment
def fix_crinfo(crinfo, to="axis"): """ Function recognize order of crinfo and convert it to proper format. """ crinfo = np.asarray(crinfo) if crinfo.shape[0] == 2: crinfo = crinfo.T return crinfo
Function recognize order of crinfo and convert it to proper format.
entailment
def grid_edges(shape, inds=None, return_directions=True): """ Get list of grid edges :param shape: :param inds: :param return_directions: :return: """ if inds is None: inds = np.arange(np.prod(shape)).reshape(shape) # if not self.segparams['use_boundary_penalties'] and \ ...
Get list of grid edges :param shape: :param inds: :param return_directions: :return:
entailment
def gen_grid_2d(shape, voxelsize): """ Generate list of edges for a base grid. """ nr, nc = shape nrm1, ncm1 = nr - 1, nc - 1 # sh = nm.asarray(shape) # calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols) nedges = 0 for direction in range(len(shape)): ...
Generate list of edges for a base grid.
entailment
def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None): """ Write nodes and edges to VTK file :param fname: VTK filename :param nodes: :param edges: :param node_flag: set if this node is really used in output :param edge_flag: set if this flag is used in output :retur...
Write nodes and edges to VTK file :param fname: VTK filename :param nodes: :param edges: :param node_flag: set if this node is really used in output :param edge_flag: set if this flag is used in output :return:
entailment
def add_nodes(self, coors, node_low_or_high=None): """ Add new nodes at the end of the list. """ last = self.lastnode if type(coors) is nm.ndarray: if len(coors.shape) == 1: coors = coors.reshape((1, coors.size)) nadd = coors.shape[0] ...
Add new nodes at the end of the list.
entailment
def add_edges(self, conn, edge_direction, edge_group=None, edge_low_or_high=None): """ Add new edges at the end of the list. :param edge_direction: direction flag :param edge_group: describes group of edges from same low super node and same direction :param edge_low_or_high: zero...
Add new edges at the end of the list. :param edge_direction: direction flag :param edge_group: describes group of edges from same low super node and same direction :param edge_low_or_high: zero for low to low resolution, one for high to high or high to low resolution. It is used to set w...
entailment
def _edge_group_substitution( self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from ): """ Reconnect edges. :param ndid: id of low resolution edges :param nsplit: number of split :param idxs: indexes of low resolution :param sr_tab: :para...
Reconnect edges. :param ndid: id of low resolution edges :param nsplit: number of split :param idxs: indexes of low resolution :param sr_tab: :param ndoffset: :param ed_remove: :param into_or_from: if zero, connection of input edges is done. If one, connection of ...
entailment
def generate_base_grid(self, vtk_filename=None): """ Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return: """ nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize) self.add_nodes(nd) self.add_edges(ed, ed_dir, ...
Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return:
entailment
def split_voxels(self, vtk_filename=None): """ Second step of algorithm :return:() """ self.cache = {} self.stats["t graph 10"] = time.time() - self.start_time self.msi = MultiscaleArray(self.data.shape, block_size=self.nsplit) # old implementation ...
Second step of algorithm :return:()
entailment
def mul_block(self, index, val): """Multiply values in block""" self._prepare_cache_slice(index) self.msinds[self.cache_slice] *= val
Multiply values in block
entailment
def select_from_fv_by_seeds(fv, seeds, unique_cls): """ Tool to make simple feature functions take features from feature array by seeds. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Doe...
Tool to make simple feature functions take features from feature array by seeds. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Does not to be linear. :param unique_cls: number of used seeds ...
entailment
def return_fv_by_seeds(fv, seeds=None, unique_cls=None): """ Return features selected by seeds and unique_cls or selection from features and corresponding seed classes. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :par...
Return features selected by seeds and unique_cls or selection from features and corresponding seed classes. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Does not to be linear. :param uniqu...
entailment
def expand(self, expression): """Expands logical constructions.""" self.logger.debug("expand : expression %s", str(expression)) if not is_string(expression): return expression result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression) res...
Expands logical constructions.
entailment
def get_gutter_client( alias='default', cache=CLIENT_CACHE, **kwargs ): """ Creates gutter clients and memoizes them in a registry for future quick access. Args: alias (str or None): Name of the client. Used for caching. If name is falsy then do not use the cache...
Creates gutter clients and memoizes them in a registry for future quick access. Args: alias (str or None): Name of the client. Used for caching. If name is falsy then do not use the cache. cache (dict): cache to store gutter managers in. **kwargs: kwargs to be passed the Manger ...
entailment
def _modulo(self, decimal_argument): """ The mod operator is prone to floating point errors, so use decimal. 101.1 % 100 >>> 1.0999999999999943 decimal_context.divmod(Decimal('100.1'), 100) >>> (Decimal('1'), Decimal('0.1')) """ _times, remainder = self....
The mod operator is prone to floating point errors, so use decimal. 101.1 % 100 >>> 1.0999999999999943 decimal_context.divmod(Decimal('100.1'), 100) >>> (Decimal('1'), Decimal('0.1'))
entailment
def enabled_for(self, inpt): """ Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for the switch to be enabled. Otherwise, *any* condition needs to be ``True`` for the switch to be enabled. The sw...
Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for the switch to be enabled. Otherwise, *any* condition needs to be ``True`` for the switch to be enabled. The switch state is then checked to see if it is ``GLOB...
entailment
def call(self, inpt): """ Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` i...
Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` is called, with ``inpt`` as the instance an...
entailment
def switches(self): """ List of all switches currently registered. """ results = [ switch for name, switch in self.storage.iteritems() if name.startswith(self.__joined_namespace) ] return results
List of all switches currently registered.
entailment
def switch(self, name): """ Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED`` switch will be with that name. Keyword Arguments: name -- A name of a switch. """ try: ...
Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED`` switch will be with that name. Keyword Arguments: name -- A name of a switch.
entailment
def register(self, switch, signal=signals.switch_registered): ''' Register a switch and persist it to the storage. ''' if not switch.name: raise ValueError('Switch name cannot be blank') switch.manager = self self.__persist(switch) signal.call(switch...
Register a switch and persist it to the storage.
entailment
def verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False): """Central interface to verify interactions. `verify` uses a fluent interface:: verify(<obj>, times=2).<method_name>(<args>) `args` can be as concrete as necessary. Often a catch-all is enough, especi...
Central interface to verify interactions. `verify` uses a fluent interface:: verify(<obj>, times=2).<method_name>(<args>) `args` can be as concrete as necessary. Often a catch-all is enough, especially if you're working with strict mocks, bc they throw at call time on unwanted, unconfigured a...
entailment
def when(obj, strict=None): """Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when(<obj>).<method_...
Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when(<obj>).<method_name>(<args>).thenReturn(<value>) ...
entailment
def when2(fn, *args, **kwargs): """Stub a function call with the given arguments Exposes a more pythonic interface than :func:`when`. See :func:`when` for more documentation. Returns `AnswerSelector` interface which exposes `thenReturn`, `thenRaise`, and `thenAnswer` as usual. Always `strict`. ...
Stub a function call with the given arguments Exposes a more pythonic interface than :func:`when`. See :func:`when` for more documentation. Returns `AnswerSelector` interface which exposes `thenReturn`, `thenRaise`, and `thenAnswer` as usual. Always `strict`. Usage:: # Given `dog` is an ...
entailment
def patch(fn, attr_or_replacement, replacement=None): """Patch/Replace a function. This is really like monkeypatching, but *note* that all interactions will be recorded and can be verified. That is, using `patch` you stay in the domain of mockito. Two ways to call this. Either:: patch(os....
Patch/Replace a function. This is really like monkeypatching, but *note* that all interactions will be recorded and can be verified. That is, using `patch` you stay in the domain of mockito. Two ways to call this. Either:: patch(os.path.exists, lambda str: True) # two arguments # OR ...
entailment
def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None): """Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.ba...
Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.bark('Wuff') # will throw at call time: too many invocations # maybe if you need to ensure th...
entailment
def unstub(*objs): """Unstubs all stubbed methods and functions If you don't pass in any argument, *all* registered mocks and patched modules, classes etc. will be unstubbed. Note that additionally, the underlying registry will be cleaned. After an `unstub` you can't :func:`verify` anymore because...
Unstubs all stubbed methods and functions If you don't pass in any argument, *all* registered mocks and patched modules, classes etc. will be unstubbed. Note that additionally, the underlying registry will be cleaned. After an `unstub` you can't :func:`verify` anymore because all interactions will...
entailment
def verifyZeroInteractions(*objs): """Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations ...
Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets recorded. So thi...
entailment
def verifyNoUnwantedInteractions(*objs): """Verifies that expectations set via `expect` are met E.g.:: expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok, called once If you leave out the argument *all* registered obje...
Verifies that expectations set via `expect` are met E.g.:: expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok, called once If you leave out the argument *all* registered objects will be checked. .. note:: **DANGER...
entailment
def verifyStubbedInvocationsAreUsed(*objs): """Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before :func:`unstub`. """ ...
Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before :func:`unstub`.
entailment
def get_function_host(fn): """Destructure a given function into its host and its name. The 'host' of a function is a module, for methods it is usually its instance or its class. This is safe only for methods, for module wide, globally declared names it must be considered experimental. For all reas...
Destructure a given function into its host and its name. The 'host' of a function is a module, for methods it is usually its instance or its class. This is safe only for methods, for module wide, globally declared names it must be considered experimental. For all reasonable fn: ``getattr(*get_function...
entailment
def get_obj(path): """Return obj for given dotted path. Typical inputs for `path` are 'os' or 'os.path' in which case you get a module; or 'os.path.exists' in which case you get a function from that module. Just returns the given input in case it is not a str. Note: Relative imports not suppo...
Return obj for given dotted path. Typical inputs for `path` are 'os' or 'os.path' in which case you get a module; or 'os.path.exists' in which case you get a function from that module. Just returns the given input in case it is not a str. Note: Relative imports not supported. Raises ImportErr...
entailment
def get_obj_attr_tuple(path): """Split path into (obj, attribute) tuple. Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` If path is not a str, delegates to `get_function_host(path)` """ if not isinstance(path, str): return get_function_host(path) if path.start...
Split path into (obj, attribute) tuple. Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` If path is not a str, delegates to `get_function_host(path)`
entailment
def spy(object): """Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under ...
Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all...
entailment
def spy2(fn): # type: (...) -> None """Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy(time.time) do_...
Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy(time.time) do_work(...) # nothing injected, uses global p...
entailment
def mock(config_or_spec=None, spec=None, strict=OMITTED): """Create 'empty' objects ('Mocks'). Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using :func:`verify` et.al. A plain `mock()` will be not `strict`,...
Create 'empty' objects ('Mocks'). Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using :func:`verify` et.al. A plain `mock()` will be not `strict`, and thus all methods regardless of the arguments will return...
entailment
def importPuppetClasses(self, smartProxyId): """ Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETURN: the API result """ return self.api.create('{}/{}/import_puppetclasses' .form...
Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETURN: the API result
entailment
def get_templates(model): """ Return a list of templates usable by a model. """ for template_name, template in templates.items(): if issubclass(template.model, model): yield (template_name, template.layout._meta.verbose_name)
Return a list of templates usable by a model.
entailment
def attach(*layouts, **kwargs): """ Registers the given layout(s) classes admin site: @pages.register(Page) class Default(PageLayout): pass """ def _model_admin_wrapper(layout_class): register(layout_class, layouts[0]) return layout_class return _model_admin_wra...
Registers the given layout(s) classes admin site: @pages.register(Page) class Default(PageLayout): pass
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTe...
Function enhance Enhance the object with new item or enhanced items
entailment
def get_api_envs(): """Get required API keys from environment variables.""" client_id = os.environ.get('CLIENT_ID') user_id = os.environ.get('USER_ID') if not client_id or not user_id: raise ValueError('API keys are not found in the environment') return client_id, user_id
Get required API keys from environment variables.
entailment
def api_call(method, end_point, params=None, client_id=None, access_token=None): """Call given API end_point with API keys. :param method: HTTP method (e.g. 'get', 'delete'). :param end_point: API endpoint (e.g. 'users/john/sets'). :param params: Dictionary to be sent in the query string (e.g. {'myparam...
Call given API end_point with API keys. :param method: HTTP method (e.g. 'get', 'delete'). :param end_point: API endpoint (e.g. 'users/john/sets'). :param params: Dictionary to be sent in the query string (e.g. {'myparam': 'myval'}) :param client_id: Quizlet client ID as string. :param access_token:...
entailment
def request_upload_secret(self, secret_id): """ :return: json with "keyId" as secret and "url" for posting key """ return self._router.post_request_upload_secret(org_id=self.organizationId, instance_id=self.instanceId, ...
:return: json with "keyId" as secret and "url" for posting key
entailment
def checkAndCreate(self, key, payload, domainId): """ Function checkAndCreate Check if a subnet exists and create it if not @param key: The targeted subnet @param payload: The targeted subnet description @param domainId: The domainId to be attached wiuth the subnet @retu...
Function checkAndCreate Check if a subnet exists and create it if not @param key: The targeted subnet @param payload: The targeted subnet description @param domainId: The domainId to be attached wiuth the subnet @return RETURN: The id of the subnet
entailment
def removeDomain(self, subnetId, domainId): """ Function removeDomain Delete a domain from a subnet @param subnetId: The subnet Id @param domainId: The domainId to be attached wiuth the subnet @return RETURN: boolean """ subnetDomainIds = [] for domain in...
Function removeDomain Delete a domain from a subnet @param subnetId: The subnet Id @param domainId: The domainId to be attached wiuth the subnet @return RETURN: boolean
entailment
def exclusive(via=threading.Lock): """ Mark a callable as exclusive :param via: factory for a Lock to guard the callable Guards the callable against being entered again before completion. Explicitly raises a :py:exc:`RuntimeError` on violation. :note: If applied to a method, it is exclusive a...
Mark a callable as exclusive :param via: factory for a Lock to guard the callable Guards the callable against being entered again before completion. Explicitly raises a :py:exc:`RuntimeError` on violation. :note: If applied to a method, it is exclusive across all instances.
entailment
def service(flavour): r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit...
r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit has been :py:meth:`~.Serv...
entailment
def execute(self, payload, *args, flavour: ModuleType, **kwargs): """ Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. """ if args or kwargs: payload = functools.partial(payl...
Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
entailment
def adopt(self, payload, *args, flavour: ModuleType, **kwargs): """ Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. """ if args or kwargs: payload = functools.partial(payload, *ar...
Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
entailment
def accept(self): """ Start accepting synchronous, asynchronous and service payloads Since services are globally defined, only one :py:class:`ServiceRunner` may :py:meth:`accept` payloads at any time. """ if self._meta_runner: raise RuntimeError('payloads sch...
Start accepting synchronous, asynchronous and service payloads Since services are globally defined, only one :py:class:`ServiceRunner` may :py:meth:`accept` payloads at any time.
entailment
def shutdown(self): """Shutdown the accept loop and stop running payloads""" self._must_shutdown = True self._is_shutdown.wait() self._meta_runner.stop()
Shutdown the accept loop and stop running payloads
entailment
def milestones(ctx, list, close): """View/edit/close milestones on github """ repos = get_repos(ctx.parent.agile.get('labels')) if list: _list_milestones(repos) elif close: click.echo('Closing milestones "%s"' % close) _close_milestone(repos, close) else: click.ec...
View/edit/close milestones on github
entailment
def start_console(local_vars={}): '''Starts a console; modified from code.interact''' transforms.CONSOLE_ACTIVE = True transforms.remove_not_allowed_in_console() sys.ps1 = prompt console = ExperimentalInteractiveConsole(locals=local_vars) console.interact(banner=banner)
Starts a console; modified from code.interact
entailment
def push(self, line): """Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as...
Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicat...
entailment
def dump(obj, f, preserve=False): """Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optional flag to preserve the inline table in result """ if not f.write: raise TypeError('You can only dump an object into a file obj...
Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optional flag to preserve the inline table in result
entailment
def dumps(obj, preserve=False): """Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result """ f = StringIO() dump(obj, f, preserve) return f.getvalue()
Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result
entailment
def license_loader(lic_dir=LIC_DIR): """Loads licenses from the given directory.""" lics = [] for ln in os.listdir(lic_dir): lp = os.path.join(lic_dir, ln) with open(lp) as lf: txt = lf.read() lic = License(txt) lics.append(lic) return lics
Loads licenses from the given directory.
entailment
def get_vector(self, max_choice=3): """Return pseudo-choice vectors.""" vec = {} for dim in ['forbidden', 'required', 'permitted']: if self.meta[dim] is None: continue dim_vec = map(lambda x: (x, max_choice), self.meta[dim]) vec[dim] = dict(dim...
Return pseudo-choice vectors.
entailment
def entity(ctx, debug, uncolorize, **kwargs): """ CLI for tonomi.com using contrib-python-qubell-client To enable completion: eval "$(_NOMI_COMPLETE=source nomi)" """ global PROVIDER_CONFIG if debug: log.basicConfig(level=log.DEBUG) log.getLogger("requests.packages.urlli...
CLI for tonomi.com using contrib-python-qubell-client To enable completion: eval "$(_NOMI_COMPLETE=source nomi)"
entailment
def import_app(files, category, overwrite, id, name): """ Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is prov...
Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is provided, looks up existing application and updates its manifest. ...
entailment
def show_account(): """ Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization. """ click.echo("# tonomi api") for (key, env) in REVERSE_MAPPING.items(): value = QUBELL.get(key, None) if value: ...
Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization.
entailment
def generate_session_token(refresh_token, verbose): """ Generates new session token from the given refresh token. :param refresh_token: refresh token to generate from :param verbose: whether expiration time should be added to output """ platform = _get_platform(authenticated=False) session_...
Generates new session token from the given refresh token. :param refresh_token: refresh token to generate from :param verbose: whether expiration time should be added to output
entailment
def runcommand(cosmology='WMAP5'): """ Example interface commands """ # Return the WMAP5 cosmology concentration predicted for # z=0 range of masses Mi = [1e8, 1e9, 1e10] zi = 0 print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi)) output = commah.run(cosmology=cosmology, zi=zi, ...
Example interface commands
entailment
def plotcommand(cosmology='WMAP5', plotname=None): """ Example ways to interrogate the dataset and plot the commah output """ # Plot the c-M relation as a functon of redshift xarray = 10**(np.arange(1, 15, 0.2)) yval = 'c' # Specify the redshift range zarray = np.arange(0, 5, 0.5) xtitle ...
Example ways to interrogate the dataset and plot the commah output
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'puppetclasses': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemPuppetClasses)}) ...
Function enhance Enhance the object with new item or enhanced items
entailment
def add_transformers(line): '''Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict ''' assert FROM_EXPERIMENTAL.match(line) line = FROM_EXPERIMENTAL.sub(' ', line) # we now have: " tra...
Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict
entailment
def import_transformer(name): '''If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module impo...
If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module import do its job - which is faste...
entailment
def extract_transformers_from_source(source): '''Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed. ''' ...
Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed.
entailment
def remove_not_allowed_in_console(): '''This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove them and print an information message specific to that tr...
This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove them and print an information message specific to that transformer as written in the transformer ...
entailment
def transform(source): '''Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transformers (for example, those found in the standard library ...
Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transformers (for example, those found in the standard library module lib2to3) cannot cop...
entailment
def _match(self, request, response): """Match all requests/responses that satisfy the following conditions: * An Admin App; i.e. the path is something like /admin/some_app/ * The ``include_flag`` is not in the response's content """ is_html = 'text/html' in response.get('Conten...
Match all requests/responses that satisfy the following conditions: * An Admin App; i.e. the path is something like /admin/some_app/ * The ``include_flag`` is not in the response's content
entailment
def _chosen_css(self): """Read the minified CSS file including STATIC_URL in the references to the sprite images.""" css = render_to_string(self.css_template, {}) for sprite in self.chosen_sprites: # rewrite path to sprites in the css css = css.replace(sprite, settings.STATI...
Read the minified CSS file including STATIC_URL in the references to the sprite images.
entailment
def _embed(self, request, response): """Embed Chosen.js directly in html of the response.""" if self._match(request, response): # Render the <link> and the <script> tags to include Chosen. head = render_to_string( "chosenadmin/_head_css.html", {"ch...
Embed Chosen.js directly in html of the response.
entailment
def clean_up(self): """ Close the I2C bus """ self.log.debug("Closing I2C bus for address: 0x%02X" % self.address) self.bus.close()
Close the I2C bus
entailment
def write_quick(self): """ Send only the read / write bit """ self.bus.write_quick(self.address) self.log.debug("write_quick: Sent the read / write bit")
Send only the read / write bit
entailment
def write_byte(self, cmd, value): """ Writes an 8-bit byte to the specified command register """ self.bus.write_byte_data(self.address, cmd, value) self.log.debug( "write_byte: Wrote 0x%02X to command register 0x%02X" % ( value, cmd ) ...
Writes an 8-bit byte to the specified command register
entailment
def write_word(self, cmd, value): """ Writes a 16-bit word to the specified command register """ self.bus.write_word_data(self.address, cmd, value) self.log.debug( "write_word: Wrote 0x%04X to command register 0x%02X" % ( value, cmd ) ...
Writes a 16-bit word to the specified command register
entailment
def write_raw_byte(self, value): """ Writes an 8-bit byte directly to the bus """ self.bus.write_byte(self.address, value) self.log.debug("write_raw_byte: Wrote 0x%02X" % value)
Writes an 8-bit byte directly to the bus
entailment
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
11