code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder): package_path, cache_path = c.make_package_path(pkg_dir, name) if package_path.exists(): yield c.type_code, package_path, cache_path
def find_packages(name, pkg_dir)
Locate pre-built packages in the _packages directory
7.553034
6.99181
1.080269
parser = subparsers.add_parser( 'new', help='Create new Metatab packages', description=new_args.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.set_defaults(run_command=new_cmd) parser.add_argument('-o', '--origin', help="Dataset origin, usu...
def new_args(subparsers)
The `mp new` command creates source package directories with a proper name, a `.gitignore` file, and optionally, example data, entries and code. Typical usage, for creating a new package with most of the example options, is :: mp new -o metatab.org -d tutorial -L -E -T "Quickstart Example Packa...
4.797504
3.985139
1.203849
self.bitarray = bitarray.bitarray(self.nbr_bits) self.current_day_bitarray = bitarray.bitarray(self.nbr_bits) self.bitarray.setall(False) self.current_day_bitarray.setall(False)
def initialize_bitarray(self)
Initialize both bitarray. This BF contain two bit arrays instead of single one like a plain BF. bitarray is the main bit array where all the historical items are stored. It's the one used for the membership query. The second one, current_day_bitarray is the one used for creating the dai...
2.571907
1.854734
1.386671
if not period: self.current_period = dt.datetime.now() else: self.current_period = period self.current_period = dt.datetime(self.current_period.year, self.current_period.month, self.current_period.day) self.date = self.current_period.strftime("%Y-%m-%d")
def initialize_period(self, period=None)
Initialize the period of BF. :period: datetime.datetime for setting the period explicity.
2.042138
2.01106
1.015453
if self.snapshot_to_load == None: last_period = self.current_period - dt.timedelta(days=self.expiration-1) self.compute_refresh_period() self.snapshot_to_load = [] base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration) ...
def warm(self, jittering_ratio=0.2)
Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same...
3.766641
3.542095
1.063394
base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration) availables_snapshots = glob.glob(base_filename) last_period = self.current_period - dt.timedelta(days=self.expiration-1) for filename in availables_snapshots: snapshot_period = dt.dat...
def restore_from_disk(self, clean_old_snapshot=False)
Restore the state of the BF using previous snapshots. :clean_old_snapshot: Delete the old snapshot on the disk (period < current - expiration)
3.625316
3.38056
1.072401
filename = "%s/%s_%s_%s.dat" % (self.snapshot_path, self.name, self.expiration, self.date) with open(filename, 'w') as f: f.write(zlib.compress(pickle.dumps(self.current_day_bitarray, protocol=pickle.HIGHEST_PROTOCOL)))
def save_snaphot(self)
Save the current state of the current day bitarray on disk. Save the internal representation (bitarray) into a binary file using this format: filename : name_expiration_2013-01-01.dat
4.344903
2.852736
1.523065
shift = 6 - 2*level bit = ((x >> shift) & 3) + 4*((y >> shift) & 3) # bit in bits 15:0 to set mask = 0xffff ^ ((4 << shift) - 1) # in {0xfffc, 0xfff0, 0xffc0, 0xff00} nx = x & mask # The mask guarantees that bits 1:0 will be cleared ny = y & mask # The mask guarantees that bits 1:0 will b...
def get_region_for_chip(x, y, level=3)
Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the specified region will ONLY select the given chip,...
6.733234
6.290553
1.070372
t = RegionCoreTree() for (x, y), cores in iteritems(targets): for p in cores: t.add_core(x, y, p) return sorted(t.get_regions_and_coremasks())
def compress_flood_fill_regions(targets)
Generate a reduced set of flood fill parameters. Parameters ---------- targets : {(x, y) : set([c, ...]), ...} For each used chip a set of core numbers onto which an application should be loaded. E.g., the output of :py:func:`~rig.place_and_route.util.build_application_map` when in...
9.7028
7.287096
1.331504
region_code = ((self.base_x << 24) | (self.base_y << 16) | (self.level << 16)) # Generate core masks for any regions which are selected at this level # Create a mapping from subregion mask to core numbers subregions_cores = collections.defaultdict(lambda:...
def get_regions_and_coremasks(self)
Generate a set of ordered paired region and core mask representations. .. note:: The region and core masks are ordered such that ``(region << 32) | core_mask`` is monotonically increasing. Consequently region and core masks generated by this method can be used with SCAMP's ...
5.321321
5.02153
1.059701
# Check that the co-ordinate is contained in this region if ((p < 0 or p > 17) or (x < self.base_x or x >= self.base_x + self.scale) or (y < self.base_y or y >= self.base_y + self.scale)): raise ValueError((x, y, p)) # Determine which subregi...
def add_core(self, x, y, p)
Add a new core to the region tree. Raises ------ ValueError If the co-ordinate is not contained within this part of the tree or the core number is out of range. Returns ------- bool True if the specified core is to be loaded to all su...
3.323061
3.129601
1.061816
# Retrieve contextual arguments from the keyword arguments. The # context system ensures that these values are present. cabinet = kwargs.pop("cabinet") frame = kwargs.pop("frame") board = kwargs.pop("board") return self._send_scp(cabinet, frame, board, *args, **...
def send_scp(self, *args, **kwargs)
Transmit an SCP Packet to a specific board. Automatically determines the appropriate connection to use. See the arguments for :py:meth:`~rig.machine_control.scp_connection.SCPConnection` for details. Parameters ---------- cabinet : int frame : int ...
6.822041
4.974789
1.371323
# Find the connection which best matches the specified coordinates, # preferring direct connections to a board when available. connection = self.connections.get((cabinet, frame, board), None) if connection is None: connection = self.connections.get((cabinet, frame), ...
def _send_scp(self, cabinet, frame, board, *args, **kwargs)
Determine the best connection to use to send an SCP packet and use it to transmit. See the arguments for :py:meth:`~rig.machine_control.scp_connection.SCPConnection` for details.
6.753934
6.550884
1.030996
sver = self._send_scp(cabinet, frame, board, SCPCommands.sver) # Format the result # arg1 code_block = (sver.arg1 >> 24) & 0xff frame_id = (sver.arg1 >> 16) & 0xff can_id = (sver.arg1 >> 8) & 0xff board_id = sver.arg1 & 0xff # arg2 (version fiel...
def get_software_version(self, cabinet, frame, board)
Get the software version for a given BMP. Returns ------- :py:class:`.BMPInfo` Information about the software running on a BMP.
4.574435
4.710479
0.971119
if isinstance(board, int): boards = [board] else: boards = list(board) arg1 = int(delay * 1000) << 16 | (1 if state else 0) arg2 = sum(1 << b for b in boards) # Allow additional time for response when powering on (since FPGAs must # be l...
def set_power(self, state, cabinet, frame, board, delay=0.0, post_power_on_delay=5.0)
Control power to the SpiNNaker chips and FPGAs on a board. Returns ------- state : bool True for power on, False for power off. board : int or iterable Specifies the board to control the power of. This may also be an iterable of multiple boards (in th...
6.446937
5.673209
1.136383
if isinstance(led, int): leds = [led] else: leds = led if isinstance(board, int): boards = [board] else: boards = list(board) board = boards[0] # LED setting actions arg1 = sum(LEDAction.from_bool(actio...
def set_led(self, led, action=None, cabinet=Required, frame=Required, board=Required)
Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this point, the LED is available for use by applications. Parameters ---------- l...
4.803813
4.348246
1.10477
arg1 = addr & (~0x3) arg2 = 4 # Read a 32-bit value arg3 = fpga_num response = self._send_scp(cabinet, frame, board, SCPCommands.link_read, arg1=arg1, arg2=arg2, arg3=arg3, expected_args=0) return struc...
def read_fpga_reg(self, fpga_num, addr, cabinet, frame, board)
Read the value of an FPGA (SPI) register. See the SpI/O project's spinnaker_fpga design's `README`_ for a listing of FPGA registers. The SpI/O project can be found on GitHub at: https://github.com/SpiNNakerManchester/spio/ .. _README: https://github.com/SpiNNakerManchester/spio/\ ...
5.359288
6.062716
0.883975
arg1 = addr & (~0x3) arg2 = 4 # Write a 32-bit value arg3 = fpga_num self._send_scp(cabinet, frame, board, SCPCommands.link_write, arg1=arg1, arg2=arg2, arg3=arg3, data=struct.pack("<I", value), expected_args=0)
def write_fpga_reg(self, fpga_num, addr, value, cabinet, frame, board)
Write the value of an FPGA (SPI) register. See the SpI/O project's spinnaker_fpga design's `README`_ for a listing of FPGA registers. The SpI/O project can be found on GitHub at: https://github.com/SpiNNakerManchester/spio/ .. _README: https://github.com/SpiNNakerManchester/spio/\ ...
5.604522
6.740265
0.831499
response = self._send_scp(cabinet, frame, board, SCPCommands.bmp_info, arg1=BMPInfoType.adc, expected_args=0) data = struct.unpack("<" # Little-endian "8H" # uint16_t adc[8] "4h" # int16_t t_int[4] ...
def read_adc(self, cabinet, frame, board)
Read ADC data from the BMP including voltages and temperature. Returns ------- :py:class:`.ADCInfo`
2.649342
2.644235
1.001932
return {resource: value + res_b.get(resource, 0) for resource, value in iteritems(res_a)}
def add_resources(res_a, res_b)
Return the resources after adding res_b's resources to res_a. Parameters ---------- res_a : dict Dictionary `{resource: value, ...}`. res_b : dict Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of res_a. If A resource is not present in res_b, the value is pre...
4.599054
4.993711
0.920969
return {resource: value - res_b.get(resource, 0) for resource, value in iteritems(res_a)}
def subtract_resources(res_a, res_b)
Return the resources remaining after subtracting res_b's resources from res_a. Parameters ---------- res_a : dict Dictionary `{resource: value, ...}`. res_b : dict Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of res_a. If A resource is not present in re...
4.10505
5.230743
0.784793
res = res.copy() res[constraint.resource] -= (constraint.reservation.stop - constraint.reservation.start) return res
def resources_after_reservation(res, constraint)
Return the resources available after a specified ReserveResourceConstraint has been applied. Note: the caller is responsible for testing that the constraint is applicable to the core whose resources are being constrained. Note: this function does not pay attention to the specific position of the r...
6.418838
8.118168
0.790676
if constraint.location is None: # Compensate for globally reserved resources machine.chip_resources \ = resources_after_reservation( machine.chip_resources, constraint) if overallocated(machine.chip_resources): raise InsufficientResourceError( ...
def apply_reserve_resource_constraint(machine, constraint)
Apply the changes implied by a reserve resource constraint to a machine model.
3.055593
3.085619
0.990269
for merged_vertex in reversed(substitutions): placement = placements.pop(merged_vertex) for v in merged_vertex.vertices: placements[v] = placement
def finalise_same_chip_constraints(substitutions, placements)
Given a set of placements containing the supplied :py:class:`MergedVertex`, remove the merged vertices replacing them with their constituent vertices (changing the placements inplace).
4.332409
3.364596
1.287646
from metapack import MetapackDoc t = self.get_resource().get_target() return MetapackDoc(t, package_url=self.package_url)
def doc(self)
Return the metatab document for the URL
8.323515
5.709482
1.457841
if self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE: # For CSV packages, need to get the package and open it to get the resoruce URL, becuase # they are always absolute web URLs and may not be related to the location of the metadata. s = self...
def resolve_url(self, resource_name)
Return a URL to a local copy of a resource, suitable for get_generator()
9.994625
9.551103
1.046437
if self.resource_file == DEFAULT_METATAB_FILE or self.target_format in ('txt','ipynb'): u = self.inner.clone().clear_fragment() u.path = dirname(self.path) + '/' u.scheme_extension = 'metapack' else: u = self return MetapackPackageUrl(st...
def package_url(self)
Return the package URL associated with this metadata
13.756914
12.704215
1.082862
d = self.dict d['fragment'] = [v, None] return MetapackResourceUrl(downloader=self._downloader, **d)
def join_resource_name(self, v)
Return a MetapackResourceUrl that includes a reference to the resource. Returns a MetapackResourceUrl, which will have a fragment
15.56499
8.203296
1.897407
u = parse_app_url(resource_name) if u.scheme != 'file': t = u elif self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE: # Thre are two forms for CSV package URLS: # - A CSV package, which can only have absolute URLs ...
def resolve_url(self, resource_name)
Return a URL to a local copy of a resource, suitable for get_generator() For Package URLS, resolution involves generating a URL to a data file from the package URL and the value of a resource. The resource value, the url, can be one of: - An absolute URL, with a web scheme - A relative...
7.435605
7.145487
1.040601
return MetapackDocumentUrl(str(self.clear_fragment()), downloader=self._downloader).package_url
def package_url(self)
Return the package URL associated with this metadata
37.078529
29.017557
1.277796
from metapack.index import SearchIndex, search_index_file idx = SearchIndex(search_index_file()) def _search_function(url): packages = idx.search(url, format='issued') if not packages: return None package = packages.pop(0) ...
def search_json_indexed_directory(directory)
Return a search function for searching a directory of packages, which has an index.json file created by the `mp install file` command. This will only search the issued index; it will not return results for the source index
7.737526
6.890294
1.12296
for cb in SearchUrl.search_callbacks: try: v = cb(self) if v is not None: return v except Exception as e: raise
def search(self)
Search for a url by returning the value from the first callback that returns a non-None value
8.446665
4.902169
1.723046
pkg_path = join(dirname(nb_path), pkg_name) makedirs(join(pkg_path,'notebooks'),exist_ok=True) makedirs(join(pkg_path, 'docs'), exist_ok=True) return pkg_path
def ensure_source_package_dir(nb_path, pkg_name)
Ensure all of the important directories in a source package exist
2.890249
2.901229
0.996215
from metatab.generate import CsvDataRowGenerator from metatab.rowgenerators import TextRowGenerator from metatab import MetatabDoc with open(nb_path) as f: nb = nbformat.reads(f.read(), as_version=4) for cell in nb.cells: source = ''.join(cell['source']).strip() if so...
def get_metatab_doc(nb_path)
Read a notebook and extract the metatab document. Only returns the first document
3.41391
3.468529
0.984253
doc = get_metatab_doc(nb_path) doc.update_name(force=True, create_term=True) pkg_name = doc['Root'].get_value('Root.Name') assert pkg_name return ensure_source_package_dir(nb_path, pkg_name), pkg_name
def get_package_dir(nb_path)
Return the package directory for a Notebook that has an embeded Metatab doc, *not* for notebooks that are part of a package
8.305668
7.008642
1.185061
from rowgenerators import SourceError from requests.exceptions import ConnectionError from metapack.cli.core import extract_path_name, alt_col_name, type_map from tableintuit import TypeIntuiter from rowgenerators.generator.python import PandasDataframeSource from appurl import parse_app_u...
def process_schema(doc, resource, df)
Add schema entiries to a metatab doc from a dataframe
4.446106
4.297618
1.034551
PROTOCOL_VERSION = 1 # Generate the (network-byte order) header header = struct.pack("!H4I", PROTOCOL_VERSION, cmd, arg1, arg2, arg3) assert len(data) % 4 == 0 # Data should always be word-sized fdata = b"" # Format the data from little- to network-/big-endian while len(data) > 0: ...
def boot_packet(sock, cmd, arg1=0, arg2=0, arg3=0, data=b"")
Create and transmit a packet to boot the machine. Parameters ---------- sock : :py:class:`~socket.socket` Connected socket to use to transmit the packet. cmd : int arg1 : int arg2 : int arg3 : int data : :py:class:`bytes` Optional data to include in the packet.
4.476356
4.704905
0.951423
return Machine( self.width, self.height, self.chip_resources, self.chip_resource_exceptions, self.dead_chips, self.dead_links)
def copy(self)
Produce a copy of this datastructure.
10.916308
10.335703
1.056175
return (set(self).issubset(set(other)) and set(self.iter_links()).issubset(set(other.iter_links())) and all(set(self[chip]).issubset(other[chip]) and all(self[chip][r] <= other[chip][r] for r in self[chip]) ...
def issubset(self, other)
Test whether the resources available in this machine description are a (non-strict) subset of those available in another machine. .. note:: This test being False does not imply that the this machine is a superset of the other machine; machines may have disjoint reso...
3.465708
3.567018
0.971598
for x in range(self.width): for y in range(self.height): for link in Links: if (x, y, link) in self: yield (x, y, link)
def iter_links(self)
An iterator over the working links in the machine. Generates a series of (x, y, link) tuples.
3.243097
2.867939
1.130811
working = 0 for x in range(self.width): if (x, 0, Links.south) in self: working += 1 if (x, self.height - 1, Links.north) in self: working += 1 if (x, 0, Links.south_west) in self: working += 1 if (x...
def has_wrap_around_links(self, minimum_working=0.9)
Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number of wrap-around links which are working to determine if w...
2.243563
2.469311
0.908578
from rowgenerators import parse_app_url if not mt_file: mt_file = doc.ref add_giturl(doc) u = parse_app_url(mt_file) if u.scheme == 'file': doc.write(mt_file) return True else: return False
def write_doc(doc : MetapackDoc, mt_file=None)
Write a Metatab doc to a CSV file, and update the Modified time :param doc: :param mt_file: :return:
4.969296
5.002024
0.993457
added = [] schema_term = r.schema_term if not schema_term: warn("No schema term for ", r.name) return rg = r.raw_row_generator # Get columns information from the schema, or, if it is a package reference, # from the upstream schema upstream_columns = {e['name'].lowe...
def update_resource_properties(r, orig_columns={}, force=False)
Get descriptions and other properties from this, or upstream, packages, and add them to the schema.
4.408386
4.151515
1.061874
from os import environ from os.path import expanduser from pathlib import Path import yaml def pexp(p): try: return Path(p).expanduser() except AttributeError: # python 3.4 return Path(expanduser(p)) paths = [environ.get("METAPACK_CONFIG...
def get_config()
Return a configuration dict
2.971459
2.86808
1.036045
from metapack.package import CsvPackageBuilder pkg_dir = m.package_root name = m.doc.get_value('Root.Name') package_path, cache_path = CsvPackageBuilder.make_package_path(pkg_dir, name) if package_path.exists(): return open_package(package_path, downloader=downloader)
def find_csv_packages(m, downloader)
Locate the build CSV package, which will have distributions if it was generated as and S3 package
7.016356
6.946243
1.010094
# Construct URL url = '/_apis/continuousdelivery/provisioningconfigurations' # Construct parameters query_parameters = {} if self.api_version: query_parameters["api-version"] = self.api_version # Construct headers header_parameters = {} ...
def provisioning_configuration( self, body, custom_headers=None, raw=False, **operation_config)
ProvisioningConfiguration. :param body: :type body: :class:`ContinuousDeploymentConfiguration <vsts_info_provider.models.ContinuousDeploymentConfiguration>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongs...
1.620828
1.644183
0.985795
# Construct URL url = '/_apis/continuousdelivery/provisioningconfigurations/{provisioningConfigurationId}' path_format_arguments = { 'provisioningConfigurationId': self._serialize.url("provisioning_configuration_id", provisioning_configuration_id, 'str') } ur...
def get_provisioning_configuration( self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config)
GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param...
1.46471
1.484846
0.986439
return [ base64.b64encode(zlib.compress(pickle.dumps(m, protocol=4))).decode() for m in messages ]
def serialize_email_messages(messages: List[EmailMessage])
Serialize EmailMessages to be passed as task argument. Pickle is used because serializing an EmailMessage to json can be a bit tricky and would probably break if Django modifies the structure of the object in the future.
4.154935
3.566959
1.16484
return [ pickle.loads(zlib.decompress(base64.b64decode(m))) for m in messages ]
def deserialize_email_messages(messages: List[str])
Deserialize EmailMessages passed as task argument.
3.784047
3.06294
1.23543
if self.estimate_z == 0: self.estimate_z = (1.0 / self.nbr_bits) self.estimate_z = min(self.estimate_z, 0.999999) self.count = int(-(self.nbr_bits / self.nbr_slices) * np.log(1 - self.estimate_z))
def _estimate_count(self)
Update the count number using the estimation of the unset ratio
4.586732
4.297013
1.067423
if self.cellarray[self.refresh_head] != 0: self.cellarray[self.refresh_head] -= 1 self.refresh_head = (self.refresh_head + 1) % self.nbr_bits
def expiration_maintenance(self)
Decrement cell value if not zero This maintenance process need to executed each self.compute_refresh_time()
5.401038
4.002439
1.349437
num_iterations = self.num_batched_maintenance(elapsed_time) for i in range(num_iterations): self.expiration_maintenance()
def batched_expiration_maintenance_dev(self, elapsed_time)
Batched version of expiration_maintenance()
4.412394
3.739103
1.180068
num_iterations = self.num_batched_maintenance(elapsed_time) self.refresh_head, nonzero = maintenance(self.cellarray, self.nbr_bits, num_iterations, self.refresh_head) if num_iterations != 0: self.estimate_z = float(nonzero) / float(num_iterations) self._estimate_...
def batched_expiration_maintenance(self, elapsed_time)
Batched version of expiration_maintenance() Cython version
8.926257
8.861609
1.007295
if self.z == 0: self.z = 1E-10 s = float(self.expiration) * (1.0/(self.nbr_bits)) * (1.0/(self.counter_init - 1 + (1.0/(self.z * (self.nbr_slices + 1))))) return s
def compute_refresh_time(self)
Compute the refresh period for the given expiration delay
8.129016
6.942736
1.170866
allocation = {} # Globally reserved resource ranges {resource, [slice, ...], ...} globally_reserved = defaultdict(list) # Locally reserved resource ranges {(x, y): {resource, [slice, ...], ...}} locally_reserved = defaultdict(lambda: defaultdict(list)) # Alignment of each resource ali...
def allocate(vertices_resources, nets, machine, constraints, placements)
Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm.
3.363063
3.407494
0.986961
LOG.info("Setting QoS policy %(qos_policy)s on port %(port)s", dict(qos_policy=qos_policy, port=port)) policy_data = self._get_policy_values(qos_policy) self._utils.set_port_qos_rule(port["port_id"], policy_data)
def create(self, port, qos_policy)
Apply QoS rules on port for the first time. :param port: port object. :param qos_policy: the QoS policy to be applied on port.
3.346869
3.362447
0.995367
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s", dict(qos_policy=qos_policy, port=port)) self._utils.remove_port_qos_rule(port["port_id"])
def delete(self, port, qos_policy=None)
Remove QoS rules from port. :param port: port object. :param qos_policy: the QoS policy to be removed from port.
3.651571
3.705174
0.985533
if func is None: return functools.partial(self.task, name=name, queue=queue, max_retries=max_retries, periodicity=periodicity) self.add(func, name=name, queue=queue, max_retries=max_retries, ...
def task(self, func: Optional[Callable]=None, name: Optional[str]=None, queue: Optional[str]=None, max_retries: Optional[Number]=None, periodicity: Optional[timedelta]=None)
Decorator to register a task function. :arg name: name of the task, used later to schedule jobs :arg queue: queue of the task, the default is used if not provided :arg max_retries: maximum number of retries, the default is used if not provided :arg periodicity: for periodic...
3.240644
4.413223
0.734303
if not name: raise ValueError('Each Spinach task needs a name') if name in self._tasks: raise ValueError('A task named {} already exists'.format(name)) if queue is None: if self.queue: queue = self.queue else: ...
def add(self, func: Callable, name: Optional[str]=None, queue: Optional[str]=None, max_retries: Optional[Number]=None, periodicity: Optional[timedelta]=None)
Register a task function. :arg func: a callable to be executed :arg name: name of the task, used later to schedule jobs :arg queue: queue of the task, the default is used if not provided :arg max_retries: maximum number of retries, the default is used if not provided ...
2.428384
2.624589
0.925243
self._require_attached_tasks() self._spin.schedule(task, *args, **kwargs)
def schedule(self, task: Schedulable, *args, **kwargs)
Schedule a job to be executed as soon as possible. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function This method can only be used once tasks have been attached to a ...
13.903049
13.974997
0.994852
self._require_attached_tasks() self._spin.schedule_at(task, at, *args, **kwargs)
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs)
Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: Date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if given, ...
9.886176
9.254012
1.068312
at = datetime.now(timezone.utc) self.schedule_at(task, at, *args, **kwargs)
def schedule(self, task: Schedulable, *args, **kwargs)
Add a job to be executed ASAP to the batch. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function
5.744424
5.888334
0.97556
self.jobs_to_create.append((task, at, args, kwargs))
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs)
Add a job to be executed in the future to the batch. :arg task: the task or its name to execute in the background :arg at: Date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if...
10.02062
7.503975
1.335375
software_name = packet.data.decode("utf-8") legacy_version_field = packet.arg2 >> 16 if legacy_version_field != 0xFFFF: # Legacy version encoding: just encoded in decimal fixed-point in the # integer. major = legacy_version_field // 100 minor = legacy_version_field % 1...
def unpack_sver_response_version(packet)
For internal use. Unpack the version-related parts of an sver (aka CMD_VERSION) response. Parameters ---------- packet : :py:class:`~rig.machine_control.packets.SCPPacket` The packet recieved in response to the version command. Returns ------- software_name : string The nam...
3.867592
3.624084
1.067192
if base_dir == None: return f file_name = os.path.join(base_dir, f) real = os.path.realpath(file_name) #print_v('- Located %s at %s'%(f,real)) return real
def _locate_file(f, base_dir)
Utility method for finding full path to a filename as string
3.922497
3.915523
1.001781
print_v("Checking arguments: %s to see whether anything should be run in simulation %s (net: %s)..." % (argv, sim.id, sim.network)) if len(argv)==1: print_v("No arguments found. Currently supported export formats:") print_v(" -nml | -nmlh5 | -jnml | -jnmlnrn | -...
def check_to_generate_or_run(argv, sim)
Useful method for calling in main method after network and simulation are generated, to handle some standard export options like -jnml, -graph etc.
3.364748
3.249062
1.035606
print_v("------------- Generating NEURON files from NeuroML for %s (default dir: %s)..." % (network.id, dir_for_mod_files)) nml_src_files = [] from neuroml import NeuroMLDocument import neuroml.writers as writers temp_nml_doc = NeuroMLDocument(id="temp") dirs_for_mod_files = [] ...
def _generate_neuron_files_from_neuroml(network, verbose=False, dir_for_mod_files = None)
Generate NEURON hoc/mod files from the NeuroML files which are marked as included in the NeuroMLlite description; also compiles the mod files
2.430874
2.396679
1.014267
print_v('Returning %i traces:'%len(traces)) for r in sorted(traces.keys()): x = traces[r] print_v(' %s (%s): %s -> %s (min: %s, max: %s, len: %i)'%(r, type(x), x[0],x[-1],min(x),max(x),len(x))) print_v('Returning %i events:'%len(events)) for r in sorted(events.keys()): x = ...
def _print_result_info(traces, events)
Print a summary of the returned (voltage) traces and spike times
2.323435
2.215644
1.04865
self._inputs[name] = wire wire.sinks.append(self)
def connect_input(self, name, wire)
Connect the specified input to a wire.
6.356012
5.76921
1.101713
memory.seek(0) memory.write(struct.pack("<5I", # sim_length self._simulator.length, # input_a_key self._inputs["a"].routing_key if...
def _write_config(self, memory)
Write the configuration for this gate to memory.
4.240308
3.939186
1.076443
self._input = wire wire.sinks.append(self)
def connect_input(self, wire)
Probe the specified wire.
11.189706
10.105589
1.107279
memory.seek(0) memory.write(struct.pack("<II", # sim_length self._simulator.length, # input_key self._input.routing_key if self._i...
def _write_config(self, memory)
Write the configuration for this probe to memory.
10.534113
9.415567
1.118797
# Seek to the simulation data and read it all back memory.seek(8) bits = bitarray(endian="little") bits.frombytes(memory.read()) self.recorded_data = bits.to01()
def _read_results(self, memory)
Read back the probed results. Returns ------- str A string of "0"s and "1"s, one for each millisecond of simulation.
8.121209
7.723165
1.051539
memory.seek(0) memory.write(struct.pack("<II", # sim_length self._simulator.length, # output_key self.output.routing_key)) # NB: memory.write will automat...
def _write_config(self, memory)
Write the configuration for this stimulus to memory.
10.003689
9.131822
1.095476
# Assign sequential routing key to new nets. wire = _Wire(source, sinks if sinks is not None else [], len(self._wires)) self._wires.append(wire) return wire
def _new_wire(self, source, sinks=None)
Create a new :py:class:`._Wire` with a unique routing key.
7.386695
5.809301
1.271529
# 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. component: {Cores: 1, SDRAM: component._get_config_s...
def run(self)
Run the simulation.
6.002425
5.952839
1.00833
import nbformat from metapack.jupyter.preprocessors import AddEpilog, AddProlog from metapack.jupyter.exporters import ExecutePreprocessor, Config from os.path import dirname, join, splitext, basename from nbconvert.preprocessors.execute import CellExecutionError with open(nb_path, encodi...
def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None)
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...
2.557251
2.626053
0.9738
with open(nb_path) as f: nb = nbformat.reads(f.read(), as_version=4) doc = ExtractInlineMetatabDoc(package_url="metapack+file:" + dirname(nb_path)).run(nb) package_name = doc.as_version(None) output_dir = join(getcwd(), package_name) de = DocumentationExporter(config=Config(), log=...
def convert_documentation(nb_path)
Run only the document conversion portion of the notebook conversion The final document will not be completel
6.301648
6.770081
0.930808
r = doc['Root'].as_dict() r.update(doc['Contacts'].as_dict()) r['author'] = r.get('author', r.get('creator', r.get('wrangler'))) return r
def doc_metadata(doc)
Create a metadata dict from a MetatabDoc, for Document conversion
6.268155
5.774366
1.085514
from metatab.rowgenerators import TextRowGenerator import nbformat with nb_path.open() as f: nb = nbformat.read(f, as_version=4) lines = '\n'.join(['Declare: metatab-latest'] + [get_cell_source(nb, tag) for tag in ['metadata', 'resources', ...
def extract_notebook_metatab(nb_path: Path)
Extract the metatab lines from a notebook and return a Metapack doc
4.712953
4.121377
1.143538
t = self.doc.find_first('Root.Datafile', value=ref) if t: self.prt("Datafile exists for '{}', deleting".format(ref)) self.doc.remove_term(t) term_name = self.classify_url(ref) ref, path, name = self.extract_path_name(ref) self.prt("Adding res...
def add_single_resource(self, ref, **properties)
Add a single resource, without trying to enumerate it's contents :param ref: :return:
6.158861
6.211513
0.991523
raise NotImplementedError("Still uses decompose_url") du = Bunch(decompose_url(ref)) added = [] if du.proto == 'file' and isdir(ref): for f in self.find_files(ref, ['csv']): if f.endswith(DEFAULT_METATAB_FILE): continue ...
def add_resource(self, ref, **properties)
Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file
8.672932
8.353459
1.038244
if doc is None: doc = self.doc resources = doc['Resources'] # We don't need these anymore because all of the data written into the package is normalized. for arg in ['startline', 'headerlines', 'encoding']: for e in list(resources.args): ...
def _clean_doc(self, doc=None)
Clean the doc before writing it, removing unnecessary properties and doing other operations.
6.961927
6.639975
1.048487
from metapack.doc import MetapackDoc assert type(self.doc) == MetapackDoc for r in self.datafiles: # Special handling for SQL is probably a really bad idea. It should be handled as # a Rowgenerator. if r.term_is('root.sql'): if not...
def _load_resources(self, abs_path=False)
Copy all of the Datafile entries into the package
4.220024
4.025699
1.048271
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_is('Root.Documentation'): # Prefer the slugified title to the base name, becaus...
def _load_documentation_files(self)
Copy all of the Datafile
6.437839
6.390921
1.007341
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, '').strip('/') src = parse_app_url(join(dr, fn...
def _load_files(self)
Load other files
4.935977
4.905942
1.006122
from os.path import abspath, islink from os import unlink, symlink nv_name = self.doc.as_version(None) from_path = abspath(self._last_write_path or self.package_path.path) to_path = join(dirname(from_path), nv_name + self.type_suffix) if islink(to_path): ...
def create_nv_link(self)
After a save(), write a link to the saved file using a non-versioned name
5.506921
4.693952
1.173195
for job in jobs: if job.should_start: job.status = JobStatus.QUEUED queue = self._get_queue(job.queue) queue.put(job.serialize()) else: with self._lock: job.status = JobStatus.WAITING ...
def enqueue_jobs(self, jobs: Iterable[Job])
Enqueue a batch of jobs.
3.903879
3.65619
1.067745
for task in tasks: self._scheduler.enter( int(task.periodicity.total_seconds()), 0, self._schedule_periodic_task, argument=(task,) )
def register_periodic_tasks(self, tasks: Iterable[Task])
Register tasks that need to be scheduled periodically.
4.892084
3.733906
1.310178
try: next_event = self._scheduler.queue[0] except IndexError: return None now = time.monotonic() next_event_time = next_event[0] if next_event_time < now: return 0 return next_event_time - now
def next_future_periodic_delta(self) -> Optional[float]
Give the amount of seconds before the next periodic task is due.
2.771667
2.625252
1.055771
return [(int(e[0]), e[3][0].name) for e in self._scheduler.queue]
def inspect_periodic_tasks(self) -> List[Tuple[int, str]]
Get the next periodic task schedule. Used only for debugging and during tests.
9.970221
9.891786
1.007929
rv = list() while len(rv) < max_jobs: try: job_json_string = self._get_queue(queue).get(block=False) except Empty: break job = Job.deserialize(job_json_string) job.status = JobStatus.RUNNING rv.append(j...
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]
Get jobs from a queue.
2.940139
2.81497
1.044466
link = self.soup.find("a", attrs={'href': url}) if link: for p in link.parents: if p.name in ('p', 'div'): return ' '.join(p.text.split()[0:30]) return None
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.
3.881259
3.556825
1.091215
yield 'a b c'.split() for i in range(10): yield [i, i*2, i*3]
def row_generator(resource, doc, env, *args, **kwargs)
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...
5.580137
6.471726
0.862233
return str(v)+'-foo'
def example_transform(v, row, row_n, i_s, i_d, header_s, header_d,scratch, errors, accumulator)
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...
89.714767
83.169189
1.078702
from metapack import Downloader from os import environ return environ.get('METAPACK_SEARCH_INDEX', Downloader.get_instance().cache.getsyspath('index.json'))
def search_index_file()
Return the default local index file, from the download cache
11.211069
8.020762
1.397756
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_file, 'w') as f: json.dump(self._db, f, indent=4) if exists(index_file): copy(index...
def write(self)
Safely write the index data to the index file
2.707782
2.469097
1.096669
self.open() try: self._db.update(o._db) except AttributeError: self._db.update(o)
def update(self,o)
Update from another index or index dict
5.867938
5.042955
1.163591
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']) )
def bounds(ctx, tile)
Print Tile bounds.
4.918809
4.565179
1.077462
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_format'] in ['WKT', 'Tile']: click.echo(geom) elif ctx.obj['output_format'] == 'GeoJSON': ...
def bbox(ctx, tile)
Print Tile bounding box as geometry.
3.84602
3.62771
1.060178