text
stringlengths
81
112k
Connect the specified input to a wire. def connect_input(self, name, wire): """Connect the specified input to a wire.""" self._inputs[name] = wire wire.sinks.append(self)
Write the configuration for this gate to memory. def _write_config(self, memory): """Write the configuration for this gate to memory.""" memory.seek(0) memory.write(struct.pack("<5I", # sim_length self._simulator.length, ...
Probe the specified wire. def connect_input(self, wire): """Probe the specified wire.""" self._input = wire wire.sinks.append(self)
Write the configuration for this probe to memory. def _write_config(self, memory): """Write the configuration for this probe to memory.""" memory.seek(0) memory.write(struct.pack("<II", # sim_length self._simulator.length, ...
Read back the probed results. Returns ------- str A string of "0"s and "1"s, one for each millisecond of simulation. def _read_results(self, memory): """Read back the probed results. Returns ------- str A string of "0"s and "1"s, one for...
Write the configuration for this stimulus to memory. def _write_config(self, memory): """Write the configuration for this stimulus to memory.""" memory.seek(0) memory.write(struct.pack("<II", # sim_length self._simulator.length, ...
Create a new :py:class:`._Wire` with a unique routing key. def _new_wire(self, source, sinks=None): """Create a new :py:class:`._Wire` with a unique routing key.""" # Assign sequential routing key to new nets. wire = _Wire(source, sinks if sinks is not None else [], len(self._wires)) se...
Run the simulation. def run(self): """Run the simulation.""" # Define the resource requirements of each component in the simulation. vertices_resources = { # Every component runs on exactly one core and consumes a certain # amount of SDRAM to hold configuration data. ...
Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to write dataframes to files :param nb_path: path to a notebook. :param pkg_dir: Directory to which dataframes are materialized :param dataframes: List of names of dataframes to materialize :return: a Noteboo...
Run only the document conversion portion of the notebook conversion The final document will not be completel def convert_documentation(nb_path): """Run only the document conversion portion of the notebook conversion The final document will not be completel """ with open(nb_path) as f: ...
Create a metadata dict from a MetatabDoc, for Document conversion def doc_metadata(doc): """Create a metadata dict from a MetatabDoc, for Document conversion""" r = doc['Root'].as_dict() r.update(doc['Contacts'].as_dict()) r['author'] = r.get('author', r.get('creator', r.get('wrangler'))) return ...
Extract the metatab lines from a notebook and return a Metapack doc def extract_notebook_metatab(nb_path: Path): """Extract the metatab lines from a notebook and return a Metapack doc """ from metatab.rowgenerators import TextRowGenerator import nbformat with nb_path.open() as f: nb = nbforma...
Publish a notebook to a wordpress post, using Gutenberg blocks. Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter' show_input: hide github: https://github.com/sandiegodata/notebooks/blob/master/tutorial/American%20Community%20Survey.ipynb identifier: 5c987397-a954-...
Add a single resource, without trying to enumerate it's contents :param ref: :return: def add_single_resource(self, ref, **properties): """ Add a single resource, without trying to enumerate it's contents :param ref: :return: """ t = self.doc.find_first('Root.Da...
Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file def add_resource(self, ref, **properties): """Add one or more resources entities, from a url and property values, possibly adding multiple entries for an exc...
Clean the doc before writing it, removing unnecessary properties and doing other operations. def _clean_doc(self, doc=None): """Clean the doc before writing it, removing unnecessary properties and doing other operations.""" if doc is None: doc = self.doc resources = doc['Resources...
Copy all of the Datafile entries into the package def _load_resources(self, abs_path=False): """Copy all of the Datafile entries into the package""" from metapack.doc import MetapackDoc assert type(self.doc) == MetapackDoc for r in self.datafiles: # Special handling for S...
Copy all of the Datafile def _load_documentation_files(self): """Copy all of the Datafile """ for t in self.doc.find(['Root.Documentation', 'Root.Image', 'Root.Notebook']): resource = self._get_ref_contents(t) if not resource: continue if t.term_i...
Load other files def _load_files(self): """Load other files""" def copy_dir(path): for (dr, _, files) in walk(path): for fn in files: if '__pycache__' in fn: continue relpath = dr.replace(self.source_dir, '')...
After a save(), write a link to the saved file using a non-versioned name def create_nv_link(self): """After a save(), write a link to the saved file using a non-versioned name""" from os.path import abspath, islink from os import unlink, symlink nv_name = self.doc.as_version(None) ...
Enqueue a batch of jobs. def enqueue_jobs(self, jobs: Iterable[Job]): """Enqueue a batch of jobs.""" for job in jobs: if job.should_start: job.status = JobStatus.QUEUED queue = self._get_queue(job.queue) queue.put(job.serialize()) ...
Register tasks that need to be scheduled periodically. def register_periodic_tasks(self, tasks: Iterable[Task]): """Register tasks that need to be scheduled periodically.""" for task in tasks: self._scheduler.enter( int(task.periodicity.total_seconds()), 0, ...
Give the amount of seconds before the next periodic task is due. def next_future_periodic_delta(self) -> Optional[float]: """Give the amount of seconds before the next periodic task is due.""" try: next_event = self._scheduler.queue[0] except IndexError: return None ...
Get the next periodic task schedule. Used only for debugging and during tests. def inspect_periodic_tasks(self) -> List[Tuple[int, str]]: """Get the next periodic task schedule. Used only for debugging and during tests. """ return [(int(e[0]), e[3][0].name) for e in self._sche...
Get jobs from a queue. def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]: """Get jobs from a queue.""" rv = list() while len(rv) < max_jobs: try: job_json_string = self._get_queue(queue).get(block=False) except Empty: b...
This method will try to return the first <p> or <div> that contains an <a> tag linking to the given URL. def snippetWithLink(self, url): """ This method will try to return the first <p> or <div> that contains an <a> tag linking to the given URL. """ link = self.s...
An example row generator function. Reference this function in a Metatab file as the value of a Datafile: Datafile: python:pylib#row_generator The function must yield rows, with the first being headers, and subsequenct rows being data. :param resource: The Datafile term being processed :p...
An example column transform. This is an example of a column transform with all of the arguments listed. An real transform can omit any ( or all ) of these, and can supply them in any order; the calling code will inspect the signature. When the function is listed as a transform for a column, it is call...
Return the default local index file, from the download cache def search_index_file(): """Return the default local index file, from the download cache""" from metapack import Downloader from os import environ return environ.get('METAPACK_SEARCH_INDEX', Downloader.get_instance().c...
Safely write the index data to the index file def write(self): """Safely write the index data to the index file """ index_file = self.path new_index_file = index_file + '.new' bak_index_file = index_file + '.bak' if not self._db: return with open(new_index_...
Update from another index or index dict def update(self,o): """Update from another index or index dict""" self.open() try: self._db.update(o._db) except AttributeError: self._db.update(o)
Print Tile bounds. def bounds(ctx, tile): """Print Tile bounds.""" click.echo( '%s %s %s %s' % TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ).tile(*tile).bounds(pixelbuffer=ctx.obj['pixelbuffer']) )
Print Tile bounding box as geometry. def bbox(ctx, tile): """Print Tile bounding box as geometry.""" geom = TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer']) if ctx.obj['output_fo...
Print Tile containing POINT.. def tile(ctx, point, zoom): """Print Tile containing POINT..""" tile = TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ).tile_from_xy(*point, zoom=zoom) if ctx.obj['output_format'] == 'Tile': cl...
Print Tiles from bounds. def tiles(ctx, bounds, zoom): """Print Tiles from bounds.""" tiles = TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ).tiles_from_bounds(bounds, zoom=zoom) if ctx.obj['output_format'] == 'Tile': for ...
Snap bbox to tile grid. def snap_bbox(ctx, bounds, zoom): """Snap bbox to tile grid.""" click.echo(box(*tilematrix.snap_bounds( bounds=bounds, tile_pyramid=TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ...
A random placer. This algorithm performs uniform-random placement of vertices (completely ignoring connectivty) and thus in the general case is likely to produce very poor quality placements. It exists primarily as a baseline comparison for placement quality and is probably of little value to most user...
For internal use. Produces a random, sequential initial placement, updating the resource availabilities of every core in the supplied machine. Parameters ---------- movable_vertices : {vertex, ...} A set of the vertices to be given a random initial placement. vertices_resources : {vertex: {...
A flat Simulated Annealing based placement algorithm. This placement algorithm uses simulated annealing directly on the supplied problem graph with the objective of reducing wire lengths (and thus, indirectly, the potential for congestion). Though computationally expensive, this placer produces relativ...
Update a citation dictionary by editing the Author field :param td: A BixTex format citation dict or a term :return: def make_citation_dict(td): """ Update a citation dictionary by editing the Author field :param td: A BixTex format citation dict or a term :return: """ from datetime im...
Return a dict with BibText key/values for metatab data :param t: :return: def make_metatab_citation_dict(t): """ Return a dict with BibText key/values for metatab data :param t: :return: """ try: if parse_app_url(t.url).proto == 'metatab': try: url...
Render citations, from a document or a doct of dicts If the input is a dict, each key is the name of the citation, and the value is a BibTex formatted dict :param doc: A MetatabDoc, or a dict of BibTex dicts :return: def _bibliography(doc, terms, converters=[], format='html'): """ Render cita...
Create a Jinja context for display def display_context(doc): """Create a Jinja context for display""" from rowgenerators.exceptions import DownloadError context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'} #import json #print(json.dumps(context, indent=4)) manda...
Markdown, specifically for the Notes field in a CKAN dataset def markdown(doc, title=True, template='short_documentation.md'): """Markdown, specifically for the Notes field in a CKAN dataset""" from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader...
A generator which iterates over a set of vertices in a breadth-first order in terms of connectivity. For use as a vertex ordering for the sequential placer. def breadth_first_vertex_order(vertices_resources, nets): """A generator which iterates over a set of vertices in a breadth-first order in terms ...
Places vertices in breadth-first order onto chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm which uses the :py:func:`breadth_first_vertex_order` vertex ordering. Parameters ---------- chip_order : No...
Produces a :class:`Comic` object for a random xkcd comic. Uses the Python standard library random number generator in order to select a comic. Returns the resulting comic object. def getRandomComic(): """ Produces a :class:`Comic` object for a random xkcd comic. Uses the Python standard library random number...
Produces a :class:`Comic` object with index equal to the provided argument. Prints an error in the event of a failure (i.e. the number is less than zero or greater than the latest comic number) and returns an empty Comic object. Arguments: an integer or string that represents a number, "number", that is the i...
Parses the xkcd What If archive. getWhatIfArchive passes the HTML text of the archive page into a :class:`WhatIfArchiveParser` and then calls the parser's :func:`WhatIfArchiveParser.getWhatIfs` method and returns the dictionary produced. This function returns a dictionary mapping article numbers to :class:`WhatI...
Returns a randomly generated :class:`WhatIf` object, using the Python standard library random number generator to select the object. The object is returned from the dictionary produced by :func:`getWhatIfArchive`; like the other What If routines, this function is called first in order to get a list of all previou...
Returns a :class:`WhatIf` object corresponding to the What If article of index passed to the function. If the index is less than zero or greater than the maximum number of articles published thus far, None is returned instead. Like all the routines for handling What If articles, :func:`getWhatIfArchive` is c...
Utility function that converts a unicode string to ASCII. This exists so the :class:`Comic` class can be compatible with Python 2 libraries that expect ASCII strings, such as Twisted (as of this writing, anyway). It is unlikely something you will need directly, and its use is discouraged. Arguments: stri...
Downloads the image of the comic onto your computer. Arguments: output: the output directory where comics will be downloaded to. The default argument for 'output is the empty string; if the empty string is passed, it defaults to a "Downloads" directory in your home folder (this directory will be cre...
Replace local hyperlinks in RST with absolute addresses using the given base URL. This is used to make links in the long description function correctly outside of the repository (e.g. when published on PyPi). NOTE: This may need adjusting if further syntax is used. def replace_local_hyperlinks( ...
Create a metatab file for the index def dump_index(args, idx): """Create a metatab file for the index""" import csv import sys from metatab import MetatabDoc doc = MetatabDoc() pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format']) r = doc['Ro...
Setup the layer two agent. def _setup(self): """Setup the layer two agent.""" agent_config = CONF.get("AGENT", {}) self._worker_count = agent_config.get('worker_count') self._phys_net_map = agent_config.get( 'physical_network_vswitch_mappings', []) self._local_networ...
Setup the RPC client for the current agent. def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN) self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN) self._client = n_rpc.get_client(self.target) ...
Callback for added ports. def _process_added_port_event(self, port_name): """Callback for added ports.""" LOG.info("Hyper-V VM vNIC added: %s", port_name) self._added_ports.add(port_name)
Load all the information regarding the physical network. def _load_physical_network_mappings(self, phys_net_vswitch_mappings): """Load all the information regarding the physical network.""" for mapping in phys_net_vswitch_mappings: parts = mapping.split(':') if len(parts) != 2: ...
Get the vswitch name for the received network information. def _get_vswitch_name(self, network_type, physical_network): """Get the vswitch name for the received network information.""" if network_type != constants.TYPE_LOCAL: vswitch_name = self._get_vswitch_for_physical_network( ...
Get the vswitch name for the received network name. def _get_vswitch_for_physical_network(self, phys_network_name): """Get the vswitch name for the received network name.""" for pattern in self._physical_network_mappings: if phys_network_name is None: phys_network_name = '' ...
Get the vswitch name for the received port id. def _get_network_vswitch_map_by_port_id(self, port_id): """Get the vswitch name for the received port id.""" for network_id, vswitch in six.iteritems(self._network_vswitch_map): if port_id in vswitch['ports']: return (network_id...
Update the ports status cache. def _update_port_status_cache(self, device, device_bound=True): """Update the ports status cache.""" with self._cache_lock: if device_bound: self._bound_ports.add(device) self._unbound_ports.discard(device) else: ...
Create and bind the event listeners. def _create_event_listeners(self): """Create and bind the event listeners.""" LOG.debug("Create the event listeners.") for event_type, callback in self._event_callback_pairs: LOG.debug("Create listener for %r event", event_type) liste...
Bind the port to the recived network. def _port_bound(self, port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov): """Bind the port to the recived network.""" LOG.debug("Binding port %s", port_id) if network_id not in s...
Process the new ports. Wraps _process_added_port, and treats the sucessful and exception cases. def process_added_port(self, device_details): """Process the new ports. Wraps _process_added_port, and treats the sucessful and exception cases. """ device = device_...
Process the new devices. def _treat_devices_added(self): """Process the new devices.""" try: devices_details_list = self._plugin_rpc.get_devices_details_list( self._context, self._added_ports, self._agent_id) except Exception as exc: LOG.debug("Unable to ...
Process the removed ports. def _process_removed_port(self, device): """Process the removed ports.""" LOG.debug("Trying to remove the port %r", device) self._update_port_status_cache(device, device_bound=False) self._port_unbound(device, vnic_deleted=True) LOG.debug("The port wa...
Process the removed devices. def _treat_devices_removed(self): """Process the removed devices.""" for device in self._removed_ports.copy(): eventlet.spawn_n(self._process_removed_port, device)
Process the information regarding the available ports. def _work(self): """Process the information regarding the available ports.""" if self._refresh_cache: # Inconsistent cache might cause exceptions. For example, # if a port has been removed, it will be known in the next ...
Build source packages. The mp build program runs all of the resources listed in a Metatab file and produces one or more Metapack packages with those resources localized. It will always try to produce a Filesystem package, and may optionally produce Excel, Zip and CSV packages. Typical usage is to ...
Create local Zip, Excel and Filesystem packages :param m: :param skip_if_exists: :return: def metatab_derived_handler(m): """Create local Zip, Excel and Filesystem packages :param m: :param skip_if_exists: :return: """ from metapack.exc import PackageError from metapack.util i...
Initialize features that are normally initialized in the CLI def init(): """Initialize features that are normally initialized in the CLI""" from metapack.appurl import SearchUrl import metapack as mp from os import environ SearchUrl.initialize() # This makes the 'index:" urls work mp.Downloa...
Interpret a struct file defining the location of variables in memory. Parameters ---------- struct_data : :py:class:`bytes` String of :py:class:`bytes` containing data to interpret as the struct definition. Returns ------- {struct_name: :py:class:`~.Struct`} A dictionar...
Convert a value from one of several bases to an int. def num(value): """Convert a value from one of several bases to an int.""" if re_hex_num.match(value): return int(value, base=16) else: return int(value)
Replace the default values of specified fields. Parameters ---------- Parameters are taken as keyword-arguments of `field=new_value`. Raises ------ KeyError If a field doesn't exist in the struct. def update_default_values(self, **updates): """Repla...
Pack the struct (and its default values) into a string of bytes. Returns ------- :py:class:`bytes` Byte-string representation of struct containing default values. def pack(self): """Pack the struct (and its default values) into a string of bytes. Returns --...
Give the amount of seconds before the next future job is due. def next_future_job_delta(self) -> Optional[float]: """Give the amount of seconds before the next future job is due.""" job = self._get_next_future_job() if not job: return None return (job.at - datetime.now(timez...
Allocate and return a file-like view of a region of SDRAM for each vertex which uses SDRAM as a resource. The tag assigned to each region of assigned SDRAM is the index of the first core that each vertex is assigned. For example:: placements = {vertex: (0, 5)} allocations = {vertex: {Core...
Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals. def advance_job_status(namespace: str, job: Job, duration: float, err: Optional[Exception]): """Advance the...
Return Tile object of this TilePyramid. - zoom: zoom level - row: tile matrix row - col: tile matrix column def tile(self, zoom, row, col): """ Return Tile object of this TilePyramid. - zoom: zoom level - row: tile matrix row - col: tile matrix column ...
Tile matrix width (number of columns) at zoom level. - zoom: zoom level def matrix_width(self, zoom): """ Tile matrix width (number of columns) at zoom level. - zoom: zoom level """ validate_zoom(zoom) width = int(math.ceil(self.grid.shape.width * 2**(zoom) / s...
Tile matrix height (number of rows) at zoom level. - zoom: zoom level def matrix_height(self, zoom): """ Tile matrix height (number of rows) at zoom level. - zoom: zoom level """ validate_zoom(zoom) height = int(math.ceil(self.grid.shape.height * 2**(zoom) / se...
Width of a tile in SRID units at zoom level. - zoom: zoom level def tile_x_size(self, zoom): """ Width of a tile in SRID units at zoom level. - zoom: zoom level """ warnings.warn(DeprecationWarning("tile_x_size is deprecated")) validate_zoom(zoom) retur...
Height of a tile in SRID units at zoom level. - zoom: zoom level def tile_y_size(self, zoom): """ Height of a tile in SRID units at zoom level. - zoom: zoom level """ warnings.warn(DeprecationWarning("tile_y_size is deprecated")) validate_zoom(zoom) ret...
Tile width in pixel. - zoom: zoom level def tile_width(self, zoom): """ Tile width in pixel. - zoom: zoom level """ warnings.warn(DeprecationWarning("tile_width is deprecated")) validate_zoom(zoom) matrix_pixel = 2**(zoom) * self.tile_size * self.grid.s...
Tile height in pixel. - zoom: zoom level def tile_height(self, zoom): """ Tile height in pixel. - zoom: zoom level """ warnings.warn(DeprecationWarning("tile_height is deprecated")) validate_zoom(zoom) matrix_pixel = 2**(zoom) * self.tile_size * self.gr...
Width of a pixel in SRID units at zoom level. - zoom: zoom level def pixel_x_size(self, zoom): """ Width of a pixel in SRID units at zoom level. - zoom: zoom level """ validate_zoom(zoom) return round( (self.grid.right - self.grid.left) / ...
Height of a pixel in SRID units at zoom level. - zoom: zoom level def pixel_y_size(self, zoom): """ Height of a pixel in SRID units at zoom level. - zoom: zoom level """ validate_zoom(zoom) return round( (self.grid.top - self.grid.bottom) / ...
Return all tiles intersecting with bounds. Bounds values will be cleaned if they cross the antimeridian or are outside of the Northern or Southern tile pyramid bounds. - bounds: tuple of (left, bottom, right, top) bounding values in tile pyramid CRS - zoom: zoom level def ...
All metatiles intersecting with given bounding box. - geometry: shapely geometry - zoom: zoom level def tiles_from_bbox(self, geometry, zoom): """ All metatiles intersecting with given bounding box. - geometry: shapely geometry - zoom: zoom level """ va...
Return all tiles intersecting with input geometry. - geometry: shapely geometry - zoom: zoom level def tiles_from_geom(self, geometry, zoom): """ Return all tiles intersecting with input geometry. - geometry: shapely geometry - zoom: zoom level """ vali...
Return tile covering a point defined by x and y values. - x: x coordinate - y: y coordinate - zoom: zoom level - on_edge_use: determine which Tile to pick if Point hits a grid edge - rb: right bottom (default) - rt: right top - lt: left top ...
Get ladder metadata. def get_ladder_metadata(session, url): """Get ladder metadata.""" parsed = make_scrape_request(session, url) tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX)) return { 'id': int(tag['href'].split('/')[-1]), 'slug': url.split('/')[-1], 'url': url }
Get metadata for all ladders. def get_ladders_metadata(session, parsed): """Get metadata for all ladders.""" ladders = {} for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)): ladders[ladder.text] = get_ladder_metadata(session, ladder['href']) return ladders
Get metadata for games (only ladder data right now). def get_metadata(session, games): """Get metadata for games (only ladder data right now).""" for data in games.values(): parsed = make_scrape_request(session, data['url']) return { 'ladders': get_ladders_metadata(session, parsed) }
Update metadata files (only ladders right now). def update_metadata(session, path=DATA_PATH): """Update metadata files (only ladders right now).""" with open(os.path.join(path, 'games.json')) as handle: games = json.loads(handle.read()) for key, data in get_metadata(session, games).items(): ...
Sample every router counter in the machine. def sample_counters(mc, system_info): """Sample every router counter in the machine.""" return { (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info }
Return the change in counter values (accounting for wrap-around). def deltas(last, now): """Return the change in counter values (accounting for wrap-around).""" return { xy: RouterDiagnostics(*((n - l) & 0xFFFFFFFF for l, n in zip(last[xy], now[xy]))) for xy in l...
Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields. def monitor_counters(mc, output, counters, detailed, f): """Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields.""" # Print CSV header output.write("t...