sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def atualizar_software_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('atualizarsoftwaresat') conteudo = resp.json() return Res...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
entailment
def extrair_logs(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.extrair_logs`. :return: Uma resposta SAT especializada em ``ExtrairLogs``. :rtype: satcfe.resposta.extrairlogs.RespostaExtrairLogs """ resp = self._http_post('extrairlogs') conteudo = resp.json() ...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.extrair_logs`. :return: Uma resposta SAT especializada em ``ExtrairLogs``. :rtype: satcfe.resposta.extrairlogs.RespostaExtrairLogs
entailment
def bloquear_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('bloquearsat') conteudo = resp.json() return RespostaSAT.bloquear_sat(conteud...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
entailment
def desbloquear_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('desbloquearsat') conteudo = resp.json() return RespostaSAT.desbloquear...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
entailment
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSA...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
entailment
def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the bounds property in relative coordinates. Bounds is a tuple ((top, left), (height, width))""" ...
Return the bounds property in relative coordinates. Bounds is a tuple ((top, left), (height, width))
entailment
def end(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None: """Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.""" ...
Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.
entailment
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None: """Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.""" ...
Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.
entailment
def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the vector property in relative coordinates. Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end)).""" ...
Return the vector property in relative coordinates. Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end)).
entailment
def get_data_item_for_hardware_source(self, hardware_source, channel_id: str=None, processor_id: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem: """Get the data item associated with hardware source and (optional) channel id and processor_id. Optionally create if missing. ...
Get the data item associated with hardware source and (optional) channel id and processor_id. Optionally create if missing. :param hardware_source: The hardware_source. :param channel_id: The (optional) channel id. :param processor_id: The (optional) processor id for the channel. :param...
entailment
def get_data_item_for_reference_key(self, data_item_reference_key: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem: """Get the data item associated with data item reference key. Optionally create if missing. :param data_item_reference_key: The data item reference key. ...
Get the data item associated with data item reference key. Optionally create if missing. :param data_item_reference_key: The data item reference key. :param create_if_needed: Whether to create a new data item if none is found. :return: The associated data item. May be None. .. versiona...
entailment
def show_get_string_message_box(self, caption: str, text: str, accepted_fn, rejected_fn=None, accepted_text: str=None, rejected_text: str=None) -> None: """Show a dialog box and ask for a string. Caption describes the user prompt. Text is the initial/default string. Accepted function must be a...
Show a dialog box and ask for a string. Caption describes the user prompt. Text is the initial/default string. Accepted function must be a function taking one argument which is the resulting text if the user accepts the message dialog. It will only be called if the user clicks OK. Rej...
entailment
def create_calibration(self, offset: float=None, scale: float=None, units: str=None) -> Calibration.Calibration: """Create a calibration object with offset, scale, and units. :param offset: The offset of the calibration. :param scale: The scale of the calibration. :param units: The unit...
Create a calibration object with offset, scale, and units. :param offset: The offset of the calibration. :param scale: The scale of the calibration. :param units: The units of the calibration as a string. :return: The calibration object. .. versionadded:: 1.0 Scriptabl...
entailment
def create_data_and_metadata(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None, data_descriptor: DataAndMetadata.DataDescriptor=None) -> DataAndMetadata.DataAndMetadata: ""...
Create a data_and_metadata object from data. :param data: an ndarray of data. :param intensity_calibration: An optional calibration object. :param dimensional_calibrations: An optional list of calibration objects. :param metadata: A dict of metadata. :param timestamp: A datetime...
entailment
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata: """Create a data_and_metadata object from data...
Create a data_and_metadata object from data. .. versionadded:: 1.0 .. deprecated:: 1.1 Use :py:meth:`~nion.swift.Facade.DataItem.create_data_and_metadata` instead. Scriptable: No
entailment
def create_data_descriptor(self, is_sequence: bool, collection_dimension_count: int, datum_dimension_count: int) -> DataAndMetadata.DataDescriptor: """Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number...
Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number of collection dimensions represented by the descriptor. :param datum_dimension_count: the number of datum dimensions represented by the descriptor. ...
entailment
def make_calibration_row_widget(ui, calibration_observable, label: str=None): """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.""" calibration_row = ui.create_row_widget() row_label = ui.create_label_widget(label, properties={"width": 60}) row_label.widg...
Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.
entailment
def add_widget_to_content(self, widget): """Subclasses should call this to add content in the section's top level column.""" self.__section_content_column.add_spacing(4) self.__section_content_column.add(widget)
Subclasses should call this to add content in the section's top level column.
entailment
def __create_list_item_widget(self, ui, calibration_observable): """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.""" calibration_row = make_calibration_row_widget(ui, calibration_observable) column = ui.create_column_widget() column.add_...
Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.
entailment
def _repaint(self, drawing_context): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size[1] canvas_height = self.canvas_size[0] left = self.display_limits[0] right = self.display_limits[1] # draw left displa...
Repaint the canvas item. This will occur on a thread.
entailment
def _repaint(self, drawing_context): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size[1] canvas_height = self.canvas_size[0] # draw background if self.background_color: with drawing_context.saver(): ...
Repaint the canvas item. This will occur on a thread.
entailment
def color_map_data(self, data: numpy.ndarray) -> None: """Set the data and mark the canvas item for updating. Data should be an ndarray of shape (256, 3) with type uint8 """ self.__color_map_data = data self.update()
Set the data and mark the canvas item for updating. Data should be an ndarray of shape (256, 3) with type uint8
entailment
def _repaint(self, drawing_context: DrawingContext.DrawingContext): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size.width canvas_height = self.canvas_size.height with drawing_context.saver(): if self.__color_...
Repaint the canvas item. This will occur on a thread.
entailment
def get_params(self): "Parameters used to initialize the class" import inspect a = inspect.getargspec(self.__init__)[0] out = dict() for key in a[1:]: value = getattr(self, "_%s" % key, None) out[key] = value return out
Parameters used to initialize the class
entailment
def signature(self): "Instance file name" kw = self.get_params() keys = sorted(kw.keys()) l = [] for k in keys: n = k[0] + k[-1] v = kw[k] if k == 'function_set': v = "_".join([x.__name__[0] + x.__n...
Instance file name
entailment
def population(self): "Class containing the population and all the individuals generated" try: return self._p except AttributeError: self._p = self._population_class(base=self, tournament_size=self._tournament_size, ...
Class containing the population and all the individuals generated
entailment
def random_leaf(self): "Returns a random variable with the associated weight" for i in range(self._number_tries_feasible_ind): var = np.random.randint(self.nvar) v = self._random_leaf(var) if v is None: continue return v raise Runti...
Returns a random variable with the associated weight
entailment
def random_offspring(self): "Returns an offspring with the associated weight(s)" function_set = self.function_set function_selection = self._function_selection_ins function_selection.density = self.population.density function_selection.unfeasible_functions.clear() for i i...
Returns an offspring with the associated weight(s)
entailment
def stopping_criteria(self): "Test whether the stopping criteria has been achieved." if self.stopping_criteria_tl(): return True if self.generations < np.inf: inds = self.popsize * self.generations flag = inds <= len(self.population.hist) else: ...
Test whether the stopping criteria has been achieved.
entailment
def nclasses(self, v): "Number of classes of v, also sets the labes" if not self.classifier: return 0 if isinstance(v, list): self._labels = np.arange(len(v)) return if not isinstance(v, np.ndarray): v = tonparray(v) self._labels = ...
Number of classes of v, also sets the labes
entailment
def fit(self, X, y, test_set=None): """Evolutive process""" self._init_time = time.time() self.X = X if self._popsize == "nvar": self._popsize = self.nvar + len(self._input_functions) if isinstance(test_set, str) and test_set == 'shuffle': test_set = self....
Evolutive process
entailment
def decision_function(self, v=None, X=None): "Decision function i.e. the raw data of the prediction" m = self.model(v=v) return m.decision_function(X)
Decision function i.e. the raw data of the prediction
entailment
def predict(self, v=None, X=None): """In classification this returns the classes, in regression it is equivalent to the decision function""" if X is None: X = v v = None m = self.model(v=v) return m.predict(X)
In classification this returns the classes, in regression it is equivalent to the decision function
entailment
def serve(application, host='127.0.0.1', port=8080): """Gevent-based WSGI-HTTP server.""" # Instantiate the server with a host/port configuration and our application. WSGIServer((host, int(port)), application).serve_forever()
Gevent-based WSGI-HTTP server.
entailment
def get_subscribers(obj): """ Returns the subscribers for a given object. :param obj: Any object. """ ctype = ContentType.objects.get_for_model(obj) return Subscription.objects.filter(content_type=ctype, object_id=obj.pk)
Returns the subscribers for a given object. :param obj: Any object.
entailment
def is_subscribed(user, obj): """ Returns ``True`` if the user is subscribed to the given object. :param user: A ``User`` instance. :param obj: Any object. """ if not user.is_authenticated(): return False ctype = ContentType.objects.get_for_model(obj) try: Subscriptio...
Returns ``True`` if the user is subscribed to the given object. :param user: A ``User`` instance. :param obj: Any object.
entailment
def _promote(self, name, instantiate=True): """Create a new subclass of Context which incorporates instance attributes and new descriptors. This promotes an instance and its instance attributes up to being a class with class attributes, then returns an instance of that class. """ metaclass = type(self._...
Create a new subclass of Context which incorporates instance attributes and new descriptors. This promotes an instance and its instance attributes up to being a class with class attributes, then returns an instance of that class.
entailment
def run_individual(sim_var, reference, neuroml_file, nml_doc, still_included, generate_dir, target, sim_time, dt, simulator, cl...
Run an individual simulation. The candidate data has been flattened into the sim_var dict. The sim_var dict contains parameter:value key value pairs, which are applied to the model before it is simulated.
entailment
def run(self,candidates,parameters): """ Run simulation for each candidate This run method will loop through each candidate and run the simulation corresponding to its parameter values. It will populate an array called traces with the resulting voltage traces for the sim...
Run simulation for each candidate This run method will loop through each candidate and run the simulation corresponding to its parameter values. It will populate an array called traces with the resulting voltage traces for the simulation and return it.
entailment
def prepare(self, context): """Executed prior to processing a request.""" if __debug__: log.debug("Assigning thread local request context.") self.local.context = context
Executed prior to processing a request.
entailment
def register(self, kind, handler): """Register a handler for a given type, class, interface, or abstract base class. View registration should happen within the `start` callback of an extension. For example, to register the previous `json` view example: class JSONExtension: def start(self, context): ...
Register a handler for a given type, class, interface, or abstract base class. View registration should happen within the `start` callback of an extension. For example, to register the previous `json` view example: class JSONExtension: def start(self, context): context.view.register(tuple, json) ...
entailment
def static(base, mapping=None, far=('js', 'css', 'gif', 'jpg', 'jpeg', 'png', 'ttf', 'woff')): """Serve files from disk. This utility endpoint factory is meant primarily for use in development environments; in production environments it is better (more efficient, secure, etc.) to serve your static content using a ...
Serve files from disk. This utility endpoint factory is meant primarily for use in development environments; in production environments it is better (more efficient, secure, etc.) to serve your static content using a front end load balancer such as Nginx. The first argument, `base`, represents the base path to ...
entailment
def serve(application, host='127.0.0.1', port=8080): """Diesel-based (greenlet) WSGI-HTTP server. As a minor note, this is crazy. Diesel includes Flask, too. """ # Instantiate the server with a host/port configuration and our application. WSGIApplication(application, port=int(port), iface=host).run()
Diesel-based (greenlet) WSGI-HTTP server. As a minor note, this is crazy. Diesel includes Flask, too.
entailment
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A script for plotting files containing spike time data") parser.add_argument('spiketimeFiles', type=str, metavar='<spiketime file>', ...
Parse command-line arguments.
entailment
def simple(application, host='127.0.0.1', port=8080): """Python-standard WSGI-HTTP server for testing purposes. The additional work performed here is to match the default startup output of "waitress". This is not a production quality interface and will be have badly under load. """ # Try to be handy as many ...
Python-standard WSGI-HTTP server for testing purposes. The additional work performed here is to match the default startup output of "waitress". This is not a production quality interface and will be have badly under load.
entailment
def iiscgi(application): """A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks. This is not a production quality interface and will behave badly under load. """ try: from wsgiref.handlers import IISCGIHandler except ImportError: print("Python 3.2 or newer is required.") ...
A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks. This is not a production quality interface and will behave badly under load.
entailment
def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. """ # Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (ho...
Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details.
entailment
def _get_method_kwargs(self): """ Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object. """ method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content...
Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object.
entailment
def save(self, *args, **kwargs): """Adds a subscription for the given user to the given object.""" method_kwargs = self._get_method_kwargs() try: subscription = Subscription.objects.get(**method_kwargs) except Subscription.DoesNotExist: subscription = Subscription...
Adds a subscription for the given user to the given object.
entailment
def prepare(self, context): """Add the usual suspects to the context. This adds `request`, `response`, and `path` to the `RequestContext` instance. """ if __debug__: log.debug("Preparing request context.", extra=dict(request=id(context))) # Bridge in WebOb `Request` and `Response` objects. # Ext...
Add the usual suspects to the context. This adds `request`, `response`, and `path` to the `RequestContext` instance.
entailment
def dispatch(self, context, consumed, handler, is_endpoint): """Called as dispatch descends into a tier. The base extension uses this to maintain the "current url". """ request = context.request if __debug__: log.debug("Handling dispatch event.", extra=dict( request = id(context), consum...
Called as dispatch descends into a tier. The base extension uses this to maintain the "current url".
entailment
def render_none(self, context, result): """Render empty responses.""" context.response.body = b'' del context.response.content_length return True
Render empty responses.
entailment
def render_binary(self, context, result): """Return binary responses unmodified.""" context.response.app_iter = iter((result, )) # This wraps the binary string in a WSGI body iterable. return True
Return binary responses unmodified.
entailment
def render_file(self, context, result): """Perform appropriate metadata wrangling for returned open file handles.""" if __debug__: log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result))) response = context.response response.conditional_response = True modified ...
Perform appropriate metadata wrangling for returned open file handles.
entailment
def render_generator(self, context, result): """Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions, which are generators, as returned views. """ context.response.encoding = 'utf8' context.response.app_iter = ( (i.encode('utf8') if isinst...
Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions, which are generators, as returned views.
entailment
def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server.""" # Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on ...
CherryPy-based WSGI-HTTP server.
entailment
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): '''Returns the colored string''' if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one name...
Returns the colored string
entailment
def render_serialization(self, context, result): """Render serialized responses.""" resp = context.response serial = context.serialize match = context.request.accept.best_match(serial.types, default_match=self.default) result = serial[match](result) if isinstance(result, str): result = result.decod...
Render serialized responses.
entailment
def serve(application, host='127.0.0.1', port=8080): """Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/). """ # Instantiate the server with a bound port and with our application. server(listen(host, int(port)), app...
Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/).
entailment
def main(args=None): """Main""" vs = [(v-100)*0.001 for v in range(200)] for f in ['IM.channel.nml','Kd.channel.nml']: nml_doc = pynml.read_neuroml2_file(f) for ct in nml_doc.ComponentType: ys = [] for v in vs: req_variables = {'v':'%sV'%v,...
Main
entailment
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to generate a LEMS " "file to analyse the behaviour of channels in " "NeuroML 2")) parser.ad...
Parse command-line arguments.
entailment
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs): """A single IV curve""" grid = plt_kwargs.pop('grid',True) same_fig = plt_kwargs.pop('same_fig',False) if not len(plt_args): plt_args = ('ko-',) if 'label' not in plt_kwargs: plt_kwargs['label'] = 'Current' if not sa...
A single IV curve
entailment
def root(context): """Multipart AJAX request example. See: http://test.getify.com/mpAjax/description.html """ response = context.response parts = [] for i in range(12): for j in range(12): parts.append(executor.submit(mul, i, j)) def stream(parts, timeout=None): try: for future in as_complete...
Multipart AJAX request example. See: http://test.getify.com/mpAjax/description.html
entailment
def render_template_with_args_in_file(file, template_file_name, **kwargs): """ Get a file and render the content of the template_file_name with kwargs in a file :param file: A File Stream to write :param template_file_name: path to route with template name :param **kwargs: Args to be rendered in tem...
Get a file and render the content of the template_file_name with kwargs in a file :param file: A File Stream to write :param template_file_name: path to route with template name :param **kwargs: Args to be rendered in template
entailment
def create_or_open(file_name, initial_template_file_name, args): """ Creates a file or open the file with file_name name :param file_name: String with a filename :param initial_template_file_name: String with path to initial template :param args: from console to determine path to save the files ...
Creates a file or open the file with file_name name :param file_name: String with a filename :param initial_template_file_name: String with path to initial template :param args: from console to determine path to save the files
entailment
def generic_insert_module(module_name, args, **kwargs): """ In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template """ file = create_or_open( ...
In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template
entailment
def sanity_check(args): """ Verify if the work folder is a django app. A valid django app always must have a models.py file :return: None """ if not os.path.isfile( os.path.join( args['django_application_folder'], 'models.py' ) ): print("django...
Verify if the work folder is a django app. A valid django app always must have a models.py file :return: None
entailment
def generic_insert_with_folder(folder_name, file_name, template_name, args): """ In general if we need to put a file on a folder, we use this method """ # First we make sure views are a package instead a file if not os.path.isdir( os.path.join( args['django_application_folder'], ...
In general if we need to put a file on a folder, we use this method
entailment
def serve(application, host='127.0.0.1', port=8080, threads=4, **kw): """The recommended development HTTP server. Note that this server performs additional buffering and will not honour chunked encoding breaks. """ # Bind and start the server; this is a blocking process. serve_(application, host=host, port=int...
The recommended development HTTP server. Note that this server performs additional buffering and will not honour chunked encoding breaks.
entailment
def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt...
Plot the result of the simulation once it's been intialized
entailment
def mul(self, a: int = None, b: int = None) -> 'json': """Multiply two values together and return the result via JSON. Python 3 function annotations are used to ensure that the arguments are integers. This requires the functionality of `web.ext.annotation:AnnotationExtension`. There are several ways to ex...
Multiply two values together and return the result via JSON. Python 3 function annotations are used to ensure that the arguments are integers. This requires the functionality of `web.ext.annotation:AnnotationExtension`. There are several ways to execute this method: * POST http://localhost:8080/mul *...
entailment
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1): '''Returns the colored string to print on the terminal. This function detects the terminal type and if it is supported and the output is not going to a pipe or a file, then it will return the colored string, otherwise it will retur...
Returns the colored string to print on the terminal. This function detects the terminal type and if it is supported and the output is not going to a pipe or a file, then it will return the colored string, otherwise it will return the string without modifications. string = the string to print. Only acc...
entailment
def mutate(self, context, handler, args, kw): """Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be freely modified, though invalid arguments to the handler will fail. """ def cast(arg, val): if arg not in annotations: return cast = annotations[...
Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be freely modified, though invalid arguments to the handler will fail.
entailment
def transform(self, context, handler, result): """Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation. """ handler = handler.__func__ if hasattr(handler, '__func__') else handler annotation = getattr(handler, '__ann...
Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation.
entailment
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!")) parser.add_argument('prefix', ...
Parse command-line arguments.
entailment
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with cell activity (e.g. as generated from a neuroConstruct simulation)") parser.add_argument('prefix', ...
Parse command-line arguments.
entailment
def serve(application, host='127.0.0.1', port=8080, **options): """Tornado's HTTPServer. This is a high quality asynchronous server with many options. For details, please visit: http://www.tornadoweb.org/en/stable/httpserver.html#http-server """ # Wrap our our WSGI application (potentially stack) in a Torn...
Tornado's HTTPServer. This is a high quality asynchronous server with many options. For details, please visit: http://www.tornadoweb.org/en/stable/httpserver.html#http-server
entailment
def parse_arguments(): """Parse command line arguments""" import argparse parser = argparse.ArgumentParser( description=('pyNeuroML v%s: Python utilities for NeuroML2' % __version__ + "\n libNeuroML v%s"%(neuroml.__version__) + "\n jNe...
Parse command line arguments
entailment
def quick_summary(nml2_doc): ''' Or better just use nml2_doc.summary(show_includes=False) ''' info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id membs = inspect.getmembers(nml2_doc) for memb in membs: if isinstance(memb[1], list) and len(memb[1])>0 \ and not...
Or better just use nml2_doc.summary(show_includes=False)
entailment
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'], prefix="Output: ", env=None): """Execute a command in specific working directory""" if os.name == 'nt': directory = os.path.normpath(directory) print_comment("Executing: (%s) in direc...
Execute a command in specific working directory
entailment
def evaluate_component(comp_type, req_variables={}, parameter_values={}): print_comment('Evaluating %s with req:%s; params:%s'%(comp_type.name,req_variables,parameter_values)) exec_str = '' return_vals = {} from math import exp for p in parameter_values: exec_str+='%s = %s\n'%(p, get_va...
print_comment_v(exec_str)
entailment
def after(self, context, exc=None): """Executed after dispatch has returned and the response populated, prior to anything being sent to the client.""" duration = context._duration = round((time.time() - context._start_time) * 1000) # Convert to ms. delta = unicode(duration) # Default response augmentatio...
Executed after dispatch has returned and the response populated, prior to anything being sent to the client.
entailment
def _process_flat_kwargs(source, kwargs): """Apply a flat namespace transformation to recreate (in some respects) a rich structure. This applies several transformations, which may be nested: `foo` (singular): define a simple value named `foo` `foo` (repeated): define a simple value for placement in an arr...
Apply a flat namespace transformation to recreate (in some respects) a rich structure. This applies several transformations, which may be nested: `foo` (singular): define a simple value named `foo` `foo` (repeated): define a simple value for placement in an array named `foo` `foo[]`: define a simple value...
entailment
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for converting NeuroML v2 files into POVRay files for 3D rendering") parser.add_argument('neuroml_file', type=str, metavar='<NeuroML file>', help='NeuroML ...
Parse command-line arguments.
entailment
def _configure(self, config): """Prepare the incoming configuration and ensure certain expected values are present. For example, this ensures BaseExtension is included in the extension list, and populates the logging config. """ config = config or dict() # We really need this to be there. if 'extensio...
Prepare the incoming configuration and ensure certain expected values are present. For example, this ensures BaseExtension is included in the extension list, and populates the logging config.
entailment
def serve(self, service='auto', **options): # pragma: no cover """Initiate a web server service to serve this application. You can always use the Application instance as a bare WSGI application, of course. This method is provided as a convienence. Pass in the name of the service you wish to use, and any...
Initiate a web server service to serve this application. You can always use the Application instance as a bare WSGI application, of course. This method is provided as a convienence. Pass in the name of the service you wish to use, and any additional configuration options appropriate for that service. Al...
entailment
def application(self, environ, start_response): """Process a single WSGI request/response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware, the `__call__` attribute of the Application instance will either become this, or become the outermost midd...
Process a single WSGI request/response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware, the `__call__` attribute of the Application instance will either become this, or become the outermost middleware callable. Most apps won't utilize middlew...
entailment
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit...
Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed
entailment
def qry_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence''' return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end))
Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence
entailment
def ref_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence''' return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence
entailment
def on_same_strand(self): '''Returns true iff the direction of the alignment is the same in the reference and the query''' return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end)
Returns true iff the direction of the alignment is the same in the reference and the query
entailment
def is_self_hit(self): '''Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity''' return self.ref_name == self.qry_name \ and self.ref_start == self.qry_start \ and self.ref_end == self.qry_end \ ...
Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity
entailment
def reverse_query(self): '''Changes the coordinates as if the query sequence has been reverse complemented''' self.qry_start = self.qry_length - self.qry_start - 1 self.qry_end = self.qry_length - self.qry_end - 1
Changes the coordinates as if the query sequence has been reverse complemented
entailment
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
Changes the coordinates as if the reference sequence has been reverse complemented
entailment
def to_msp_crunch(self): '''Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name ...
Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name 6. subject sequence start ...
entailment
def qry_coords_from_ref_coord(self, ref_coord, variant_list): '''Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether o...
Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether or not the ref_coord lies in an indel. If it is, then returns t...
entailment
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breakl...
Construct the nucmer command
entailment
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) ret...
Construct delta-filter command
entailment
def _show_coords_command(self, infile, outfile): '''Construct show-coords command''' command = 'show-coords -dTlro' if not self.coords_header: command += ' -H' return command + ' ' + infile + ' > ' + outfile
Construct show-coords command
entailment
def _write_script(self, script_name, ref, qry, outfile): '''Write commands into a bash script''' f = pyfastaq.utils.open_file_write(script_name) print(self._nucmer_command(ref, qry, 'p'), file=f) print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f) print(self._s...
Write commands into a bash script
entailment