code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def debug(self, message, *args, **kwargs): """Debug level to use and abuse when coding """ self._log(logging.DEBUG, message, *args, **kwargs)
Debug level to use and abuse when coding
def _set_fcoe_max_enode(self, v, load=False): """ Setter method for fcoe_max_enode, mapped from YANG variable /rbridge_id/fcoe_config/fcoe_max_enode (fcoe-max-enodes-per-rbridge-type) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_max_enode is considered as a priva...
Setter method for fcoe_max_enode, mapped from YANG variable /rbridge_id/fcoe_config/fcoe_max_enode (fcoe-max-enodes-per-rbridge-type) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_max_enode is considered as a private method. Backends looking to populate this variable ...
def generate_html_documentation(self): """generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can cho...
generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring...
def _parse_migrate_output(self, output): """ Args: output: str, output of "manage.py migrate" Returns (succeeded: list(tuple), failed: tuple or None) Both tuples are of the form (app, migration) """ failed = None succeeded = [] # Mark migratio...
Args: output: str, output of "manage.py migrate" Returns (succeeded: list(tuple), failed: tuple or None) Both tuples are of the form (app, migration)
def get_directory(db, user_id, api_dirname, content): """ Return the names of all files/directories that are direct children of api_dirname. If content is False, return a bare model containing just a database-style name. """ db_dirname = from_api_dirname(api_dirname) if not _dir_exists(...
Return the names of all files/directories that are direct children of api_dirname. If content is False, return a bare model containing just a database-style name.
def _zforce(self,R,z,phi=0,t=0): """ NAME: _zforce PURPOSE: evaluate the vertical force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: verti...
NAME: _zforce PURPOSE: evaluate the vertical force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: vertical force at (R,z, phi) HISTORY: 2...
def __filterItems(self, terms, autoExpand=True, caseSensitive=False, parent=None, level=0): """ Filters the items in this tree based on the inputed keywords. :param ...
Filters the items in this tree based on the inputed keywords. :param terms | {<int> column: [<str> term, ..], ..} autoExpand | <bool> caseSensitive | <bool> parent | <QtGui.QTreeWidgetItem> || None ...
def organismsKEGG(): """ Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row. """ organisms=urlopen("http://rest.kegg.jp/list/organism").read() organisms=organisms.split("\n") #for o in organisms: # print o # sys.stdout.flus...
Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row.
def sequential_connect(self): """ Sequential connect is designed to return a connection to the Rendezvous Server but it does so in a way that the local port ranges (both for the server and used for subsequent hole punching) are allocated sequentially and predictably. This is...
Sequential connect is designed to return a connection to the Rendezvous Server but it does so in a way that the local port ranges (both for the server and used for subsequent hole punching) are allocated sequentially and predictably. This is because Delta+1 type NATs only preserve th...
def request(self, url, *, method='GET', headers=None, data=None, result_callback=None): """Perform request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: request data. :param obje...
Perform request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: request data. :param object -> object result_callback: result callback. :rtype: dict :raise: APIError
def _list_itemstrs(list_, **kwargs): """ Create a string representation for each item in a list. """ items = list(list_) kwargs['_return_info'] = True _tups = [repr2(item, **kwargs) for item in items] itemstrs = [t[0] for t in _tups] max_height = max([t[1]['max_height'] for t in _tups]) ...
Create a string representation for each item in a list.
def design_expparams_field(self, guess, field, cost_scale_k=1.0, disp=False, maxiter=None, maxfun=None, store_guess=False, grad_h=None, cost_mult=False ): r""" Designs a new experiment by varying a single field of a shape ``(1,)`` record ar...
r""" Designs a new experiment by varying a single field of a shape ``(1,)`` record array and minimizing the objective function .. math:: O(\vec{e}) = r(\vec{e}) + k \$(\vec{e}), where :math:`r` is the Bayes risk as calculated by the updater, and wher...
def remove(self, child): """Remove a child element.""" for i in range(len(self)): if self[i] == child: del self[i]
Remove a child element.
def netconf_state_schemas_schema_identifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") schemas = ET.SubElement(netconf_state, "schema...
Auto Generated Code
def get_interface_detail_output_interface_ip_mtu(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") ...
Auto Generated Code
def _layer_norm_new_params(input_shape, rng, epsilon=1e-6): # pylint: disable=invalid-name """Helper: create layer norm parameters.""" del rng, epsilon features = input_shape[-1] scale = np.ones(features) bias = np.zeros(features) return (scale, bias)
Helper: create layer norm parameters.
def get_permissions(self): """ Permissions of the user. Returns: List of Permission objects. """ user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role return user_role.get_permissions()
Permissions of the user. Returns: List of Permission objects.
def feed_fetch_force(request, id, redirect_to): """Forcibly fetch tweets for the feed""" feed = Feed.objects.get(id=id) feed.fetch(force=True) msg = _("Fetched tweets for %s" % feed.name) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
Forcibly fetch tweets for the feed
def repeat_str(state): """Convert internal API repeat state to string.""" if state == const.REPEAT_STATE_OFF: return 'Off' if state == const.REPEAT_STATE_TRACK: return 'Track' if state == const.REPEAT_STATE_ALL: return 'All' return 'Unsupported'
Convert internal API repeat state to string.
def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None): """ Check if IP is a threat :param result: httpBL results; if None, then results from last check_ip() used (optional) :param harmless_age: harmless age for check if httpBL age is older (optional) ...
Check if IP is a threat :param result: httpBL results; if None, then results from last check_ip() used (optional) :param harmless_age: harmless age for check if httpBL age is older (optional) :param threat_score: threat score for check if httpBL threat is lower (optional) :param threat_...
def quit(self, message=None): """Quit from the server.""" if message is None: message = 'Quit' if self.connected: self.send('QUIT', params=[message])
Quit from the server.
def start_dashboard(self): """Start the dashboard.""" stdout_file, stderr_file = self.new_log_files("dashboard", True) self._webui_url, process_info = ray.services.start_dashboard( self.redis_address, self._temp_dir, stdout_file=stdout_file, stderr...
Start the dashboard.
def extract(self, package_name): """Extract given package.""" for cmd in ['rpm2cpio', 'cpio']: if not Cmd.which(cmd): message = '{0} command not found. Install {0}.'.format(cmd) raise InstallError(message) pattern = '{0}*{1}.rpm'.format(package_name, ...
Extract given package.
def audio_inputs(self): """ :return: A list of audio input :class:`Ports`. """ return self.client.get_ports(is_audio=True, is_physical=True, is_input=True)
:return: A list of audio input :class:`Ports`.
def _GenerateDescription(self): """Generates description into a MANIFEST file in the archive.""" manifest = { "description": self.description, "processed_files": len(self.processed_files), "archived_files": len(self.archived_files), "ignored_files": len(self.ignored_files), ...
Generates description into a MANIFEST file in the archive.
def gen_xlsx_table_info(): ''' 向表中插入数据 ''' XLSX_FILE = './database/esheet/20180811.xlsx' if os.path.exists(XLSX_FILE): pass else: return RAW_LIST = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',...
向表中插入数据
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): """ Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this me...
Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param outstanding_certs: Certificates that belongs to me that the IdP may have used to encry...
def field_to_dict(fields): """ Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { ...
Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } ...
def ReadDataFile(self): """ Reads the contents of the Comtrade .dat file and store them in a private variable. For accessing a specific channel data, see methods getAnalogData and getDigitalData. """ if os.path.isfile(self.filename[0:-4] + '.dat'): ...
Reads the contents of the Comtrade .dat file and store them in a private variable. For accessing a specific channel data, see methods getAnalogData and getDigitalData.
def AgregarFusion(self, nro_ing_brutos, nro_actividad, **kwargs): "Datos de comprador o vendedor según liquidación a ajustar (fusión.)" self.ajuste['ajusteBase']['fusion'] = {'nroIngBrutos': nro_ing_brutos, 'nroActividad': nro_actividad, ...
Datos de comprador o vendedor según liquidación a ajustar (fusión.)
def rget(self, key, replica_index=None, quiet=None): """Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`config...
Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`configured_replica_count` to figure out the upper bound fo...
def plot_site(fignum, SiteRec, data, key): """ deprecated (used in ipmag) """ print('Site mean data: ') print(' dec inc n_lines n_planes kappa R alpha_95 comp coord') print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'], ...
deprecated (used in ipmag)
def _generate_struct_class(self, ns, data_type): # type: (ApiNamespace, Struct) -> None """Defines a Python class that represents a struct in Stone.""" self.emit(self._class_declaration_for_type(ns, data_type)) with self.indent(): if data_type.has_documented_type_or_fields():...
Defines a Python class that represents a struct in Stone.
def to_datetime(dt, tzinfo=None, format=None): """ Convert a date or time to datetime with tzinfo """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if isinstance(dt, (str, unicode)): if not format: formats = DEFAULT_DATETIME_INPUT_FORMATS ...
Convert a date or time to datetime with tzinfo
def mutual_information( self, M_c, X_L_list, X_D_list, Q, seed, n_samples=1000): """Estimate mutual information for each pair of columns on Q given the set of samples. :param Q: List of tuples where each tuple contains the two column indexes to compare :type Q: l...
Estimate mutual information for each pair of columns on Q given the set of samples. :param Q: List of tuples where each tuple contains the two column indexes to compare :type Q: list of two-tuples of ints :param n_samples: the number of simple predictive samples to use ...
def interrupt(self): """ Invoked on a write operation into the IR of the RendererDevice. """ if(self.device.read(9) & 0x01): self.handle_request() self.device.clear_IR()
Invoked on a write operation into the IR of the RendererDevice.
def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key))
Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].
def calculate_lyapunov(self): """ Return the current Lyapunov Characteristic Number (LCN). Note that you need to call init_megno() before the start of the simulation. To get a timescale (the Lyapunov timescale), take the inverse of this quantity. """ if self._calculate_me...
Return the current Lyapunov Characteristic Number (LCN). Note that you need to call init_megno() before the start of the simulation. To get a timescale (the Lyapunov timescale), take the inverse of this quantity.
def _get_nsamps_samples_n(res): """ Helper function for calculating the number of samples Parameters ---------- res : :class:`~dynesty.results.Results` instance The :class:`~dynesty.results.Results` instance taken from a previous nested sampling run. Returns ------- nsamps:...
Helper function for calculating the number of samples Parameters ---------- res : :class:`~dynesty.results.Results` instance The :class:`~dynesty.results.Results` instance taken from a previous nested sampling run. Returns ------- nsamps: int The total number of samples...
def is_gene_list(bed_file): """Check if the file is only a list of genes, not a BED """ with utils.open_gzipsafe(bed_file) as in_handle: for line in in_handle: if not line.startswith("#"): if len(line.split()) == 1: return True else: ...
Check if the file is only a list of genes, not a BED
def is_decorated_with_property(node): """Check if the function is decorated as a property. :param node: The node to check. :type node: astroid.nodes.FunctionDef :returns: True if the function is a property, False otherwise. :rtype: bool """ if not node.decorators: return False ...
Check if the function is decorated as a property. :param node: The node to check. :type node: astroid.nodes.FunctionDef :returns: True if the function is a property, False otherwise. :rtype: bool
def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''...
Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats
def zDDEInit(self): """Initiates link with OpticStudio DDE server""" self.pyver = _get_python_version() # do this only one time or when there is no channel if _PyZDDE.liveCh==0: try: _PyZDDE.server = _dde.CreateServer() _PyZDDE.server.Create("Z...
Initiates link with OpticStudio DDE server
def get(self, key): """ Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subclass) if the given key is present in the cache, but the value it points to is gone. """ o = self....
Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subclass) if the given key is present in the cache, but the value it points to is gone.
def dict_to_env(d, pathsep=os.pathsep): ''' Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep) ''' out_env = {} for k, v in d.iteritems(): ...
Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep)
def grid(script, size=1.0, x_segments=1, y_segments=1, center=False, color=None): """2D square/plane/grid created on XY plane x_segments # Number of segments in the X direction. y_segments # Number of segments in the Y direction. center="false" # If true square will be centered on origin; ...
2D square/plane/grid created on XY plane x_segments # Number of segments in the X direction. y_segments # Number of segments in the Y direction. center="false" # If true square will be centered on origin; otherwise it is place in the positive XY quadrant.
def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False): """ m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs] """ abf.setsweep(sweep) if m1 is None: m1=0 else: m1=m1*abf.pointsPerSec if m2 is None: m2=-1 else: m2=m2*abf.pointsPerSec # obtain X and Y Yorig=ab...
m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs]
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge Relocated Directory record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdl...
Generate a string representing the Rock Ridge Relocated Directory record. Parameters: None. Returns: String containing the Rock Ridge record.
def FaultFromException(ex, inheader, tb=None, actor=None): '''Return a Fault object created from a Python exception. <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Processing Failure</faultstring> <detail> <ZSI:FaultDetail> <ZSI:string></ZSI:string> ...
Return a Fault object created from a Python exception. <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Processing Failure</faultstring> <detail> <ZSI:FaultDetail> <ZSI:string></ZSI:string> <ZSI:trace></ZSI:trace> </ZSI:FaultDetail> </...
def getoutputerror(cmd): """Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str stderr : str """ o...
Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str stderr : str
def setMotorShutdown(self, value, device=DEFAULT_DEVICE_ID, message=True): """ Set the motor shutdown on error status stored on the hardware device. :Parameters: value : `int` An integer indicating the effect on the motors when an error occurs. A `1` will cause...
Set the motor shutdown on error status stored on the hardware device. :Parameters: value : `int` An integer indicating the effect on the motors when an error occurs. A `1` will cause the cause the motors to stop on an error and a `0` will ignore errors keeping the ...
def xpathNextChild(self, cur): """Traversal function for the "child" direction The child axis contains the children of the context node in document order. """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextChild(self._o, cur__o) if ret ...
Traversal function for the "child" direction The child axis contains the children of the context node in document order.
def to_json(value, pretty=False): """ Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ opt...
Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str
def t_text(self, t): r':\s*<text>' t.lexer.text_start = t.lexer.lexpos - len('<text>') t.lexer.begin('text')
r':\s*<text>
def count(self, request, *args, **kwargs): """ To get a count of events - run **GET** against */api/events/count/* as authenticated user. Endpoint support same filters as events list. Response example: .. code-block:: javascript {"count": 12321} """ ...
To get a count of events - run **GET** against */api/events/count/* as authenticated user. Endpoint support same filters as events list. Response example: .. code-block:: javascript {"count": 12321}
def conn_gcp(cred, crid): """Establish connection to GCP.""" gcp_auth_type = cred.get('gcp_auth_type', "S") if gcp_auth_type == "A": # Application Auth gcp_crd_ia = CONFIG_DIR + ".gcp_libcloud_a_auth." + cred['gcp_proj_id'] gcp_crd = {'user_id': cred['gcp_client_id'], 'ke...
Establish connection to GCP.
def create_symlinks(d): """Create new symbolic links in output directory.""" data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in da...
Create new symbolic links in output directory.
def list_slot_differences_slot( self, resource_group_name, name, slot, target_slot, preserve_vnet, custom_headers=None, raw=False, **operation_config): """Get the difference in configuration settings between two web app slots. Get the difference in configuration settings between two web app...
Get the difference in configuration settings between two web app slots. Get the difference in configuration settings between two web app slots. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param name: Nam...
def _suppress_distutils_logs(): """Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392. """ f = distutils.log.Log._log def _log(log, level, msg, args): if level >= distutils.log.ER...
Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392.
def close(self): """Close the current session, if still open.""" if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
Close the current session, if still open.
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = F...
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
def api(self): """ Get or create an Api() instance using django settings. """ api = getattr(self, '_api', None) if api is None: self._api = mailjet.Api() return self._api
Get or create an Api() instance using django settings.
def estimate_from_ssr(histograms, readout_povm, channel_ops, settings): """ Estimate a density matrix from single shot histograms obtained by measuring bitstrings in the Z-eigenbasis after application of given channel operators. :param numpy.ndarray histograms: The single shot histogram...
Estimate a density matrix from single shot histograms obtained by measuring bitstrings in the Z-eigenbasis after application of given channel operators. :param numpy.ndarray histograms: The single shot histograms, `shape=(n_channels, dim)`. :param DiagognalPOVM readout_povm: The POVM correspond...
def get_resource_area(self, area_id, enterprise_name=None, organization_name=None): """GetResourceArea. [Preview API] :param str area_id: :param str enterprise_name: :param str organization_name: :rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.Resour...
GetResourceArea. [Preview API] :param str area_id: :param str enterprise_name: :param str organization_name: :rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>`
def _setBitOn(x, bitNum): """Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit num...
Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (...
def post(self): '''This handles POST requests. Saves the changes made by the user on the frontend back to the current checkplot-list.json file. ''' # if self.readonly is set, then don't accept any changes # return immediately with a 400 if self.readonly: ...
This handles POST requests. Saves the changes made by the user on the frontend back to the current checkplot-list.json file.
def handle_webhook_event(self, environ, url, params): """ Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response. ...
Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response.
def _prepare_executor(self, data, executor): """Copy executor sources into the destination directory. :param data: The :class:`~resolwe.flow.models.Data` object being prepared for. :param executor: The fully qualified name of the executor that is to be used for this data...
Copy executor sources into the destination directory. :param data: The :class:`~resolwe.flow.models.Data` object being prepared for. :param executor: The fully qualified name of the executor that is to be used for this data object. :return: Tuple containing the relative ...
def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]: """ Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups """ identifiers = set() ...
Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups
def apply_mutation(module_path, operator, occurrence): """Apply a specific mutation to a file on disk. Args: module_path: The path to the module to mutate. operator: The `operator` instance to use. occurrence: The occurrence of the operator to apply. Returns: A `(unmutated-code, mu...
Apply a specific mutation to a file on disk. Args: module_path: The path to the module to mutate. operator: The `operator` instance to use. occurrence: The occurrence of the operator to apply. Returns: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was no ...
def parse_rcfile(rcfile): """ Parses rcfile Invalid lines are ignored with a warning """ def parse_bool(value): """Parse boolean string""" value = value.lower() if value in ['yes', 'true']: return True elif value in ['no', 'false']: return Fal...
Parses rcfile Invalid lines are ignored with a warning
def dropped(self, param, event): """Adds the dropped parameter *param* into the protocol list. Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>` """ if event.source() == self or isinstance(param, AddLabel): index = self.ind...
Adds the dropped parameter *param* into the protocol list. Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>`
def call(self, command, *args): """ Sends call to the function, whose name is specified by command. Used by Script invocations and normalizes calls using standard Redis arguments to use the expected redis-py arguments. """ command = self._normalize_command_name(command) ...
Sends call to the function, whose name is specified by command. Used by Script invocations and normalizes calls using standard Redis arguments to use the expected redis-py arguments.
def get_assessment_offered_query_session_for_bank(self, bank_id): """Gets the ``OsidSession`` associated with the assessment offered query service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentOfferedQuerySession) - an ...
Gets the ``OsidSession`` associated with the assessment offered query service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentOfferedQuerySession) - an ``AssessmentOfferedQuerySession`` raise: NotFound - ``bank_id`` no...
def get_vocab(self, vocab_name, **kwargs): """ Returns data stream of an rdf vocabulary args: vocab_name: the name or uri of the vocab to return """ vocab_dict = self.__get_vocab_dict__(vocab_name, **kwargs) filepaths = list(set([os.path.join(self.cache_dir, ...
Returns data stream of an rdf vocabulary args: vocab_name: the name or uri of the vocab to return
def produce(self, **kwargs): """Call the primitive function, or the predict method of the primitive. The given keyword arguments will be passed directly to the primitive, if it is a simple function, or to the `produce` method of the primitive instance specified in the JSON annotation, i...
Call the primitive function, or the predict method of the primitive. The given keyword arguments will be passed directly to the primitive, if it is a simple function, or to the `produce` method of the primitive instance specified in the JSON annotation, if it is a class. If any of the ...
def parse_sdk_name(name): """Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path. """ # Version like x.y.z, return as-is. if all(part.isdigit() for part in name.split('.', 2)): return DOWNLOAD_URL % name # A network location. u...
Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path.
def set_properties(self, properties, recursive=True): """ Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values ...
Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values for a key. recursive - on folders property attachment is rec...
def galleries(self): """Instance depends on the API version: * 2018-06-01: :class:`GalleriesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleriesOperations>` * 2019-03-01: :class:`GalleriesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleriesOperations>` """ ...
Instance depends on the API version: * 2018-06-01: :class:`GalleriesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleriesOperations>` * 2019-03-01: :class:`GalleriesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleriesOperations>`
def qteBindKeyWidget(self, keysequence, macroName: str, widgetObj: QtGui.QWidget): """ Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used...
Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used to individualise the key bindings inside every applet instance and every widget inside that instance. Even mult...
def randomColor( self ): """ Generates a random color. :return <QColor> """ r = random.randint(120, 180) g = random.randint(120, 180) b = random.randint(120, 180) return QColor(r, g, b)
Generates a random color. :return <QColor>
def log_likelihood(self,x, K_extra=1): """ Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model. """ x = np.asarray(x) ks ...
Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model.
def DbUnExportServer(self, argin): """ Mark all devices belonging to a specified device server process as non exported :param argin: Device server name (executable/instance) :type: tango.DevString :return: :rtype: tango.DevVoid """ self._log.debug("In DbUnExportS...
Mark all devices belonging to a specified device server process as non exported :param argin: Device server name (executable/instance) :type: tango.DevString :return: :rtype: tango.DevVoid
def convolve_spatial3(im, psfs, mode="constant", grid_dim=None, sub_blocks=None, pad_factor=2, plan=None, return_plan=False, verbose=False): """ GPU accelerat...
GPU accelerated spatial varying convolution of an 3d image with a (Gz, Gy, Gx) grid of psfs assumed to be equally spaced within the image the input image im is subdivided into (Gz, Gy,Gx) blocks, each block is convolved with the corresponding psf and linearly interpolated to give the final result ...
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the boun...
Returns the bounds of the slice at each stage of doubling procedure. Precomputes the x coordinates of the left (L) and right (R) endpoints of the interval `I` produced in the "doubling" algorithm [Neal 2003][1] P713. Note that we simultaneously compute all possible doubling values for each chain, for the reaso...
def pretty_repr(instance): """ A function assignable to the ``__repr__`` dunder method, so that the ``prettyprinter`` definition for the type is used to provide repr output. Usage: .. code:: python from prettyprinter import pretty_repr class MyClass: __repr__ = pretty_...
A function assignable to the ``__repr__`` dunder method, so that the ``prettyprinter`` definition for the type is used to provide repr output. Usage: .. code:: python from prettyprinter import pretty_repr class MyClass: __repr__ = pretty_repr
def _dpi(self, resolution_tag): """ Return the dpi value calculated for *resolution_tag*, which can be either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The calculation is based on the values of both that tag and the TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries...
Return the dpi value calculated for *resolution_tag*, which can be either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The calculation is based on the values of both that tag and the TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries| instance.
def get_purchase(self, purchase_id, purchase_key='sid'): """ Retrieve information about a purchase using the system's unique ID or a client's ID @param id_: a string that represents a unique_id or an extid. @param key: a string that is either 'sid' or 'extid'. """ data = ...
Retrieve information about a purchase using the system's unique ID or a client's ID @param id_: a string that represents a unique_id or an extid. @param key: a string that is either 'sid' or 'extid'.
def setup_logger(debug, color): """Configure the logger.""" if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger = logging.getLogger('exifread') stream = Handler(log_level, debug, color) logger.addHandler(stream) logger.setLevel(log_level)
Configure the logger.
def from_graph(cls, graph, linear_energy_ranges, quadratic_energy_ranges): """Create Theta from a graph and energy ranges. Args: graph (:obj:`networkx.Graph`): Provides the structure for Theta. linear_energy_ranges (dict): A dict of the form {v: ...
Create Theta from a graph and energy ranges. Args: graph (:obj:`networkx.Graph`): Provides the structure for Theta. linear_energy_ranges (dict): A dict of the form {v: (min, max), ...} where min and max are the range of values allowed to ...
def save(self): """ Create the writer & save """ # GH21227 internal compression is not used when file-like passed. if self.compression and hasattr(self.path_or_buf, 'write'): msg = ("compression has no effect when passing file-like " "object as inpu...
Create the writer & save
def access_token(): """Token view handles exchange/refresh access tokens.""" client = Client.query.filter_by( client_id=request.form.get('client_id') ).first() if not client: abort(404) if not client.is_confidential and \ 'client_credentials' == request.form.get('grant_...
Token view handles exchange/refresh access tokens.
def camelcase_underscore(name): """ Convert camelcase names to underscore """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Convert camelcase names to underscore
def pull(i): """ Input: { (path) - repo UOA (where to create entry) (type) - type (url) - URL or (data_uoa) - repo UOA (clone) - if 'yes', clone repo instead of update (current_repos) - if r...
Input: { (path) - repo UOA (where to create entry) (type) - type (url) - URL or (data_uoa) - repo UOA (clone) - if 'yes', clone repo instead of update (current_repos) - if resolving dependencies on ...
def register_action(self, name, **kwargs): """ Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :retu...
Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: Action. :rtype: QAction
def _retrieveRegions(self): """ Retrieve and store Python region instances for each column """ self.sensors = [] self.coarseSensors = [] self.locationInputs = [] self.L4Columns = [] self.L2Columns = [] self.L5Columns = [] self.L6Columns = [] for i in xrange(self.numColumns):...
Retrieve and store Python region instances for each column
def load_all(self, group): """ Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the everest configurator as single argument. """ for ep in iter_entry_points(group=group): plugin = ep...
Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the everest configurator as single argument.
def salvar(self, destino=None, prefix='tmp', suffix='-sat.log'): """Salva o arquivo de log decodificado. :param str destino: (Opcional) Caminho completo para o arquivo onde os dados dos logs deverão ser salvos. Se não informado, será criado um arquivo temporário via :func:`tempf...
Salva o arquivo de log decodificado. :param str destino: (Opcional) Caminho completo para o arquivo onde os dados dos logs deverão ser salvos. Se não informado, será criado um arquivo temporário via :func:`tempfile.mkstemp`. :param str prefix: (Opcional) Prefixo para o nome do ...
def port_str_arrange(ports): """ Gives a str in the format (always tcp listed first). T:<tcp ports/portrange comma separated>U:<udp ports comma separated> """ b_tcp = ports.find("T") b_udp = ports.find("U") if (b_udp != -1 and b_tcp != -1) and b_udp < b_tcp: return ports[b_tcp:] + ports[...
Gives a str in the format (always tcp listed first). T:<tcp ports/portrange comma separated>U:<udp ports comma separated>
def to_phase(self, time, component=None, t0='t0_supconj', **kwargs): """ Get the phase(s) of a time(s) for a given ephemeris :parameter time: time to convert to phases (should be in same system as t0s) :type time: float, list, or array :parameter t0: qualifier of the...
Get the phase(s) of a time(s) for a given ephemeris :parameter time: time to convert to phases (should be in same system as t0s) :type time: float, list, or array :parameter t0: qualifier of the parameter to be used for t0 :type t0: str :parameter str component: comp...