code
stringlengths
59
4.4k
docstring
stringlengths
5
7.69k
def x10_command(self, house_code, unit_number, state): house_code = normalize_housecode(house_code) if unit_number is not None: unit_number = normalize_unitnumber(unit_number) return self._x10_command(house_code, unit_number, state)
Send X10 command to ??? unit. @param house_code (A-P) - example='A' @param unit_number (1-16)- example=1 (or None to impact entire house code) @param state - Mochad command/state, See https://sourceforge.net/p/mochad/code/ci/master/tree/README examples=OFF, 'OFF'...
def buildOverlappedSequences( numSequences = 2, seqLen = 5, sharedElements = [3,4], numOnBitsPerPattern = 3, patternOverlap = 0, seqOverlap = 0, ...
Create training sequences that share some elements in the middle. Parameters: ----------------------------------------------------- numSequences: Number of unique training sequences to generate seqLen: Overall length of each sequence sharedElements: Which element indices of each s...
def delayed_call(self, delay, function): main_loop = self handler = [] class DelayedCallHandler(TimeoutHandler): @timeout_handler(delay, False) def callback(self): try: function() finally: main_loop.r...
Schedule function to be called from the main loop after `delay` seconds. :Parameters: - `delay`: seconds to wait :Types: - `delay`: `float`
def flat_map(self, flatmap_function): from heronpy.streamlet.impl.flatmapbolt import FlatMapStreamlet fm_streamlet = FlatMapStreamlet(flatmap_function, self) self._add_child(fm_streamlet) return fm_streamlet
Return a new Streamlet by applying map_function to each element of this Streamlet and flattening the result
def get_raw_output(self, tile, _baselevel_readonly=False): if not isinstance(tile, (BufferedTile, tuple)): raise TypeError("'tile' must be a tuple or BufferedTile") if isinstance(tile, tuple): tile = self.config.output_pyramid.tile(*tile) if _baselevel_readonly: ...
Get output raw data. This function won't work with multiprocessing, as it uses the ``threading.Lock()`` class. Parameters ---------- tile : tuple, Tile or BufferedTile If a tile index is given, a tile from the output pyramid will be assumed. Tile cannot ...
def getOutputElementCount(self, name): if name == "resetOut": print ("WARNING: getOutputElementCount should not have been called with " "resetOut") return 1 elif name == "sequenceIdOut": print ("WARNING: getOutputElementCount should not have been called with " "sequen...
Computes the width of dataOut. Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
def _setup_custom_grouping(self, topology): for i in range(len(topology.bolts)): for in_stream in topology.bolts[i].inputs: if in_stream.stream.component_name == self.my_component_name and \ in_stream.gtype == topology_pb2.Grouping.Value("CUSTOM"): if in_stream.type == topology_pb2...
Checks whether there are any bolts that consume any of my streams using custom grouping
def _store_helper(model: Action, session: Optional[Session] = None) -> None: if session is None: session = _make_session() session.add(model) session.commit() session.close()
Help store an action.
def remove_handler(self, handler): with self.lock: if handler in self.handlers: self.handlers.remove(handler) self._update_handlers()
Remove a handler object. :Parameters: - `handler`: the object to remove
def in_op(self, other): if not is_object(other): raise MakeError( 'TypeError', "You can\'t use 'in' operator to search in non-objects") return other.has_property(to_string(self))
checks if self is in other
def register(self, what, obj): name = obj.name version = obj.version enable = obj.enable if enable == 'n': return key = Key(name, version) self.plugins[what][key] = obj
Registering a plugin Params ------ what: Nature of the plugin (backend, instrumentation, repo) obj: Instance of the plugin
def _build_google_client(service, api_version, http_auth): client = build(service, api_version, http=http_auth) return client
Google build client helper. :param service: service to build client for :type service: ``str`` :param api_version: API version to use. :type api_version: ``str`` :param http_auth: Initialized HTTP client to use. :type http_auth: ``object`` :return: google-python-api client initialized to...
def limit(self, max=30): if abs(self.vx) > max: self.vx = self.vx/abs(self.vx)*max if abs(self.vy) > max: self.vy = self.vy/abs(self.vy)*max if abs(self.vz) > max: self.vz = self.vz/abs(self.vz)*max
The speed limit for a boid. Boids can momentarily go very fast, something that is impossible for real animals.
def save_file(self, obj): try: import StringIO as pystringIO except ImportError: import io as pystringIO if not hasattr(obj, 'name') or not hasattr(obj, 'mode'): raise pickle.PicklingError("Cannot pickle files that do not map to an actual file") if obj is sys.stdout: return self...
Save a file
def load_all_methods(self): r methods = [] Tmins, Tmaxs = [], [] if self.CASRN in ['7732-18-5', '67-56-1', '64-17-5']: methods.append(TEST_METHOD_1) self.TEST_METHOD_1_Tmin = 200. self.TEST_METHOD_1_Tmax = 350 self.TEST_METHOD_1_coeffs = [1...
r'''Method to load all data, and set all_methods based on the available data and properties. Demo function for testing only; must be implemented according to the methods available for each individual method.
def __intermediate_dns_servers(self, uci, address): if 'dns' in uci: return uci['dns'] if address['proto'] in ['dhcp', 'dhcpv6', 'none']: return None dns = self.netjson.get('dns_servers', None) if dns: return ' '.join(dns)
determines UCI interface "dns" option
def serialize_text(out, text): padding = len(out) add_padding = padding_adder(padding) text = add_padding(text, ignore_first_line=True) return out + text
This method is used to append content of the `text` argument to the `out` argument. Depending on how many lines in the text, a padding can be added to all lines except the first one. Concatenation result is appended to the `out` argument.
def mpsse_read_gpio(self): self._write('\x81\x83') data = self._poll_read(2) low_byte = ord(data[0]) high_byte = ord(data[1]) logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte)) return (high_byte << 8) | low_byte
Read both GPIO bus states and return a 16 bit value with their state. D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
def ip2long(ip): try: return int(binascii.hexlify(socket.inet_aton(ip)), 16) except socket.error: return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)
Wrapper function for IPv4 and IPv6 converters. :arg ip: IPv4 or IPv6 address
def delete_key(key_name, stash, passphrase, backend): stash = _get_stash(backend, stash, passphrase) for key in key_name: try: click.echo('Deleting key {0}...'.format(key)) stash.delete(key_name=key) except GhostError as ex: sys.exit(ex) click.echo('Keys d...
Delete a key from the stash `KEY_NAME` is the name of the key to delete You can provide that multiple times to delete multiple keys at once
def hsv2rgb_spectrum(hsv): h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
Generates RGB values from HSV values in line with a typical light spectrum.
def create_tree(endpoints): tree = {} for method, url, doc in endpoints: path = [p for p in url.strip('/').split('/')] here = tree version = path[0] here.setdefault(version, {}) here = here[version] for p in path[1:]: part = _camelcase_to_underscore(p)...
Creates the Trello endpoint tree. >>> r = {'1': { \ 'actions': {'METHODS': {'GET'}}, \ 'boards': { \ 'members': {'METHODS': {'DELETE'}}}} \ } >>> r == create_tree([ \ 'GET /1/actions/[idAction]', \ 'DELETE /1/b...
def schedule_play(self, call_params): path = '/' + self.api_version + '/SchedulePlay/' method = 'POST' return self.request(path, method, call_params)
REST Schedule playing something on a call Helper
def warn_if_not_float(X, estimator='This algorithm'): if not isinstance(estimator, str): estimator = estimator.__class__.__name__ if X.dtype.kind != 'f': warnings.warn("%s assumes floating point values as input, " "got %s" % (estimator, X.dtype)) return True ret...
Warning utility function to check that data type is floating point. Returns True if a warning was raised (i.e. the input is not float) and False otherwise, for easier input validation.
def get_zones(input_list): if not input_list: return [] output_list = [] for zone in input_list: if zone.endswith('*'): prefix = zone[:-1] output_list.extend([z for z in _ZONES if z.startswith(prefix)]) else: output_list.append(zone) return output_list
Returns a list of zones based on any wildcard input. This function is intended to provide an easy method for producing a list of desired zones for a pipeline to run in. The Pipelines API default zone list is "any zone". The problem with "any zone" is that it can lead to incurring Cloud Storage egress charges ...
def total_memory(): with file('/proc/meminfo', 'r') as f: for line in f: words = line.split() if words[0].upper() == 'MEMTOTAL:': return int(words[1]) * 1024 raise IOError('MemTotal unknown')
Returns the the amount of memory available for use. The memory is obtained from MemTotal entry in /proc/meminfo. Notes ===== This function is not very useful and not very portable.
def play(self): if not self.is_playing(): self.play_pause() self._is_playing = True self.playEvent(self)
Play the video asynchronously returning control immediately to the calling code
def from_json(cls, fh): if isinstance(fh, str): return cls(json.loads(fh)) else: return cls(json.load(fh))
Load json from file handle. Args: fh (file): File handle to load from. Examlple: >>> with open('data.json', 'r') as json: >>> data = composite.load(json)
def html(tag): return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))
Return sequence of start and end regex patterns for simple HTML tag
def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False): queues = _get_queues(self.g, queues, edge, edge_type) data = np.zeros((0, 6)) for q in queues: dat = self.edge2queue[q].fetch_data() if len(dat) > 0: data = np.vstack((d...
Gets data from all the queues. If none of the parameters are given then data from every :class:`.QueueServer` is retrieved. Parameters ---------- queues : int or an *array_like* of int, (optional) The edge index (or an iterable of edge indices) identifying ...
def IIR_sos_header(fname_out, SOS_mat): Ns, Mcol = SOS_mat.shape f = open(fname_out, 'wt') f.write('//define a IIR SOS CMSIS-DSP coefficient array\n\n') f.write(' f.write(' f.write(' f.write(' f.write('/*********************************************************/\n'); f.write('/* ...
Write IIR SOS Header Files File format is compatible with CMSIS-DSP IIR Directform II Filter Functions Mark Wickert March 2015-October 2016
def requirements_for_changes(self, changes): requirements = [] reqs_set = set() if isinstance(changes, str): changes = changes.split('\n') if not changes or changes[0].startswith('-'): return requirements for line in changes: line = line.strip(...
Parse changes for requirements :param list changes:
def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, ...
Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or iterable of strings, scope(s) to request. code: string, An authorization code, most likely passed down from ...
def parse_file_provider(uri): providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL} provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29})://', uri) if provider_found: prefix = provider_found.group(1).lower() else: prefix = 'file' if prefix in providers: return provid...
Find the file provider for a URI.
def _make_user_class(session, name): attrs = session.eval('fieldnames(%s);' % name, nout=1).ravel().tolist() methods = session.eval('methods(%s);' % name, nout=1).ravel().tolist() ref = weakref.ref(session) doc = _DocDescriptor(ref, name) values = dict(__doc__=doc, _name=name, _ref=ref, _attrs=attrs...
Make an Octave class for a given class name
def put(self, credentials): self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock()
Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.
def getobjectsize(self, window_name, object_name=None): if not object_name: handle, name, app = self._get_window_handle(window_name) else: handle = self._get_object_handle(window_name, object_name) return self._getobjectsize(handle)
Get object size @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type...
def reload_programs(self): print("Reloading programs:") for name, program in self._programs.items(): if getattr(program, 'program', None): print(" - {}".format(program.meta.label)) program.program = resources.programs.load(program.meta)
Reload all shader programs with the reloadable flag set
def crown(self, depth=2): nodes = [] for node in self.leaves: nodes += node.flatten(depth-1) return cluster.unique(nodes)
Returns a list of leaves, nodes connected to leaves, etc.
def run_metrics(command, parser, cl_args, unknown_args): cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ'] topology = cl_args['topology-name'] try: result = tracker_access.get_topology_info(cluster, env, topology, role) spouts = result['physical_plan']['spouts'].keys() bolts...
run metrics subcommand
def guid(self, guid): return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
Determines JSONAPI type for provided GUID
def update(self, dicomset): if not isinstance(dicomset, DicomFileSet): raise ValueError('Given dicomset is not a DicomFileSet.') self.items = list(set(self.items).update(dicomset))
Update this set with the union of itself and dicomset. Parameters ---------- dicomset: DicomFileSet
def condense_ranges(cls, ranges): result = [] if ranges: ranges.sort(key=lambda tup: tup[0]) result.append(ranges[0]) for i in range(1, len(ranges)): if result[-1][1] + 1 >= ranges[i][0]: result[-1] = (result[-1][0], max(result[-1][...
Sorts and removes overlaps
def _get_password_url(self): password_url = None if self._settings["user"] or self._settings["authorization"]: if self._settings["url"]: password_url = self._settings["url"] elif self._settings["base_url"]: password_url = self._settings["base_url"]...
Get URL used for authentication Returns: string: URL
def handle(self, *args, **options): LOGGER.info('Starting assigning enterprise roles to users!') role = options['role'] if role == ENTERPRISE_ADMIN_ROLE: self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options) elif role == ENTERPRISE_OPERATOR_RO...
Entry point for managment command execution.
def _ignore_path(cls, path, ignore_list=None, white_list=None): ignore_list = ignore_list or [] white_list = white_list or [] return (cls._matches_patterns(path, ignore_list) and not cls._matches_patterns(path, white_list))
Returns a whether a path should be ignored or not.
def _get(self, *args, **kwargs): messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs) if self.user.is_authenticated(): inbox_messages = self.backend.inbox_list(self.user) else: inbox_messages = [] return messages + inbox_messages, all_retrieve...
Retrieve unread messages for current user, both from the inbox and from other storages
def _dump_field(self, fd): v = {} v['label'] = Pbd.LABELS[fd.label] v['type'] = fd.type_name if len(fd.type_name) > 0 else Pbd.TYPES[fd.type] v['name'] = fd.name v['number'] = fd.number v['default'] = '[default = {}]'.format(fd.default_value) if len(fd.default_value) > 0 ...
Dump single field.
def set_pkg_license_declared(self, doc, lic): self.assert_package_exists() if not self.package_license_declared_set: self.package_license_declared_set = True if validations.validate_lics_conc(lic): doc.package.license_declared = lic return True ...
Sets the package's declared license. Raises SPDXValueError if data malformed. Raises OrderError if no package previously defined. Raises CardinalityError if already set.
def get_top_long_short_abs(positions, top=10): positions = positions.drop('cash', axis='columns') df_max = positions.max() df_min = positions.min() df_abs_max = positions.abs().max() df_top_long = df_max[df_max > 0].nlargest(top) df_top_short = df_min[df_min < 0].nsmallest(top) df_top_abs = ...
Finds the top long, short, and absolute positions. Parameters ---------- positions : pd.DataFrame The positions that the strategy takes over time. top : int, optional How many of each to find (default 10). Returns ------- df_top_long : pd.DataFrame Top long position...
def calculate_subgraph_edge_overlap( graph: BELGraph, annotation: str = 'Subgraph' ) -> Tuple[ Mapping[str, EdgeSet], Mapping[str, Mapping[str, EdgeSet]], Mapping[str, Mapping[str, EdgeSet]], Mapping[str, Mapping[str, float]], ]: sg2edge = defaultdict(set) for u, v, d in graph.ed...
Build a DatafFame to show the overlap between different sub-graphs. Options: 1. Total number of edges overlap (intersection) 2. Percentage overlap (tanimoto similarity) :param graph: A BEL graph :param annotation: The annotation to group by and compare. Defaults to 'Subgraph' :return: {subgrap...
def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name else: strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer...
Iterates over a generator looking for things that match.
def centerdc_2_twosided(data): N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
Convert a center-dc PSD to a twosided PSD
def course_key_is_valid(course_key): if course_key is None: return False try: CourseKey.from_string(text_type(course_key)) except (InvalidKeyError, UnicodeDecodeError): return False return True
Course key object validation
def create(self, data): self.app_id = None if 'client_id' not in data: raise KeyError('The authorized app must have a client_id') if 'client_secret' not in data: raise KeyError('The authorized app must have a client_secret') return self._mc_client._post(url=self._...
Retrieve OAuth2-based credentials to associate API calls with your application. :param data: The request body parameters :type data: :py:class:`dict` data = { "client_id": string*, "client_secret": string* }
def can(obj): import_needed = False for cls, canner in iteritems(can_map): if isinstance(cls, string_types): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: _import_mapping(can_map, _original_can_map) ...
Prepare an object for pickling.
def _create_folder(local_folder, parent_folder_id): new_folder = session.communicator.create_folder( session.token, os.path.basename(local_folder), parent_folder_id) return new_folder['folder_id']
Function for creating a remote folder and returning the id. This should be a building block for user-level functions. :param local_folder: full path to a local folder :type local_folder: string :param parent_folder_id: id of parent folder on the Midas Server instance, where the new folder will ...
def joint_torques(self): return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF] for j in self.joints)
Get a list of all current joint torques in the skeleton.
def get_heron_dir(): go_above_dirs = 9 path = "/".join(os.path.realpath(__file__).split('/')[:-go_above_dirs]) return normalized_class_path(path)
This will extract heron directory from .pex file. For example, when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc', the internal variable ``path`` would be '/Users/heron...
def queue(users, label, extra_context=None, sender=None): if extra_context is None: extra_context = {} if isinstance(users, QuerySet): users = [row["pk"] for row in users.values("pk")] else: users = [user.pk for user in users] notices = [] for user in users: notices.a...
Queue the notification in NoticeQueueBatch. This allows for large amounts of user notifications to be deferred to a seperate process running outside the webserver.
def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None): db = get_server(server_url)[db_name] if rev: headers, response = db.resource.get(doc_id, rev=rev) return couchdb.client.Document(response) return db[doc_id]
Return a CouchDB document, given its ID, revision and database name.
def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails): existing_users, unregistered_emails = cls.get_users_by_email(emails) successes = [] pending = [] failures = [] for user in existing_users: succeeded = cls.enroll_user(enterprise_cust...
Enroll existing users in a course, and create a pending enrollment for nonexisting users. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment course_id (str): The unique identifier of the course in which we're enrolling course_mode (str): The...
def _get_const_info(const_index, const_list): argval = const_index if const_list is not None: try: argval = const_list[const_index] except IndexError: raise ValidationError("Consts value out of range: {}".format(const_index)) from None return argval, repr(argval)
Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined. Otherwise returns the constant index and its repr().
def isodate(datestamp=None, microseconds=False): datestamp = datestamp or datetime.datetime.now() if not microseconds: usecs = datetime.timedelta(microseconds=datestamp.microsecond) datestamp = datestamp - usecs return datestamp.isoformat(b' ' if PY2 else u' ')
Return current or given time formatted according to ISO-8601.
def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None): return Baystat().dist(src, tar, min_ss_len, left_ext, right_ext)
Return the Baystat distance. This is a wrapper for :py:meth:`Baystat.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison min_ss_len : int Minimum substring length to be considered left_ext : int Left-sid...
def dropbox_submission(dropbox, request): try: data = dropbox_schema.deserialize(request.POST) except Exception: return HTTPFound(location=request.route_url('dropbox_form')) dropbox.message = data.get('message') if 'testing_secret' in dropbox.settings: dropbox.from_watchdog = is_...
handles the form submission, redirects to the dropbox's status page.
def encode_body(req): if isinstance(req.body, text_type): split = req.headers.get('content-type', 'text/plain').split(';') if len(split) == 2: ct, cs = split cs = cs.split('=')[1] req.body = req.body.encode(cs) else: ...
Encode body of request to bytes and update content-type if required. If the body of req is Unicode then encode to the charset found in content-type header if present, otherwise UTF-8, or ASCII if content-type is application/x-www-form-urlencoded. If encoding to UTF-8 then add charset to...
def rows_after(self): rows_after = [] for mesh in self.produced_meshes: if mesh.is_consumed(): row = mesh.consuming_row if rows_after not in rows_after: rows_after.append(row) return rows_after
The rows that consume meshes from this row. :rtype: list :return: a list of rows that consume meshes from this row. Each row occurs only once. They are sorted by the first occurrence in the instructions.
def get_suggested_filename(metadata): if metadata.get('title') and metadata.get('track_number'): suggested_filename = '{track_number:0>2} {title}'.format(**metadata) elif metadata.get('title') and metadata.get('trackNumber'): suggested_filename = '{trackNumber:0>2} {title}'.format(**metadata) elif metadata.get('...
Generate a filename for a song based on metadata. Parameters: metadata (dict): A metadata dict. Returns: A filename.
def merge_images(images, axis='t'): if not images: return None axis_dim = {'x': 0, 'y': 1, 'z': 2, 't': 3, } if axis not in axis_dim: raise ValueError('Expected `axis` to be one of ({}), got {}.'.format(set(axis_dim.keys()), axi...
Concatenate `images` in the direction determined in `axis`. Parameters ---------- images: list of str or img-like object. See NeuroImage constructor docstring. axis: str 't' : concatenate images in time 'x' : concatenate images in the x direction 'y' : concatenate images in t...
def connect(self): if not self.connected(): self._ws = create_connection(self.WS_URI) message = { 'type':self.WS_TYPE, 'product_id':self.WS_PRODUCT_ID } self._ws.send(dumps(message)) with self._lock: if not self._thread: thread = Thread(target=self._ke...
Connects and subscribes to the WebSocket Feed.
def finalizeOp(self, ops, account, permission, **kwargs): if "append_to" in kwargs and kwargs["append_to"]: if self.proposer: log.warning( "You may not use append_to and self.proposer at " "the same time. Append new_proposal(..) instead" ...
This method obtains the required private keys if present in the wallet, finalizes the transaction, signs it and broadacasts it :param operation ops: The operation (or list of operaions) to broadcast :param operation account: The account that authorizes th...
def org_by_name(self, hostname): addr = self._gethostbyname(hostname) return self.org_by_addr(addr)
Returns Organization, ISP, or ASNum name for given hostname. :arg hostname: Hostname (e.g. example.com)
def human_transactions(self): txs = [] for tx in self.transactions: if tx.depth == 0: txs.append(tx) return tuple(txs)
Completed human transaction
def issue_line_with_user(self, line, issue): if not issue.get("pull_request") or not self.options.author: return line if not issue.get("user"): line += u" (Null user)" elif self.options.username_as_tag: line += u" (@{0})".format( issue["user"][...
If option author is enabled, a link to the profile of the author of the pull reqest will be added to the issue line. :param str line: String containing a markdown-formatted single issue. :param dict issue: Fetched issue from GitHub. :rtype: str :return: Issue line with added aut...
def _get_children_as_string(node): out = [] if node: for child in node: if child.nodeType == child.TEXT_NODE: out.append(child.data) else: out.append(_get_children_as_string(child.childNodes)) return ''.join(out)
Iterate through all the children of a node. Returns one string containing the values from all the text-nodes recursively.
def _import_mapping(mapping, original=None): for key, value in list(mapping.items()): if isinstance(key, string_types): try: cls = import_item(key) except Exception: if original and key not in original: print("ERROR: canning class n...
Import any string-keys in a type mapping.
def init_raspbian_vm(self): r = self.local_renderer r.comment('Installing system packages.') r.sudo('add-apt-repository ppa:linaro-maintainers/tools') r.sudo('apt-get update') r.sudo('apt-get install libsdl-dev qemu-system') r.comment('Download image.') r.local('w...
Creates an image for running Raspbian in a QEMU virtual machine. Based on the guide at: https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel
def read_chunk(filename, offset=-1, length=-1, escape_data=False): try: length = int(length) offset = int(offset) except ValueError: return {} if not os.path.isfile(filename): return {} try: fstat = os.stat(filename) except Exception: return {} if offset == -1: offset = fstat.st_...
Read a chunk of a file from an offset upto the length.
def find_matching(cls, path, patterns): for pattern in patterns: if pattern.match(path): yield pattern
Yield all matching patterns for path.
def export(self): graph = nx.MultiDiGraph() regions = self.network.getRegions() for idx in xrange(regions.getCount()): regionPair = regions.getByIndex(idx) regionName = regionPair[0] graph.add_node(regionName, label=regionName) for linkName, link in self.network.getLinks(): graph...
Exports a network as a networkx MultiDiGraph intermediate representation suitable for visualization. :return: networkx MultiDiGraph
def mapCellsToColumns(self, cells): cellsForColumns = defaultdict(set) for cell in cells: column = self.columnForCell(cell) cellsForColumns[column].add(cell) return cellsForColumns
Maps cells to the columns they belong to. :param cells: (set) Cells :returns: (dict) Mapping from columns to their cells in `cells`
def get_notification_subject_line(course_name, template_configuration=None): stock_subject_template = _('You\'ve been enrolled in {course_name}!') default_subject_template = getattr( settings, 'ENTERPRISE_ENROLLMENT_EMAIL_DEFAULT_SUBJECT_LINE', stock_subject_template, ) if templa...
Get a subject line for a notification email. The method is designed to fail in a "smart" way; if we can't render a database-backed subject line template, then we'll fall back to a template saved in the Django settings; if we can't render _that_ one, then we'll fall through to a friendly string written ...
def wheel_helper(pos, length, cycle_step): return wheel_color((pos * len(_WHEEL) / length) + cycle_step)
Helper for wheel_color that distributes colors over length and allows shifting position.
def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs)
Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that ta...
def is_empty(self): if len(self.val) != 0: if isinstance(self.val, str_types): self._err('Expected <%s> to be empty string, but was not.' % self.val) else: self._err('Expected <%s> to be empty, but was not.' % self.val) return self
Asserts that val is empty.
def _reproject(self, p): nulls = self.problem.nullspace equalities = self.problem.equalities if np.allclose(equalities.dot(p), self.problem.b, rtol=0, atol=self.feasibility_tol): new = p else: LOGGER.info("feasibility violated in sample" ...
Reproject a point into the feasibility region. This function is guaranteed to return a new feasible point. However, no guarantees in terms of proximity to the original point can be made. Parameters ---------- p : numpy.array The current sample point. Return...
def add_tags(self, tags): return self.get_data( "firewalls/%s/tags" % self.id, type=POST, params={"tags": tags} )
Add tags to this Firewall.
def get_md_status(self, line): ret = {} splitted = split('\W+', line) if len(splitted) < 7: ret['available'] = None ret['used'] = None ret['config'] = None else: ret['available'] = splitted[-4] ret['used'] = splitted[-3] ...
Return a dict of md status define in the line.
def NormalizePath(path): if path.endswith('/') or path.endswith('\\'): slash = os.path.sep else: slash = '' return os.path.normpath(path) + slash
Normalizes a path maintaining the final slashes. Some environment variables need the final slash in order to work. Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used in the Visual Studio projects. :param unicode path: The path to normalize. :rtype: ...
def numeric_task_id(task_id): if task_id is not None: if task_id.startswith('task-'): return int(task_id[len('task-'):]) else: return int(task_id)
Converts a task-id to the numeric task-id. Args: task_id: task-id in either task-n or n format Returns: n
def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None): expected_read_counts = self.probability.sum(axis=APM.Axis.READ) if grp_wise: lname = self.probability.gname expected_read_counts = expected_read_counts * self.grp_conv_mat else: ...
Exports expected read counts :param filename: File name for output :param grp_wise: whether the report is at isoform level or gene level :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is' :return: Nothing but the method writes a file
def get_repr(self, obj, referent=None): objtype = type(obj) typename = str(objtype.__module__) + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if name: prettytype = "%s %r" % (prettytype, name) key...
Return an HTML tree block describing the given object.
def _adaptToResource(self, result): if result is None: return NotFound() spinneretResource = ISpinneretResource(result, None) if spinneretResource is not None: return SpinneretResource(spinneretResource) renderable = IRenderable(result, None) if renderable...
Adapt a result to `IResource`. Several adaptions are tried they are, in order: ``None``, `IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource <twisted:twisted.web.resource.IResource>`, and `URLPath <twisted:twisted.python.urlpath.URLPath>`. Anything else is returned as ...
def textpath(self, txt, x, y, width=None, height=1000000, enableRendering=False, **kwargs): txt = self.Text(txt, x, y, width, height, **kwargs) path = txt.path if draw: path.draw() return path
Draws an outlined path of the input text
def anomalyRemoveLabels(self, start, end, labelFilter): self._getAnomalyClassifier().getSelf().removeLabels(start, end, labelFilter)
Remove labels from the anomaly classifier within this model. Removes all records if ``labelFilter==None``, otherwise only removes the labels equal to ``labelFilter``. :param start: (int) index to start removing labels :param end: (int) index to end removing labels :param labelFilter: (string) If sp...
def iterwindows(self, count=64, window_shape=(256, 256)): if count is None: while True: yield self.randwindow(window_shape) else: for i in xrange(count): yield self.randwindow(window_shape)
Iterate over random windows of an image Args: count (int): the number of the windows to generate. Defaults to 64, if `None` will continue to iterate over random windows until stopped. window_shape (tuple): The desired shape of each image as (height, width) in pixels. Yields: ...
def proto_04_01_MTmon70s2(abf=exampleABF): standard_inspect(abf) swhlab.memtest.memtest(abf) swhlab.memtest.checkSweep(abf) swhlab.plot.save(abf,tag='check',resize=False) swhlab.memtest.plot_standard4(abf) swhlab.plot.save(abf,tag='memtests')
repeated membrane tests, likely with drug added. Maybe IPSCs.
def getTopologyByClusterRoleEnvironAndName(self, cluster, role, environ, topologyName): topologies = list(filter(lambda t: t.name == topologyName and t.cluster == cluster and (not role or t.execution_state.role == role) and t.env...
Find and return the topology given its cluster, environ, topology name, and an optional role. Raises exception if topology is not found, or more than one are found.
def hierarchy_flatten(annotation): intervals, values = annotation.to_interval_values() ordering = dict() for interval, value in zip(intervals, values): level = value['level'] if level not in ordering: ordering[level] = dict(intervals=list(), labels=list()) ordering[level]...
Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists of intervals, ordered by increasing specificity. hier_labels : l...