code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def build_defines(defines): """Build a list of `-D` directives to pass to the compiler. This will drop any definitions whose value is None so that you can get rid of a define from another architecture by setting its value to null in the `module_settings.json`. """ return ['-D"%s=%s"' % (x, str...
Build a list of `-D` directives to pass to the compiler. This will drop any definitions whose value is None so that you can get rid of a define from another architecture by setting its value to null in the `module_settings.json`.
def set_mask(self, mask_img): """Sets a mask img to this. So every operation to self, this mask will be taken into account. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: ...
Sets a mask img to this. So every operation to self, this mask will be taken into account. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: - a file path to a Nifti image ...
def available_ports(low=1024, high=65535, exclude_ranges=None): """ Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range. """ if exclude_ranges is None: exclude_ranges = [] available = utils.ranges_t...
Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range.
def send_email(sender, subject, content, email_recipient_list, email_address_list, email_user=None, email_pass=None, email_server=None): '''This sends an email to addresses, informing them about events. The...
This sends an email to addresses, informing them about events. The email account settings are retrieved from the settings file as described above. Parameters ---------- sender : str The name of the sender to use in the email header. subject : str Subject of the email. co...
def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> summarize_address_range(IPv4Address('1.1.1.0'), IPv4Address('1.1.1.130')) [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'), IPv4Network('1.1.1.13...
Summarize a network range given the first and last IP addresses. Example: >>> summarize_address_range(IPv4Address('1.1.1.0'), IPv4Address('1.1.1.130')) [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'), IPv4Network('1.1.1.130/32')] Args: first: the first IPv4A...
def track_metric(self, unique_identifier, metric, date=None, inc_amt=1, **kwargs): """ Tracks a metric for a specific ``unique_identifier`` for a certain date. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for tracking of multiple metrics for multiple ...
Tracks a metric for a specific ``unique_identifier`` for a certain date. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for tracking of multiple metrics for multiple unique_identifiers efficiently. Not all backends may support this. :param unique_identif...
def sle(actual, predicted): """ Computes the squared log error. This function computes the squared log error between two numbers, or for element between a pair of lists or numpy arrays. Parameters ---------- actual : int, float, list of numbers, numpy array The ground truth va...
Computes the squared log error. This function computes the squared log error between two numbers, or for element between a pair of lists or numpy arrays. Parameters ---------- actual : int, float, list of numbers, numpy array The ground truth value predicted : same type as actual ...
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.
def autoprops_decorate(cls, # type: Type[T] include=None, # type: Union[str, Tuple[str]] exclude=None # type: Union[str, Tuple[str]] ): # type: (...) -> Type[T] """ To automatically generate all properties getters and setters ...
To automatically generate all properties getters and setters from the class constructor manually, without using @autoprops decorator. * if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the parameter contract will be added on the generated setter method ...
def _get_class(template_file): """ Import the file and inspect for subclass of TaskTemplate. :param template_file: filename to import. """ with warnings.catch_warnings(): # suppress warning from importing warnings.filterwarnings("ignore", category=RuntimeW...
Import the file and inspect for subclass of TaskTemplate. :param template_file: filename to import.
def norm_to_uniform(im, scale=None): r""" Take an image with normally distributed greyscale values and converts it to a uniform (i.e. flat) distribution. It's also possible to specify the lower and upper limits of the uniform distribution. Parameters ---------- im : ND-image The im...
r""" Take an image with normally distributed greyscale values and converts it to a uniform (i.e. flat) distribution. It's also possible to specify the lower and upper limits of the uniform distribution. Parameters ---------- im : ND-image The image containing the normally distributed s...
def auto_rewrite_input(self, cmd): """Print to the screen the rewritten form of the user's command. This shows visual feedback by rewriting input lines that cause automatic calling to kick in, like:: /f x into:: ------> f(x) after the user's input prompt....
Print to the screen the rewritten form of the user's command. This shows visual feedback by rewriting input lines that cause automatic calling to kick in, like:: /f x into:: ------> f(x) after the user's input prompt. This helps the user understand that the ...
def blockreplace( name, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', source=None, source_hash=None, template='jinja', sources=None, source_hashes=None, defaults=None, context=None, content='', ...
Maintain an edit in a file in a zone delimited by two line markers .. versionadded:: 2014.1.0 .. versionchanged:: 2017.7.5,2018.3.1 ``append_newline`` argument added. Additionally, to improve idempotence, if the string represented by ``marker_end`` is found in the middle of the line, th...
def tdSensor(self): """Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. """ protocol = create_string_buffer(20) model = create_string_buffer(20) sid = c_int() datatypes = c_int() self._lib.tdSensor(proto...
Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes.
def reverse_iter(self, start=None, stop=None, count=2000): """ -> yields items of the list in reverse """ cursor = '0' count = 1000 start = start if start is not None else (-1 * count) stop = stop if stop is not None else -1 _loads = self._loads while cursor: ...
-> yields items of the list in reverse
def parse_meta(self, selected_meta_data): """ Parses all of the metadata files :param selected_meta_data: if specified then only the columns that are contained here are going to be parsed :return: """ # reads all meta data files files = self._get_files("meta", sel...
Parses all of the metadata files :param selected_meta_data: if specified then only the columns that are contained here are going to be parsed :return:
def plot_fit_individuals_lens_plane_only( fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None, should_plot_image_plane_pix=False, should_plot_image=False, should_plot_noise_map=False, should_plot_signal_to_noise_map=False, sho...
Plot the model datas_ of an analysis, using the *Fitter* class object. The visualization and output type can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_square...
def find_link(self, device): '''find a device based on number, name or label''' for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] if (str(i) == device or conn.address == device or getattr(conn, 'label', None) == device...
find a device based on number, name or label
def _set_security(self, v, load=False): """ Setter method for security, mapped from YANG variable /rbridge_id/threshold_monitor/security (container) If this variable is read-only (config: false) in the source YANG file, then _set_security is considered as a private method. Backends looking to popula...
Setter method for security, mapped from YANG variable /rbridge_id/threshold_monitor/security (container) If this variable is read-only (config: false) in the source YANG file, then _set_security is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
def fetch_batch_status(self, guid): """Fetch the status of a batch, given the guid""" url = '%s/api/v5/batch/%s/status' % (self.base_url, guid) headers = { 'User-Agent': 'kentik-python-api/0.1', 'Content-Type': 'application/json', 'X-CH-Auth-Email': self.api_e...
Fetch the status of a batch, given the guid
def _starts_with_vowel(self, letter_group: str) -> bool: """Check if a string starts with a vowel.""" if len(letter_group) == 0: return False return self._contains_vowels(letter_group[0])
Check if a string starts with a vowel.
def get_validated_token(self, raw_token): """ Validates an encoded JSON web token and returns a validated token wrapper object. """ messages = [] for AuthToken in api_settings.AUTH_TOKEN_CLASSES: try: return AuthToken(raw_token) exc...
Validates an encoded JSON web token and returns a validated token wrapper object.
def calculate_sampling_decision(trace_header, recorder, sampling_req): """ Return 1 or the matched rule name if should sample and 0 if should not. The sampling decision coming from ``trace_header`` always has the highest precedence. If the ``trace_header`` doesn't contain sampling decision then it c...
Return 1 or the matched rule name if should sample and 0 if should not. The sampling decision coming from ``trace_header`` always has the highest precedence. If the ``trace_header`` doesn't contain sampling decision then it checks if sampling is enabled or not in the recorder. If not enbaled it returns ...
def get_variable(name, temp_s): ''' Get variable by name. ''' return tf.Variable(tf.zeros(temp_s), name=name)
Get variable by name.
def print_groups(): """Print all groups as JSON""" print("Printing information about all groups defined in the Gateway") groups = api(gateway.get_groups()) if len(groups) == 0: exit(bold("No groups defined")) container = [] for group in groups: container.append(api(group).raw) ...
Print all groups as JSON
def _is_admin(user_id): """ Is the specified user an admin """ user = get_session().query(User).filter(User.id==user_id).one() if user.is_admin(): return True else: return False
Is the specified user an admin
def now_micros(absolute=False) -> int: """Return current micros since epoch as integer.""" micros = int(time.time() * 1e6) if absolute: return micros return micros - EPOCH_MICROS
Return current micros since epoch as integer.
def destination_uri_file_counts(self): """Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts Returns: a list of integer counts, each representing the number of fi...
Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts Returns: a list of integer counts, each representing the number of files per destination URI or URI pattern...
def split(args): """ %prog split pairs.fastq Split shuffled pairs into `.1.fastq` and `.2.fastq`, using `sed`. Can work on gzipped file. <http://seqanswers.com/forums/showthread.php?t=13776> """ from jcvi.apps.grid import Jobs p = OptionParser(split.__doc__) opts, args = p.parse_a...
%prog split pairs.fastq Split shuffled pairs into `.1.fastq` and `.2.fastq`, using `sed`. Can work on gzipped file. <http://seqanswers.com/forums/showthread.php?t=13776>
def dispatch(argdict): '''Call the command-specific function, depending on the command.''' cmd = argdict['command'] ftc = getattr(THIS_MODULE, 'do_'+cmd) ftc(argdict)
Call the command-specific function, depending on the command.
def get_cloud_init_mime(cloud_init): ''' Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init> ''' if isinstance(cloud_init, six.stri...
Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init>
def convert_to_string(self, block): """ Takes a list of SeqRecordExpanded objects corresponding to a gene_code and produces the gene_block as string. :param block: :return: str. """ out = "" for seq_record in block: taxon_id = ">{0}_{1}_{2} [o...
Takes a list of SeqRecordExpanded objects corresponding to a gene_code and produces the gene_block as string. :param block: :return: str.
def make_mujoco_env(env_id, seed, reward_scale=1.0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ rank = MPI.COMM_WORLD.Get_rank() myseed = seed + 1000 * rank if seed is not None else None set_global_seeds(myseed) env = gym.make(env_id) logger_path = None if logger.get_dir() ...
Create a wrapped, monitored gym.Env for MuJoCo.
def element_creator(namespace=None): """Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator """ ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace, ...
Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator
def iterate(self, start_line=None, parse_attr=True, headers=False, comments=False): """Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Next GFF3 entry. If 'handle' has been partially read and you want to start iterating at the next entry, read...
Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Next GFF3 entry. If 'handle' has been partially read and you want to start iterating at the next entry, read the next GFF3 entry and pass it to this variable when calling gff3_it...
def deserialize(cls, config, credentials): """ A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the ...
A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the credentials. :param str credentials: ...
def index(self, row, column, parent): """Reimplemented from QtCore.QAbstractItemModel The internal pointer is the section. The row determines the key in the scalars then sections of the configobj. So for a given index, use row to retrieve the key:: key = self.get_key(index.in...
Reimplemented from QtCore.QAbstractItemModel The internal pointer is the section. The row determines the key in the scalars then sections of the configobj. So for a given index, use row to retrieve the key:: key = self.get_key(index.internalPointer(), index.row()) To use the...
def evaluate_block(self, comments): """Evaluate block comments.""" if self.jsdocs: m1 = RE_JSDOC.match(comments) if m1: lines = [] for line in m1.group(1).splitlines(True): l = line.lstrip() lines.append(l[1...
Evaluate block comments.
def update(self, data, length=None): """ Hashes given byte string @param data - string to hash @param length - if not specifed, entire string is hashed, otherwise only first length bytes """ if self.digest_finalized: raise DigestError("No upda...
Hashes given byte string @param data - string to hash @param length - if not specifed, entire string is hashed, otherwise only first length bytes
def get_file(self, name): """ Returns the output file with the specified name, if no output files match, returns None. """ files = self.get_output_files() for f in files: if f.get_name() == name: return f return None
Returns the output file with the specified name, if no output files match, returns None.
def close(self): """Logs out and quits the current web driver/selenium session.""" if not self.driver: return try: self.driver.implicitly_wait(1) self.driver.find_element_by_id('link-logout').click() except NoSuchElementException: pass ...
Logs out and quits the current web driver/selenium session.
def groupByContent(paths): """Byte-for-byte comparison on an arbitrary number of files in parallel. This operates by opening all files in parallel and comparing chunk-by-chunk. This has the following implications: - Reads the same total amount of data as hash comparison. - Performs a *lot*...
Byte-for-byte comparison on an arbitrary number of files in parallel. This operates by opening all files in parallel and comparing chunk-by-chunk. This has the following implications: - Reads the same total amount of data as hash comparison. - Performs a *lot* of disk seeks. (Best suited for S...
def get_linode(kwargs=None, call=None): ''' Returns data for a single named Linode. name The name of the Linode for which to get data. Can be used instead ``linode_id``. Note this will induce an additional API call compared to using ``linode_id``. linode_id The ID of th...
Returns data for a single named Linode. name The name of the Linode for which to get data. Can be used instead ``linode_id``. Note this will induce an additional API call compared to using ``linode_id``. linode_id The ID of the Linode for which to get data. Can be used instead ...
def _merge_flags(new_flags, old_flags=None, conf='any'): ''' Merges multiple lists of flags removing duplicates and resolving conflicts giving priority to lasts lists. ''' if not old_flags: old_flags = [] args = [old_flags, new_flags] if conf == 'accept_keywords': tmp = new_f...
Merges multiple lists of flags removing duplicates and resolving conflicts giving priority to lasts lists.
def process_shell(self, creator, entry, config): """Processing a shell entry.""" self.logger.info("Processing Bash code: start") output = [] shell = creator(entry, config) for line in shell.process(): output.append(line) self.logger.info(" | %s", line) ...
Processing a shell entry.
def launch(self, args, unknown): """Launch something according to the provided arguments :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises:...
Launch something according to the provided arguments :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: SystemExit
def get_states(self): """ Returns the states of variables present in the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_states() {'bowel-problem': ['true', 'false'], 'dog-out': ['true', 'false'], 'fa...
Returns the states of variables present in the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_states() {'bowel-problem': ['true', 'false'], 'dog-out': ['true', 'false'], 'family-out': ['true', 'false'], 'he...
def two_digit_freqs(digits, normalize=False): """ Consume digits of pi and compute 2 digits freq. counts. """ freqs = np.zeros(100, dtype='i4') last = digits.next() this = digits.next() for d in digits: index = int(last + this) freqs[index] += 1 last = this th...
Consume digits of pi and compute 2 digits freq. counts.
def binaryRecords(self, path, recordLength): """ .. note:: Experimental Load data from a flat binary file, assuming each record is a set of numbers with the specified numerical format (see ByteBuffer), and the number of bytes per record is constant. :param path: Directo...
.. note:: Experimental Load data from a flat binary file, assuming each record is a set of numbers with the specified numerical format (see ByteBuffer), and the number of bytes per record is constant. :param path: Directory to the input data files :param recordLength: The lengt...
def network_lopf_solve(network, snapshots=None, formulation="angles", solver_options={},solver_logfile=None, keep_files=False, free_memory={'pyomo'},extra_postprocessing=None): """ Solve linear optimal power flow for a group of snapshots and extract results. Parameters ---------...
Solve linear optimal power flow for a group of snapshots and extract results. Parameters ---------- snapshots : list or index slice A list of snapshots to optimise, must be a subset of network.snapshots, defaults to network.snapshots formulation : string Formulation of the linea...
def action_rename(self): """ Rename a shortcut """ # get old and new name from args old = self.args['<old>'] new = self.args['<new>'] # select the old shortcut self.db_query(''' SELECT id FROM shortcuts WHERE name=? ''', (old,)) ...
Rename a shortcut
def get_ips(host, port): """ lookup all IPs (v4 and v6) """ ips = set() for af_type in (socket.AF_INET, socket.AF_INET6): try: records = socket.getaddrinfo(host, port, af_type, socket.SOCK_STREAM) ips.update(rec[4][0] for rec in records) except socket.gaierro...
lookup all IPs (v4 and v6)
def get_fallback_languages(self, language_code=None, site_id=None): """ Find out what the fallback language is for a given language choice. .. versionadded 1.5 """ choices = self.get_active_choices(language_code, site_id=site_id) return choices[1:]
Find out what the fallback language is for a given language choice. .. versionadded 1.5
def in4_chksum(proto, u, p): """ As Specified in RFC 2460 - 8.1 Upper-Layer Checksums Performs IPv4 Upper Layer checksum computation. Provided parameters are: - 'proto' : value of upper layer protocol - 'u' : IP upper layer instance - 'p' : the payload of the upper layer provided as a string ...
As Specified in RFC 2460 - 8.1 Upper-Layer Checksums Performs IPv4 Upper Layer checksum computation. Provided parameters are: - 'proto' : value of upper layer protocol - 'u' : IP upper layer instance - 'p' : the payload of the upper layer provided as a string
def update(self, values): """Add new declarations to this set/ Args: values (dict(name, declaration)): the declarations to ingest. """ for k, v in values.items(): root, sub = self.split(k) if sub is None: self.declarations[root] = v ...
Add new declarations to this set/ Args: values (dict(name, declaration)): the declarations to ingest.
def status(context): """See which files have changed, checked in, and uploaded""" context.obj.find_repo_type() context.obj.call([context.obj.vc_name, 'status'])
See which files have changed, checked in, and uploaded
def mask_blurring_from_mask_and_psf_shape(mask, psf_shape): """Compute a blurring masks from an input masks and psf shape. The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \ light blur into the masked region due to PSF convolution.""" blurri...
Compute a blurring masks from an input masks and psf shape. The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \ light blur into the masked region due to PSF convolution.
def _join_partner(self, partner: Address): """ Ensure a channel exists with partner and is funded in our side """ try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelErro...
Ensure a channel exists with partner and is funded in our side
def _move_node_file(path, old_id, new_id): """ Move the files from a node when changing his id :param path: Path of the project :param old_id: ID before change :param new_id: New node UUID """ root = os.path.join(path, "project-files") if os.path.exists(root): for dirname in os....
Move the files from a node when changing his id :param path: Path of the project :param old_id: ID before change :param new_id: New node UUID
def set_SaveName(self,SaveName=None, include=None, ForceUpdate=False): """ Set the name for saving the instance (SaveName) SaveName can be either: - provided by the user (no constraint) - not recommended - automatically generated from Na...
Set the name for saving the instance (SaveName) SaveName can be either: - provided by the user (no constraint) - not recommended - automatically generated from Name and key attributes (cf. include) Parameters ---------- SaveName : None / str If ...
def append_new_text(destination, text, join_str=None): """ This method provides the functionality of adding text appropriately underneath the destination node. This will be either to the destination's text attribute or to the tail attribute of the last child. """ if join_str is None: joi...
This method provides the functionality of adding text appropriately underneath the destination node. This will be either to the destination's text attribute or to the tail attribute of the last child.
def normalize_slice(e, n): """ Return the slice tuple normalized for an ``n``-element object. :param e: a slice object representing a selector :param n: number of elements in a sequence to which ``e`` is applied :returns: tuple ``(start, count, step)`` derived from ``e``. """ if n == 0: ...
Return the slice tuple normalized for an ``n``-element object. :param e: a slice object representing a selector :param n: number of elements in a sequence to which ``e`` is applied :returns: tuple ``(start, count, step)`` derived from ``e``.
def getDelta(original, update): """ Generates an update token delta_{k->k'}. @original: values for k: (w,msk,s) @update: values for kPrime: (w',msk',s') @return (delta, p'): @delta = k'/k, @p' is a new pubkey based on k'. """ # Compute both keys k = genKw(*original) kPrime = genKw(*u...
Generates an update token delta_{k->k'}. @original: values for k: (w,msk,s) @update: values for kPrime: (w',msk',s') @return (delta, p'): @delta = k'/k, @p' is a new pubkey based on k'.
def ast_from_module_name(self, modname, context_file=None): """given a module name, return the astroid object""" if modname in self.astroid_cache: return self.astroid_cache[modname] if modname == "__main__": return self._build_stub_module(modname) old_cwd = os.get...
given a module name, return the astroid object
async def _connect(self): """ Connect to the stream Returns ------- asyncio.coroutine The streaming response """ logger.debug("connecting to the stream") await self.client.setup if self.session is None: self.session = s...
Connect to the stream Returns ------- asyncio.coroutine The streaming response
def packageInfo(self): """gets the item's package information file""" url = "%s/item.pkinfo" % self.root params = {'f' : 'json'} result = self._get(url=url, param_dict=params, securityHandler=self._securityHandler, ...
gets the item's package information file
def get_download_link(self): """ Get direct download link with soudcloud's redirect system. """ url = None if not self.get("downloadable"): try: url = self.client.get_location( self.client.STREAM_URL % self.get("id")) except serror as e...
Get direct download link with soudcloud's redirect system.
def create_node(manager, name, meta_type_label, type_label, handle_id, legacy=True): """ Creates a node with the mandatory attributes name and handle_id also sets type label. :param manager: Manager to handle sessions and transactions :param name: Node name :param meta_type_label: Node meta type ...
Creates a node with the mandatory attributes name and handle_id also sets type label. :param manager: Manager to handle sessions and transactions :param name: Node name :param meta_type_label: Node meta type :param type_label: Node label :param handle_id: Unique id :param legacy: Backwards comp...
def formatters(*chained_formatters): """ Chain formatter functions. :param chained_formatters: :type chained_formatters: :return: :rtype: """ def formatters_chain(input_string): # pylint:disable=missing-docstring for chained_formatter in chained_formatters: input_str...
Chain formatter functions. :param chained_formatters: :type chained_formatters: :return: :rtype:
def get_dataarg(args): """Retrieve the world 'data' argument from a set of input parameters. """ for i, arg in enumerate(args): if is_nested_config_arg(arg): return i, arg elif is_std_config_arg(arg): return i, {"config": arg} elif isinstance(arg, (list, tuple...
Retrieve the world 'data' argument from a set of input parameters.
def plot(self, coordinates, directed=False, weighted=False, fig='current', ax=None, edge_style=None, vertex_style=None, title=None, cmap=None): '''Plot the graph using matplotlib in 2 or 3 dimensions. coordinates : (n,2) or (n,3) array of vertex coordinates directed : if True, edges have arrows ...
Plot the graph using matplotlib in 2 or 3 dimensions. coordinates : (n,2) or (n,3) array of vertex coordinates directed : if True, edges have arrows indicating direction. weighted : if True, edges are colored by their weight. fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to ...
def connect(self, component): """Connect two ThreadPools. The ``in_queue`` of the second pool will be set as the ``out_queue`` of the current pool, thus all the output will be input to the second pool. Args: component (ThreadPool): the ThreadPool to be connected. Re...
Connect two ThreadPools. The ``in_queue`` of the second pool will be set as the ``out_queue`` of the current pool, thus all the output will be input to the second pool. Args: component (ThreadPool): the ThreadPool to be connected. Returns: ThreadPool: the modifi...
def mixedSuites(self, tests): """The complex case where there are tests that don't all share the same context. Groups tests into suites with common ancestors, according to the following (essentially tail-recursive) procedure: Starting with the context of the first test, if it is not ...
The complex case where there are tests that don't all share the same context. Groups tests into suites with common ancestors, according to the following (essentially tail-recursive) procedure: Starting with the context of the first test, if it is not None, look for tests in the remainin...
def create(genome, config): """ Receives a genome and returns its phenotype (a FeedForwardNetwork). """ # Gather expressed connections. connections = [cg.key for cg in itervalues(genome.connections) if cg.enabled] layers = feed_forward_layers(config.genome_config.input_keys, config.gen...
Receives a genome and returns its phenotype (a FeedForwardNetwork).
def row(self): """ Returns the periodic table row of the element. """ z = self.Z total = 0 if 57 <= z <= 71: return 8 elif 89 <= z <= 103: return 9 for i in range(len(_pt_row_sizes)): total += _pt_row_sizes[i] ...
Returns the periodic table row of the element.
def to_function(var_instance, lineno=None): """ Converts a var_instance to a function one """ assert isinstance(var_instance, SymbolVAR) from symbols import FUNCTION var_instance.__class__ = FUNCTION var_instance.class_ = CLASS.function var_instance.reset(lineno=l...
Converts a var_instance to a function one
def execute(self, conn, child_block_name='', child_lfn_list=[], transaction=False): sql = '' binds = {} child_ds_name = '' child_where = '' if child_block_name: child_ds_name = child_block_name.split('#')[0] parent_where = " where d.dataset = :child_ds_nam...
cursors = self.dbi.processData(sql, binds, conn, transaction=transaction, returnCursor=True) for i in cursors: d = self.formatCursor(i, size=100) if isinstance(d, list) or isinstance(d, GeneratorType): for elem in d: yield elem elif d: ...
def value(self): """ returns the class as a dictionary """ r = {} attributes = [attr for attr in dir(self) if not attr.startswith('__') and \ not attr.startswith('_')] for a in attributes: if a != "value": val = geta...
returns the class as a dictionary
def contains_ignoring_case(self, *items): """Asserts that val is string and contains the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') if isinstance(self.val, str_types): if len(items) == 1: if not isinstanc...
Asserts that val is string and contains the given item or items.
def tagre(tag, attribute, value, quote='"', before="", after=""): """Return a regular expression matching the given HTML tag, attribute and value. It matches the tag and attribute names case insensitive, and skips arbitrary whitespace and leading HTML attributes. The "<>" at the start and end of the HTM...
Return a regular expression matching the given HTML tag, attribute and value. It matches the tag and attribute names case insensitive, and skips arbitrary whitespace and leading HTML attributes. The "<>" at the start and end of the HTML tag is also matched. @param tag: the tag name @ptype tag: strin...
def serialize_checks(check_set): """ Serialize a check_set for raphael """ check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, ...
Serialize a check_set for raphael
def firwin_bpf(N_taps, f1, f2, fs = 1.0, pass_zero=False): """ Design a windowed FIR bandpass filter in terms of passband critical frequencies f1 < f2 in Hz relative to sampling rate fs in Hz. The number of taps must be provided. Mark Wickert October 2016 """ return signal.firwin(N_...
Design a windowed FIR bandpass filter in terms of passband critical frequencies f1 < f2 in Hz relative to sampling rate fs in Hz. The number of taps must be provided. Mark Wickert October 2016
def parse(directive): """ Given a string in the format `scope:directive`, or simply `scope` or `directive`, return a Placement object suitable for passing back over the websocket API. """ if not directive: # Handle null case return None if isinstance(directive, (list, tuple...
Given a string in the format `scope:directive`, or simply `scope` or `directive`, return a Placement object suitable for passing back over the websocket API.
def _bls_runner(times, mags, nfreq, freqmin, stepsize, nbins, minduration, maxduration): '''This runs the pyeebls.eebls function using the given inputs. Parameters ---------- times,mags : np...
This runs the pyeebls.eebls function using the given inputs. Parameters ---------- times,mags : np.array The input magnitude time-series to search for transits. nfreq : int The number of frequencies to use when searching for transits. freqmin : float The minimum frequency...
def l2_regularizer(weight=1.0, scope=None): """Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. """ def regularizer(tensor): with tf.name_scope(scope, 'L2Regularizer', [tensor]): l2_weight = tf....
Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function.
def _year_info_pq(self, year, keyword): """Returns a PyQuery object containing the info from the meta div at the top of the team year page with the given keyword. :year: Int representing the season. :keyword: A keyword to filter to a single p tag in the meta div. :returns: A PyQ...
Returns a PyQuery object containing the info from the meta div at the top of the team year page with the given keyword. :year: Int representing the season. :keyword: A keyword to filter to a single p tag in the meta div. :returns: A PyQuery object for the selected p element.
def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0): """Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive) """ fil...
Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive)
def message_to_dict(msg): """Convert an email message into a dictionary. This function transforms an `email.message.Message` object into a dictionary. Headers are stored as key:value pairs while the body of the message is stored inside `body` key. Body may have two other keys inside, 'plain', for p...
Convert an email message into a dictionary. This function transforms an `email.message.Message` object into a dictionary. Headers are stored as key:value pairs while the body of the message is stored inside `body` key. Body may have two other keys inside, 'plain', for plain body messages and 'html'...
def update(self, name=None, metadata=None): """ Updates this webhook. One or more of the parameters may be specified. """ return self.policy.update_webhook(self, name=name, metadata=metadata)
Updates this webhook. One or more of the parameters may be specified.
def sparse(x0, rho, gamma): """ Proximal operator for the l1 norm (induces sparsity) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger value -> stays closer to x0) ...
Proximal operator for the l1 norm (induces sparsity) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger value -> stays closer to x0) gamma : float A constant that...
def _sample_condition(exp_condition, frame_times, oversampling=50, min_onset=-24): """Make a possibly oversampled event regressor from condition information. Parameters ---------- exp_condition : arraylike of shape (3, n_events) yields description of events for this conditi...
Make a possibly oversampled event regressor from condition information. Parameters ---------- exp_condition : arraylike of shape (3, n_events) yields description of events for this condition as a (onsets, durations, amplitudes) triplet frame_times : array of shape(n_scans) samp...
def remoteLocation_resolve(self, d_remote): """ Resolve the remote path location :param d_remote: the "remote" specification :return: a string representation of the remote path """ b_status = False str_remotePath = "" if 'path' in d_remote.keys():...
Resolve the remote path location :param d_remote: the "remote" specification :return: a string representation of the remote path
def add_words(self): """The data block must fill the entire data capacity of the QR code. If we fall short, then we must add bytes to the end of the encoded data field. The value of these bytes are specified in the standard. """ data_blocks = len(self.buffer.getvalue()) // 8 ...
The data block must fill the entire data capacity of the QR code. If we fall short, then we must add bytes to the end of the encoded data field. The value of these bytes are specified in the standard.
def get_b(self): """ Get Galactic latitude (b) corresponding to the current position :return: Latitude """ try: return self.b.value except AttributeError: # Transform from L,B to R.A., Dec return self.sky_coord.transform_to('galac...
Get Galactic latitude (b) corresponding to the current position :return: Latitude
def format_result(line, line_num, txt): """ highlight the search result """ return '&nbsp;&nbsp;' + str(line_num) + ': ' + line.replace(txt, '<span style="background-color: #FFFF00">' + txt + '</span>')
highlight the search result
def get_users(self, search=None, page=1, per_page=20, **kwargs): """ Returns a list of users from the Gitlab server :param search: Optional search query :param page: Page number (default: 1) :param per_page: Number of items to list per page (default: 20, max: 100) :retur...
Returns a list of users from the Gitlab server :param search: Optional search query :param page: Page number (default: 1) :param per_page: Number of items to list per page (default: 20, max: 100) :return: List of Dictionaries containing users :raise: HttpError if invalid respons...
def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value ...
Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: valu...
def read_clusters(self, min_cluster_size): """Read and parse OSLOM clusters output file.""" num_found = 0 clusters = [] with open(self.get_path(OslomRunner.OUTPUT_FILE), "r") as reader: # Read the output file every two lines for line1, line2 in itertools.izip_long...
Read and parse OSLOM clusters output file.
def _maybe_notify_connected(self, arg): """ Internal helper. .callback or .errback on all Deferreds we've returned from `when_connected` """ if self._connected_listeners is None: return for d in self._connected_listeners: # Twisted will tu...
Internal helper. .callback or .errback on all Deferreds we've returned from `when_connected`
def draw_variable_local(self, size): """ Simulate from the Normal distribution using instance values Parameters ---------- size : int How many simulations to perform Returns ---------- np.ndarray of Normal random variable """ return ...
Simulate from the Normal distribution using instance values Parameters ---------- size : int How many simulations to perform Returns ---------- np.ndarray of Normal random variable