code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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': click.echo('%s %s %s' % tile.id) elif ctx.obj['output_format'] == 'WKT': click.echo(...
def tile(ctx, point, zoom)
Print Tile containing POINT..
2.517834
2.506994
1.004324
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 tile in tiles: click.echo('%s %s %s' % tile.id) elif ctx.obj['output_f...
def tiles(ctx, bounds, zoom)
Print Tiles from bounds.
2.624062
2.6005
1.009061
click.echo(box(*tilematrix.snap_bounds( bounds=bounds, tile_pyramid=TilePyramid( ctx.obj['grid'], tile_size=ctx.obj['tile_size'], metatiling=ctx.obj['metatiling'] ), zoom=zoom, pixelbuffer=ctx.obj['pixelbuffer'] )))
def snap_bbox(ctx, bounds, zoom)
Snap bbox to tile grid.
5.005229
4.888941
1.023786
# Within the algorithm we modify the resource availability values in the # machine to account for the effects of the current placement. As a result, # an internal copy of the structure must be made. machine = machine.copy() # {vertex: (x, y), ...} gives the location of all vertices, updated ...
def place(vertices_resources, nets, machine, constraints, random=default_random)
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...
4.888489
5.027544
0.972341
# Initially fill chips in the system in a random order locations = list(machine) random.shuffle(locations) location_iter = iter(locations) # Greedily place the vertices in a random order movable_vertices = list(v for v in vertices_resources if v in movable_verti...
def _initial_placement(movable_vertices, vertices_resources, machine, random)
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: {...
3.742077
3.618949
1.034023
from datetime import datetime if isinstance(td, dict): d = td name = d['name_link'] else: d = td.as_dict() d['_term'] = td try: d['name_link'] = td.name except AttributeError: d['name_link'] = td['name_link'].value if 'aut...
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:
2.634501
2.594712
1.015335
try: if parse_app_url(t.url).proto == 'metatab': try: url = parse_app_url(str(t.resolved_url)).resource_url doc = t.row_generator.generator.package except AttributeError as e: return False # It isn't a resource or reference ...
def make_metatab_citation_dict(t)
Return a dict with BibText key/values for metatab data :param t: :return:
5.028544
5.063888
0.99302
output_backend = 'latex' if format == 'latex' else MetatabHtmlBackend def mk_cite(v): for c in converters: r = c(v) if r is not False: return r return make_citation_dict(v) if isinstance(doc, MetatabDoc): # This doesn't work for LaTex...
def _bibliography(doc, terms, converters=[], format='html')
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:
7.145332
6.920227
1.032529
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)) mandatory_sections = ['documentation', 'contacts'] # Remove section names deletes = [] for k,v...
def display_context(doc)
Create a Jinja context for display
4.532511
4.531472
1.000229
from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader('metapack', 'support/templates') #autoescape=select_autoescape(['html', 'xml']) ) context = display_context(doc) return env.get_template(template).render(**context)
def markdown(doc, title=True, template='short_documentation.md')
Markdown, specifically for the Notes field in a CKAN dataset
3.091954
3.078402
1.004402
# Special case: no vertices, just stop immediately if len(vertices_resources) == 0: return # Enumerate the set of nets attached to each vertex vertex_neighbours = defaultdict(set) for net in nets: # Note: Iterating over a Net object produces the set of vertices # involv...
def breadth_first_vertex_order(vertices_resources, nets)
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.
2.930072
2.820943
1.038686
return sequential_place(vertices_resources, nets, machine, constraints, breadth_first_vertex_order(vertices_resources, nets), chip_order)
def place(vertices_resources, nets, machine, constraints, chip_order=None)
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...
5.645202
4.923531
1.146576
random.seed() numComics = getLatestComicNum() number = random.randint(1, numComics) return Comic(number)
def getRandomComic()
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.
4.22739
5.31024
0.796083
numComics = getLatestComicNum() if type(number) is str and number.isdigit(): number = int(number) if number > numComics or number <= 0: if not silent: print("Error: You have requested an invalid comic.") return Comic(-1) return Comic(number)
def getComic(number, silent=True)
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...
2.998131
3.135028
0.956333
archive = urllib.urlopen(archiveUrl) text = archive.read() if sys.version_info[0] >= 3: text = text.decode('utf-8') archive.close() parser = WhatIfArchiveParser() parser.feed(text) return parser.getWhatIfs()
def getWhatIfArchive()
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...
2.774344
2.49985
1.109804
random.seed() archive = getWhatIfArchive() latest = getLatestWhatIfNum(archive) number = random.randint(1, latest) return archive[number]
def getRandomWhatIf()
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...
5.43904
4.639356
1.17237
archive = getWhatIfArchive() latest = getLatestWhatIfNum(archive) if type(number) is str and number.isdigit(): number = int(number) if number > latest or latest <= 0: return None return archive[number]
def getWhatIf(number)
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...
4.476821
4.325706
1.034934
running = True asciiString = string while running: try: asciiString = asciiString.encode('ascii') except UnicodeError as unicode: start = unicode.start end = unicode.end asciiString = asciiString[:start] + "?" + asciiString[end:] else: running = False return asciiString
def convertToAscii(string, error="?")
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...
2.907311
3.141098
0.925572
image = urllib.urlopen(self.imageLink).read() #Process optional input to work out where the dowload will go and what it'll be called if output != "": output = os.path.abspath(os.path.expanduser(output)) if output == "" or not os.path.exists(output): output = os.path.expanduser(os.path.join("~", "Downl...
def download(self, output="", outputFile="", silent=True)
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...
2.928639
2.630985
1.113134
def get_new_url(url): return base_url + url[2:] # Deal with anonymous URLS for match in re.finditer(r"^__ (?P<url>\./.*)", text, re.MULTILINE): orig_url = match.groupdict()["url"] url = get_new_url(orig_url) text = re.sub("^__ {}".format(orig_url), ...
def replace_local_hyperlinks( text, base_url="https://github.com/project-rig/rig/blob/master/")
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.
1.990958
2.02812
0.981677
import csv import sys from metatab import MetatabDoc doc = MetatabDoc() pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format']) r = doc['Root'] r.new_term('Root.Title', 'Package Index') for p in idx.list(): pack_section.new_te...
def dump_index(args, idx)
Create a metatab file for the index
6.305465
5.547222
1.136689
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_network_vswitch = agent_config.get( 'local_network_vswitch') sel...
def _setup(self)
Setup the layer two agent.
4.05567
4.201249
0.965349
self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN) self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN) self._client = n_rpc.get_client(self.target) self._consumers.extend([ [topics.PORT, topics.UPDATE], [topics.NETWORK, topics.DELETE], [to...
def _setup_rpc(self)
Setup the RPC client for the current agent.
3.011988
2.945998
1.0224
LOG.info("Hyper-V VM vNIC added: %s", port_name) self._added_ports.add(port_name)
def _process_added_port_event(self, port_name)
Callback for added ports.
6.555635
6.846968
0.957451
for mapping in phys_net_vswitch_mappings: parts = mapping.split(':') if len(parts) != 2: LOG.debug('Invalid physical network mapping: %s', mapping) else: pattern = re.escape(parts[0].strip()).replace('\\*', '.*') patter...
def _load_physical_network_mappings(self, phys_net_vswitch_mappings)
Load all the information regarding the physical network.
2.482723
2.416304
1.027488
if network_type != constants.TYPE_LOCAL: vswitch_name = self._get_vswitch_for_physical_network( physical_network) else: vswitch_name = self._local_network_vswitch if vswitch_name: return vswitch_name err_msg = _("No vSwitch c...
def _get_vswitch_name(self, network_type, physical_network)
Get the vswitch name for the received network information.
2.43386
2.36237
1.030262
for pattern in self._physical_network_mappings: if phys_network_name is None: phys_network_name = '' if re.match(pattern, phys_network_name): return self._physical_network_mappings[pattern]
def _get_vswitch_for_physical_network(self, phys_network_name)
Get the vswitch name for the received network name.
2.836397
2.464931
1.150701
for network_id, vswitch in six.iteritems(self._network_vswitch_map): if port_id in vswitch['ports']: return (network_id, vswitch) # If the port was not found, just return (None, None) return (None, None)
def _get_network_vswitch_map_by_port_id(self, port_id)
Get the vswitch name for the received port id.
2.774208
2.65592
1.044538
with self._cache_lock: if device_bound: self._bound_ports.add(device) self._unbound_ports.discard(device) else: self._bound_ports.discard(device) self._unbound_ports.add(device)
def _update_port_status_cache(self, device, device_bound=True)
Update the ports status cache.
1.962598
1.758138
1.116294
LOG.debug("Create the event listeners.") for event_type, callback in self._event_callback_pairs: LOG.debug("Create listener for %r event", event_type) listener = self._utils.get_vnic_event_listener(event_type) eventlet.spawn_n(listener, callback)
def _create_event_listeners(self)
Create and bind the event listeners.
4.931163
4.299314
1.146965
LOG.debug("Binding port %s", port_id) if network_id not in self._network_vswitch_map: self._provision_network( port_id, network_id, network_type, physical_network, segmentation_id) vswitch_map = self._network_vswitch_map[network_id] ...
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.
2.582914
2.564791
1.007066
device = device_details['device'] port_id = device_details['port_id'] reprocess = True try: self._process_added_port(device_details) LOG.debug("Updating cached port %s status as UP.", port_id) self._update_port_status_cache(device, device_bou...
def process_added_port(self, device_details)
Process the new ports. Wraps _process_added_port, and treats the sucessful and exception cases.
4.888551
4.791492
1.020256
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 get ports details for " "devices %(devices)s: %(exc)s", ...
def _treat_devices_added(self)
Process the new devices.
2.738215
2.715691
1.008294
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 was successfully removed.") self._removed_ports.discard(device)
def _process_removed_port(self, device)
Process the removed ports.
6.547306
6.075683
1.077625
for device in self._removed_ports.copy(): eventlet.spawn_n(self._process_removed_port, device)
def _treat_devices_removed(self)
Process the removed devices.
7.06001
5.617028
1.256894
if self._refresh_cache: # Inconsistent cache might cause exceptions. For example, # if a port has been removed, it will be known in the next # loop. Using the old switch port can cause exceptions. LOG.debug("Refreshing os_win caches...") self....
def _work(self)
Process the information regarding the available ports.
7.776143
7.32921
1.06098
parser = subparsers.add_parser( 'build', help='Build derived packages', description=build.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='') parser.set_defaults(run_command=run_metapack) parser.add_argument('metatabfile', nargs='?', ...
def build(subparsers)
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 ...
3.327332
2.976634
1.117817
from metapack.exc import PackageError from metapack.util import get_materialized_data_cache from shutil import rmtree create_list = [] url = None doc = MetapackDoc(m.mt_file) env = get_lib_module_dict(doc) package_dir = m.package_root if m.args.package_directory: # ...
def metatab_derived_handler(m)
Create local Zip, Excel and Filesystem packages :param m: :param skip_if_exists: :return:
4.432741
4.266141
1.039052
from metapack.appurl import SearchUrl import metapack as mp from os import environ SearchUrl.initialize() # This makes the 'index:" urls work mp.Downloader.context.update(environ)
def init()
Initialize features that are normally initialized in the CLI
29.487522
27.808157
1.060391
# Holders for all structs structs = dict() # Holders for the current struct name = None # Iterate over every line in the file for i, l in enumerate(struct_data.splitlines()): # Empty the line of comments, if the line is empty then skip to the # next line. Split on whitesp...
def read_struct_file(struct_data)
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...
3.001327
3.032472
0.989729
if re_hex_num.match(value): return int(value, base=16) else: return int(value)
def num(value)
Convert a value from one of several bases to an int.
3.747756
3.634484
1.031166
for (field, value) in six.iteritems(updates): fname = six.b(field) self[fname] = self[fname]._replace(default=value)
def update_default_values(self, **updates)
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.
6.357612
6.660627
0.954507
# Generate a buffer big enough to hold the packed values data = bytearray(b"\x00" * self.size) # Iterate over the fields, pack each value in little-endian format and # insert into the buffered data. for field in six.itervalues(self.fields): packed_data = str...
def pack(self)
Pack the struct (and its default values) into a string of bytes. Returns ------- :py:class:`bytes` Byte-string representation of struct containing default values.
4.982664
4.609993
1.08084
job = self._get_next_future_job() if not job: return None return (job.at - datetime.now(timezone.utc)).total_seconds()
def next_future_job_delta(self) -> Optional[float]
Give the amount of seconds before the next future job is due.
3.195578
2.874434
1.111724
# For each vertex we perform an SDRAM alloc to get a file-like for # the vertex. vertex_memory = dict() for vertex, allocs in six.iteritems(allocations): if sdram_resource in allocs: sdram_slice = allocs[sdram_resource] assert sdram_slice.step is None si...
def sdram_alloc_for_vertices(controller, placements, allocations, core_as_tag=True, sdram_resource=SDRAM, cores_resource=Cores, clear=False)
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...
3.581394
3.226757
1.109905
duration = human_duration(duration) if not err: job.status = JobStatus.SUCCEEDED logger.info('Finished execution of %s in %s', job, duration) return if job.should_retry: job.status = JobStatus.NOT_SET job.retries += 1 if isinstance(err, RetryException) a...
def advance_job_status(namespace: str, job: Job, duration: float, err: Optional[Exception])
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.
2.800853
2.731501
1.025389
return Tile(self, zoom, row, col)
def tile(self, zoom, row, col)
Return Tile object of this TilePyramid. - zoom: zoom level - row: tile matrix row - col: tile matrix column
7.070642
6.821968
1.036452
validate_zoom(zoom) width = int(math.ceil(self.grid.shape.width * 2**(zoom) / self.metatiling)) return 1 if width < 1 else width
def matrix_width(self, zoom)
Tile matrix width (number of columns) at zoom level. - zoom: zoom level
8.579785
10.049872
0.853721
validate_zoom(zoom) height = int(math.ceil(self.grid.shape.height * 2**(zoom) / self.metatiling)) return 1 if height < 1 else height
def matrix_height(self, zoom)
Tile matrix height (number of rows) at zoom level. - zoom: zoom level
8.576759
10.403332
0.824424
warnings.warn(DeprecationWarning("tile_x_size is deprecated")) validate_zoom(zoom) return round(self.x_size / self.matrix_width(zoom), ROUND)
def tile_x_size(self, zoom)
Width of a tile in SRID units at zoom level. - zoom: zoom level
6.411326
6.791984
0.943955
warnings.warn(DeprecationWarning("tile_y_size is deprecated")) validate_zoom(zoom) return round(self.y_size / self.matrix_height(zoom), ROUND)
def tile_y_size(self, zoom)
Height of a tile in SRID units at zoom level. - zoom: zoom level
6.702308
7.071535
0.947787
warnings.warn(DeprecationWarning("tile_width is deprecated")) validate_zoom(zoom) matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.width tile_pixel = self.tile_size * self.metatiling return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel
def tile_width(self, zoom)
Tile width in pixel. - zoom: zoom level
6.451044
7.300389
0.883658
warnings.warn(DeprecationWarning("tile_height is deprecated")) validate_zoom(zoom) matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.height tile_pixel = self.tile_size * self.metatiling return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel
def tile_height(self, zoom)
Tile height in pixel. - zoom: zoom level
6.55467
7.449417
0.87989
validate_zoom(zoom) return round( (self.grid.right - self.grid.left) / (self.grid.shape.width * 2**zoom * self.tile_size), ROUND )
def pixel_x_size(self, zoom)
Width of a pixel in SRID units at zoom level. - zoom: zoom level
6.74853
7.622696
0.885321
validate_zoom(zoom) return round( (self.grid.top - self.grid.bottom) / (self.grid.shape.height * 2**zoom * self.tile_size), ROUND )
def pixel_y_size(self, zoom)
Height of a pixel in SRID units at zoom level. - zoom: zoom level
7.070017
7.924003
0.892228
validate_zoom(zoom) if not isinstance(bounds, tuple) or len(bounds) != 4: raise ValueError("bounds must be a tuple of left, bottom, right, top values") if not isinstance(bounds, Bounds): bounds = Bounds(*bounds) if self.is_global: for tile in ...
def tiles_from_bounds(self, bounds, zoom)
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
2.985966
3.138866
0.951288
validate_zoom(zoom) return self.tiles_from_bounds(geometry.bounds, zoom)
def tiles_from_bbox(self, geometry, zoom)
All metatiles intersecting with given bounding box. - geometry: shapely geometry - zoom: zoom level
5.552811
7.762138
0.715371
validate_zoom(zoom) if geometry.is_empty: return if not geometry.is_valid: raise ValueError("no valid geometry: %s" % geometry.type) if geometry.geom_type == "Point": yield self.tile_from_xy(geometry.x, geometry.y, zoom) elif geometry....
def tiles_from_geom(self, geometry, zoom)
Return all tiles intersecting with input geometry. - geometry: shapely geometry - zoom: zoom level
2.574703
2.698907
0.95398
validate_zoom(zoom) if x < self.left or x > self.right or y < self.bottom or y > self.top: raise ValueError("x or y are outside of grid bounds") if on_edge_use not in ["lb", "rb", "rt", "lt"]: raise ValueError("on_edge_use must be one of lb, rb, rt or lt") ...
def tile_from_xy(self, x, y, zoom, on_edge_use="rb")
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 ...
2.167426
2.321491
0.933635
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 }
def get_ladder_metadata(session, url)
Get ladder metadata.
3.840402
3.882618
0.989127
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
def get_ladders_metadata(session, parsed)
Get metadata for all ladders.
2.329003
2.294985
1.014823
for data in games.values(): parsed = make_scrape_request(session, data['url']) return { 'ladders': get_ladders_metadata(session, parsed) }
def get_metadata(session, games)
Get metadata for games (only ladder data right now).
7.439065
6.046255
1.230359
with open(os.path.join(path, 'games.json')) as handle: games = json.loads(handle.read()) for key, data in get_metadata(session, games).items(): with open(os.path.join(path, '{}.json'.format(key)), 'w') as handle: handle.write(json.dumps(data, indent=2))
def update_metadata(session, path=DATA_PATH)
Update metadata files (only ladders right now).
2.784764
2.618723
1.063405
return { (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info }
def sample_counters(mc, system_info)
Sample every router counter in the machine.
6.360304
4.928071
1.290628
return { xy: RouterDiagnostics(*((n - l) & 0xFFFFFFFF for l, n in zip(last[xy], now[xy]))) for xy in last }
def deltas(last, now)
Return the change in counter values (accounting for wrap-around).
16.505625
13.885969
1.188655
# Print CSV header output.write("time,{}{}\n".format("x,y," if detailed else "", ",".join(counters))) system_info = mc.get_system_info() # Make an initial sample of the counters last_counter_values = sample_counters(mc, system_info) start_time = time...
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.
3.09212
3.046773
1.014884
def f(): try: while True: if silent: yield input() else: sys.stderr.write("<press enter> ") sys.stderr.flush() yield input() if not multiple: ...
def press_enter(multiple=False, silent=False)
Return a generator function which yields every time the user presses return.
4.651654
3.988345
1.166312
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Don't take control of this socket in the system (i.e. allow other # processes to bind to it) since we're listening for broadcasts. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Listen for the broadcasts s.bind(('0.0.0.0',...
def listen(timeout=6.0, port=BOOT_PORT)
Listen for a 'ping' broadcast message from an unbooted SpiNNaker board. Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish seconds on port 54321. This function listens for such messages and reports the IP address that it came from. Parameters ---------- timeout : float ...
2.918063
2.867492
1.017636
for what, reason, url, path in files_processed: cp = m.doc.downloader.cache_path(url) if m.cache.exists(cp): m.cache.remove(cp)
def clear_cache(m, files_processed)
Remove any files we may have uploaded from the cache.
7.961045
7.888034
1.009256
for col in df.columns[df.isna().any()].tolist(): if df[col].dtype.name != 'category': # If not categorical, fill with a blank, which creates and # empty cell in CSV. df[col] = df[col].fillna('') else: try: df[col].cat.add_categor...
def fill_categorical_na(df, nan_cat='NA')
Fill categoricals with 'NA', possibly creating a new category, and fill other NaNa with blanks
3.349197
3.209128
1.043647
def executor_ips(sc): try: app_id = sc.applicationId except AttributeError: app_id = sc.getConf().get('spark.app.id') # for getting the url (see: https://github.com/apache/spark/pull/15000) try: base_url = sc.uiWebUrl except AttributeError: base_url = s...
gets the unique ip addresses of the executors of the current application This uses the REST API of the status web UI on the driver (http://spark.apache.org/docs/latest/monitoring.html) :param sc: Spark context :return: set of ip addresses
null
null
null
def change(sc=None, app_name='customSpark', master=None, wait='ips', min_cores=None, min_ips=None, timeout=30, refresh_rate=0.5, fail_on_timeout=False, **kwargs): # checking input if master is None and sc is None: raise ValueError('Both master and sc are None') if master is Non...
Returns a new Spark Context (sc) object with added properties set :param sc: current SparkContext if None will create a new one :param app_name: name of new spark app :param master: url to master, if None will get from current sc :param wait: when to return after asking for a new sc (or max of tim...
null
null
null
def fallback(func): @wraps(func) def dec(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.getLogger('pySparkUtils').error('Decorator handled exception %s' % e, exc_info=True) _, _, tb = sys.exc_info() ...
Decorator function for functions that handle spark context. If a function changes sc we might lose it if an error occurs in the function. In the event of an error this decorator will log the error but return sc. :param func: function to decorate :return: decorated function
null
null
null
def thunder_decorator(func): @wraps(func) def dec(*args, **kwargs): # find Images / Series object in args result = None args = list(args) image_args = list(map(lambda x: isinstance(x, td.images.Images), args)) series_args = list(map(lambda x: isinstance(x, td...
Decorator for functions so they could get as input a thunder.Images / thunder.Series object, while they are expecting an rdd. Also will return the data from rdd to the appropriate type Assumes only one input object of type Images/Series, and up to one output object of type RDD :param func: function to ...
null
null
null
def balanced_repartition(data, partitions): def repartition(data_inner, partitions_inner): # repartition by zipping an index to the data, repartition by % on it and removing it data_inner = data_inner.zipWithIndex().map(lambda x: (x[1], x[0])) data_inner = data_inner.partitionBy(...
balanced_repartition(data, partitions) Reparations an RDD making sure data is evenly distributed across partitions for Spark version < 2.1 (see: https://issues.apache.org/jira/browse/SPARK-17817) or < 2.3 when #partitions is power of 2 (see: https://issues.apache.org/jira/browse/SPARK-21782) :para...
null
null
null
def regroup(rdd, groups=10, check_first=False): if check_first: first = rdd.first() if isinstance(first, (list, tuple, collections.Iterable)): if len(first) != 2: raise ValueError('first item was not not length 2: %d' % len(first)) else: r...
Regroup an rdd using a new key added that is 0 ... number of groups - 1 :param rdd: input rdd as a (k,v) pairs :param groups: number of groups to concatenate to :param check_first: check if first value is a key value pair. :return: a new rdd in the form of (groupNum, list of (k, v) in that group) ...
null
null
null
def save_rdd_as_pickle(rdd, path, batch_size=10, overwrite=False): if os.path.isdir(path): if overwrite: logging.getLogger('pySparkUtils').info('Deleting files from: %s' % path) shutil.rmtree(path) logging.getLogger('pySparkUtils').info('Done deleting files fro...
Saves an rdd by grouping all the records of each partition as one pickle file :param rdd: rdd to save :param path: where to save :param batch_size: batch size to pass to spark saveAsPickleFile :param overwrite: if directory exist whether to overwrite
null
null
null
def load_rdd_from_pickle(sc, path, min_partitions=None, return_type='images'): if min_partitions is None: min_partitions = sc.defaultParallelism rdd = sc.pickleFile(path, minPartitions=min_partitions) rdd = rdd.flatMap(lambda x: x) if return_type == 'images': result = td.imag...
Loads an rdd that was saved as one pickle file per partition :param sc: Spark Context :param path: directory to load from :param min_partitions: minimum number of partitions. If None will be sc.defaultParallelism :param return_type: what to return: 'rdd' - RDD 'images' - Thunder ...
null
null
null
import geopandas as gpd from shapely.geometry.polygon import BaseGeometry from shapely.wkt import loads gdf = gpd.GeoDataFrame(self) first = next(gdf.iterrows())[1].geometry if isinstance(first, str): # We have a GeoDataframe, but the geometry colu...
def geo(self)
Return a geopandas dataframe
5.341018
5.218038
1.023568
yield [self.index.name] + list(self.columns) for t in self.itertuples(): yield list(t)
def rows(self)
Yield rows like a partition does, with a header first, then rows.
8.186267
5.657081
1.447083
matches = None for key in node_set_props: ns_val = node_set_props[key] if key in type_info: if ns_val==type_info[key]: if matches: matches = matches and True else: matches = True else: ...
def _matches_node_set_props(type_info, node_set_props)
Check whether the node_set properties match the given model type definition
3.037915
2.933289
1.035668
from neuroml.hdf5.NetworkBuilder import NetworkBuilder neuroml_handler = NetworkBuilder() sr = SonataReader(filename=sonata_filename, id=id) sr.parse(neuroml_handler) nml_doc = neuroml_handler.get_nml_doc() sr.add_neuroml_components(nml_doc) ...
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format='xml')
Return a NeuroMLDocument with (most of) the contents of the Sonata model
2.428503
2.520405
0.963537
#print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path)) if type(path) == int or type(path) == float: return path for s in self.init_substitutes: if path.startswith(s): path = path.replace(s,self.init_substi...
def subs(self, path)
Search the strings in a config file for a substitutable value, e.g. "morphologies_dir": "$COMPONENT_DIR/morphologies",
3.063008
3.014323
1.016151
#pp.pprint(self.simulation_config) #pp.pprint(self.pop_comp_info) #pp.pprint(self.node_set_mappings) if 'output' in self.simulation_config: gen_spike_saves_for_all_somas = True target = nml_doc.networks[0].id sim_id = 'Sim_%...
def generate_lems_file(self, nml_file_name, nml_doc)
Generate a LEMS file to use in simulations of the NeuroML file
3.608441
3.541615
1.018869
if not geometry.is_valid: raise ValueError("invalid geometry given") pyramid_bbox = box(*pyramid.bounds) # Special case for global tile pyramids if geometry extends over tile # pyramid boundaries (such as the antimeridian). if pyramid.is_global and not geometry.within(pyramid_bbox): ...
def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False)
Clip input geometry to SRS bounds of given TilePyramid. If geometry passes the antimeridian, it will be split up in a multipart geometry and shifted to within the SRS boundaries. Note: geometry SRS must be the TilePyramid SRS! - geometry: any shapely geometry - pyramid: a TilePyramid object - ...
3.148721
2.909036
1.082393
bounds = Bounds(*bounds) validate_zoom(zoom) lb = _tile_from_xy(tile_pyramid, bounds.left, bounds.bottom, zoom, on_edge_use="rt") rt = _tile_from_xy(tile_pyramid, bounds.right, bounds.top, zoom, on_edge_use="lb") left, bottom, _, _ = lb.bounds(pixelbuffer) _, _, right, top = rt.bounds(pixel...
def snap_bounds(bounds=None, tile_pyramid=None, zoom=None, pixelbuffer=0)
Extend bounds to be aligned with union of tile bboxes. - bounds: (left, bottom, right, top) - tile_pyramid: a TilePyramid object - zoom: target zoom level - pixelbuffer: apply pixelbuffer
3.287756
3.803146
0.864483
if not isinstance(shape, (tuple, list)) or len(shape) != 2: raise TypeError( "shape must be a tuple or list with two elements: %s" % str(shape) ) if not isinstance(bounds, (tuple, list)) or len(bounds) != 4: raise TypeError( "bounds must be a tuple or list wi...
def _verify_shape_bounds(shape, bounds)
Verify that shape corresponds to bounds apect ratio.
1.96198
1.900288
1.032465
if tile.tp.grid != tp.grid: raise ValueError("Tile and TilePyramid source grids must be the same.") tile_metatiling = tile.tile_pyramid.metatiling pyramid_metatiling = tp.metatiling multiplier = tile_metatiling / pyramid_metatiling if tile_metatiling > pyramid_metatiling: return...
def _tile_intersecting_tilepyramid(tile, tp)
Return all tiles from tilepyramid intersecting with tile.
2.61957
2.577743
1.016226
seen = set() # clip to tilepyramid top and bottom bounds left, right = bounds.left, bounds.right top = tp.top if bounds.top > tp.top else bounds.top bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom if left >= tp.left and right <= tp.right: for tile in _tiles_from...
def _global_tiles_from_bounds(tp, bounds, zoom)
Return also Tiles if bounds cross the antimeridian.
2.155281
2.047286
1.05275
lb = _tile_from_xy(tp, bounds.left, bounds.bottom, zoom, on_edge_use="rt") rt = _tile_from_xy(tp, bounds.right, bounds.top, zoom, on_edge_use="lb") for tile_id in product([zoom], range(rt.row, lb.row + 1), range(lb.col, rt.col + 1)): yield tp.tile(*tile_id)
def _tiles_from_cleaned_bounds(tp, bounds, zoom)
Return all tiles intersecting with bounds.
3.938524
3.877264
1.0158
parser = subparsers.add_parser( 'open', help='open a CSV resoruce with a system application', description=open_args.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.set_defaults(run_command=open_cmd) parser.add_argument('metatabfile', nargs='...
def open_args(subparsers)
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
4.663673
3.849755
1.211421
out = _concentric_hexagons.get(radius) if out is None: out = tuple(concentric_hexagons(radius)) _concentric_hexagons[radius] = out return out
def memoized_concentric_hexagons(radius)
A memoized wrapper around :py:func:`rig.geometry.concentric_hexagons` which memoizes the coordinates and stores them as a tuple. Note that the caller must manually offset the coordinates as required. This wrapper is used to avoid the need to repeatedly call :py:func:`rig.geometry.concentric_hexagons` f...
2.340425
2.949744
0.793433
new_root = None # Lookup for copied routing tree {(x, y): RoutingTree, ...} new_lookup = {} # List of missing connections in the copied routing tree [(new_parent, # new_child), ...] broken_links = set() # A queue [(new_parent, direction, old_node), ...] to_visit = deque([(None, N...
def copy_and_disconnect_tree(root, machine)
Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting nodes which are not connected in the machine. Note that if a dead chip is part of the input RoutingTree, no corresponding node will be included in the copy. The assumption behind this is that the only reason a tree would visit a de...
4.322032
3.853863
1.12148
# Select the heuristic function to use for distances if wrap_around: heuristic = (lambda node: shortest_torus_path_length(to_xyz(node), to_xyz(heuristic_source), machine.width, machi...
def a_star(sink, heuristic_source, sources, machine, wrap_around)
Use A* to find a path from any of the sources to the sink. Note that the heuristic means that the search will proceed towards heuristic_source without any concern for any other sources. This means that the algorithm may miss a very close neighbour in order to pursue its goal of reaching heuristic_sourc...
4.141346
3.855668
1.074093
for direction, (x, y), routes in root.traverse(): for route in routes: if (x, y, route) not in machine: return True return False
def route_has_dead_links(root, machine)
Quickly determine if a route uses any dead links. Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing but RoutingTrees (i.e. no vertices and links). machine : :py:class:`~rig.place_and_route.Machine` ...
6.133287
7.653977
0.80132
# Make a copy of the RoutingTree with all broken parts disconnected root, lookup, broken_links = copy_and_disconnect_tree(root, machine) # For each disconnected subtree, use A* to connect the tree to *any* other # disconnected subtree. Note that this process will eventually result in # all dis...
def avoid_dead_links(root, machine, wrap_around=False)
Modify a RoutingTree to route-around dead links in a Machine. Uses A* to reconnect disconnected branches of the tree (due to dead links in the machine). Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing...
6.330986
6.004944
1.054296
wrap_around = machine.has_wrap_around_links() # Vertices constrained to route to a specific link. {vertex: route} route_to_endpoint = {} for constraint in constraints: if isinstance(constraint, RouteEndpointConstraint): route_to_endpoint[constraint.vertex] = constraint.route ...
def route(vertices_resources, nets, machine, constraints, placements, allocations={}, core_resource=Cores, radius=20)
Routing algorithm based on Neighbour Exploring Routing (NER). Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast routing, Parallel Computing (2014). http://dx.doi.org/10.1016/j.parco.2015.01.002 This algorithm attempts to use NER to generate routing trees for all nets and routes...
5.33626
5.329213
1.001322
if patterns is None: return True else: return any(re.match(pattern, string) for pattern in patterns)
def match(string, patterns)
Given a string return true if it matches the supplied list of patterns. Parameters ---------- string : str The string to be matched. patterns : None or [pattern, ...] The series of regular expressions to attempt to match.
2.952075
3.135416
0.941526
system_info = mc.get_system_info() for (x, y), chip_info in sorted(iteritems(system_info)): if x_ is not None and x_ != x: continue if y_ is not None and y_ != y: continue for p in range(chip_info.num_cores): if p_ is not None and p_ != p: ...
def get_process_list(mc, x_=None, y_=None, p_=None, app_ids=None, applications=None, states=None)
Scan a SpiNNaker system's cores filtering by the specified features. Generates ------- (x, y, core, state, runtime_exception, application, app_id)
3.753568
3.493844
1.074338
reservation = None # Cores is in ascending order for core in cores: if reservation is None: reservation = slice(core, core + 1) elif reservation.stop == core: reservation = slice(reservation.start, core + 1) else: yield ReserveResourceConstra...
def _get_minimal_core_reservations(core_resource, cores, chip=None)
Yield a minimal set of :py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint` objects which reserve the specified set of cores. Parameters ---------- core_resource : resource type The type of resource representing cores. cores : [int, ...] The core numbers to res...
3.054482
2.967259
1.029395