INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Finds moves in a given direction
def moves_in_direction(self, direction, position): """ Finds moves in a given direction :type: direction: lambda :type: position: Board :rtype: list """ current_square = self.location while True: try: current_square = directio...
Returns all possible rook moves.
def possible_moves(self, position): """ Returns all possible rook moves. :type: position: Board :rtype: list """ for move in itertools.chain(*[self.moves_in_direction(fn, position) for fn in self.cross_fn]): yield move
Check overlap between two arrays.
def overlap_status(a, b): """Check overlap between two arrays. Parameters ---------- a, b : array-like Arrays to check. Assumed to be in the same unit. Returns ------- result : {'full', 'partial', 'none'} * 'full' - ``a`` is within or same as ``b`` * 'partial' - ``a...
Check integrated flux for invalid values.
def validate_totalflux(totalflux): """Check integrated flux for invalid values. Parameters ---------- totalflux : float Integrated flux. Raises ------ synphot.exceptions.SynphotError Input is zero, negative, or not a number. """ if totalflux <= 0.0: raise e...
Check wavelengths for synphot compatibility.
def validate_wavelengths(wavelengths): """Check wavelengths for ``synphot`` compatibility. Wavelengths must satisfy these conditions: * valid unit type, if given * no zeroes * monotonic ascending or descending * no duplicate values Parameters ---------- wavelengths...
Generate wavelength array to be used for spectrum sampling.
def generate_wavelengths(minwave=500, maxwave=26000, num=10000, delta=None, log=True, wave_unit=u.AA): """Generate wavelength array to be used for spectrum sampling. .. math:: minwave \\le \\lambda < maxwave Parameters ---------- minwave, maxwave : float L...
Return the union of the two sets of wavelengths using: func: numpy. union1d.
def merge_wavelengths(waveset1, waveset2, threshold=1e-12): """Return the union of the two sets of wavelengths using :func:`numpy.union1d`. The merged wavelengths may sometimes contain numbers which are nearly equal but differ at levels as small as 1e-14. Having values this close together can cause...
Download CDBS data files to given root directory. Download is skipped if a data file already exists.
def download_data(cdbs_root, verbose=True, dry_run=False): """Download CDBS data files to given root directory. Download is skipped if a data file already exists. Parameters ---------- cdbs_root : str Root directory for CDBS data files. verbose : bool Print extra information to...
Demonstrate functionality of PyVLX.
async def main(loop): """Demonstrate functionality of PyVLX.""" pyvlx = PyVLX('pyvlx.yaml', loop=loop) # Alternative: # pyvlx = PyVLX(host="192.168.2.127", password="velux123", loop=loop) # Runing scenes: await pyvlx.load_scenes() await pyvlx.scenes["All Windows Closed"].run() # Changi...
Return Payload.
def get_payload(self): """Return Payload.""" if self.password is None: raise PyVLXException("password is none") if len(self.password) > self.MAX_SIZE: raise PyVLXException("password is too long") return string_to_bytes(self.password, self.MAX_SIZE)
Add Node replace existing node if node with node_id is present.
def add(self, node): """Add Node, replace existing node if node with node_id is present.""" if not isinstance(node, Node): raise TypeError() for i, j in enumerate(self.__nodes): if j.node_id == node.node_id: self.__nodes[i] = node return ...
Load nodes from KLF 200 if no node_id is specified all nodes are loaded.
async def load(self, node_id=None): """Load nodes from KLF 200, if no node_id is specified all nodes are loaded.""" if node_id is not None: await self._load_node(node_id=node_id) else: await self._load_all_nodes()
Load single node via API.
async def _load_node(self, node_id): """Load single node via API.""" get_node_information = GetNodeInformation(pyvlx=self.pyvlx, node_id=node_id) await get_node_information.do_api_call() if not get_node_information.success: raise PyVLXException("Unable to retrieve node inform...
Load all nodes via API.
async def _load_all_nodes(self): """Load all nodes via API.""" get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx) await get_all_nodes_information.do_api_call() if not get_all_nodes_information.success: raise PyVLXException("Unable to retrieve node informatio...
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetAllNodesInformationConfirmation): self.number_of_nodes = frame.number_of_nodes # We are still waiting for FrameGetAllNodesInformationNoti...
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetNodeInformationConfirmation) and frame.node_id == self.node_id: # We are still waiting for GetNodeInformationNotification return False ...
Create loop task.
def start(self): """Create loop task.""" self.run_task = self.pyvlx.loop.create_task( self.loop())
Stop heartbeat.
async def stop(self): """Stop heartbeat.""" self.stopped = True self.loop_event.set() # Waiting for shutdown of loop() await self.stopped_event.wait()
Pulse every timeout seconds until stopped.
async def loop(self): """Pulse every timeout seconds until stopped.""" while not self.stopped: self.timeout_handle = self.pyvlx.connection.loop.call_later( self.timeout_in_seconds, self.loop_timeout) await self.loop_event.wait() if not self.stopped: ...
Send get state request to API to keep the connection alive.
async def pulse(self): """Send get state request to API to keep the connection alive.""" get_state = GetState(pyvlx=self.pyvlx) await get_state.do_api_call() if not get_state.success: raise PyVLXException("Unable to send get state.")
Return Payload.
def get_payload(self): """Return Payload.""" payload = bytes([self.gateway_state.value, self.gateway_sub_state.value]) payload += bytes(4) # State date, reserved for future use return payload
Init frame from binary data.
def from_payload(self, payload): """Init frame from binary data.""" self.gateway_state = GatewayState(payload[0]) self.gateway_sub_state = GatewaySubState(payload[1])
Convert string to bytes add padding.
def string_to_bytes(string, size): """Convert string to bytes add padding.""" if len(string) > size: raise PyVLXException("string_to_bytes::string_to_large") encoded = bytes(string, encoding='utf-8') return encoded + bytes(size-len(encoded))
Convert bytes to string.
def bytes_to_string(raw): """Convert bytes to string.""" ret = bytes() for byte in raw: if byte == 0x00: return ret.decode("utf-8") ret += bytes([byte]) return ret.decode("utf-8")
Return Payload.
def get_payload(self): """Return Payload.""" payload = bytes([self.node_id]) payload += bytes([self.state]) payload += bytes(self.current_position.raw) payload += bytes(self.target.raw) payload += bytes(self.current_position_fp1.raw) payload += bytes(self.current_...
Init frame from binary data.
def from_payload(self, payload): """Init frame from binary data.""" self.node_id = payload[0] self.state = payload[1] self.current_position = Parameter(payload[2:4]) self.target = Parameter(payload[4:6]) self.current_position_fp1 = Parameter(payload[6:8]) self.cur...
Enable house status monitor.
async def house_status_monitor_enable(pyvlx): """Enable house status monitor.""" status_monitor_enable = HouseStatusMonitorEnable(pyvlx=pyvlx) await status_monitor_enable.do_api_call() if not status_monitor_enable.success: raise PyVLXException("Unable enable house status monitor.")
Disable house status monitor.
async def house_status_monitor_disable(pyvlx): """Disable house status monitor.""" status_monitor_disable = HouseStatusMonitorDisable(pyvlx=pyvlx) await status_monitor_disable.do_api_call() if not status_monitor_disable.success: raise PyVLXException("Unable disable house status monitor.")
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorEnableConfirmation): return False self.success = True return True
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorDisableConfirmation): return False self.success = True return True
An argument type for integrations with the argparse module.
def BitmathType(bmstring): """An 'argument type' for integrations with the argparse module. For more information, see https://docs.python.org/2/library/argparse.html#type Of particular interest to us is this bit: ``type=`` can take any callable that takes a single string argument and returns the converted v...
Updates the widget with the current NIST/ SI speed.
def update(self, pbar): """Updates the widget with the current NIST/SI speed. Basically, this calculates the average rate of update and figures out how to make a "pretty" prefix unit""" if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: scaled = bitmath.Byte() else: ...
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameCommandSendConfirmation) and frame.session_id == self.session_id: if frame.status == CommandSendConfirmationStatus.ACCEPTED: self.succes...
Construct initiating frame.
def request_frame(self): """Construct initiating frame.""" self.session_id = get_new_session_id() return FrameCommandSendRequest(node_ids=[self.node_id], parameter=self.parameter, session_id=self.session_id)
Read configuration file.
def read_config(self, path): """Read configuration file.""" PYVLXLOG.info('Reading config file: %s', path) try: with open(path, 'r') as filehandle: doc = yaml.safe_load(filehandle) self.test_configuration(doc, path) self.host = doc['con...
Setup apiv2 when using PyQt4 and Python2.
def setup_apiv2(): """ Setup apiv2 when using PyQt4 and Python2. """ # setup PyQt api to version 2 if sys.version_info[0] == 2: logging.getLogger(__name__).debug( 'setting up SIP API to version 2') import sip try: sip.setapi("QString", 2) s...
Auto - detects and use the first available QT_API by importing them in the following order:
def autodetect(): """ Auto-detects and use the first available QT_API by importing them in the following order: 1) PyQt5 2) PyQt4 3) PySide """ logging.getLogger(__name__).debug('auto-detecting QT_API') try: logging.getLogger(__name__).debug('trying PyQt5') import Py...
Read roller shutter from config.
def from_config(cls, pyvlx, item): """Read roller shutter from config.""" name = item['name'] ident = item['id'] subtype = item['subtype'] typeid = item['typeId'] return cls(pyvlx, ident, name, subtype, typeid)
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetSceneListConfirmation): self.count_scenes = frame.count_scenes if self.count_scenes == 0: self.success = True ...
Return Payload.
def get_payload(self): """Return Payload.""" ret = bytes([len(self.scenes)]) for number, name in self.scenes: ret += bytes([number]) ret += string_to_bytes(name, 64) ret += bytes([self.remaining_scenes]) return ret
Init frame from binary data.
def from_payload(self, payload): """Init frame from binary data.""" number_of_objects = payload[0] self.remaining_scenes = payload[-1] predicted_len = number_of_objects * 65 + 2 if len(payload) != predicted_len: raise PyVLXException('scene_list_notification_wrong_leng...
Read FITS or ASCII spectrum from a remote location.
def read_remote_spec(filename, encoding='binary', cache=True, show_progress=True, **kwargs): """Read FITS or ASCII spectrum from a remote location. Parameters ---------- filename : str Spectrum filename. encoding, cache, show_progress See :func:`~astropy.utils....
Read FITS or ASCII spectrum.
def read_spec(filename, fname='', **kwargs): """Read FITS or ASCII spectrum. Parameters ---------- filename : str or file pointer Spectrum file name or pointer. fname : str Filename. This is *only* used if ``filename`` is a pointer. kwargs : dict Keywords acceptable by...
Read ASCII spectrum.
def read_ascii_spec(filename, wave_unit=u.AA, flux_unit=units.FLAM, **kwargs): """Read ASCII spectrum. ASCII table must have following columns: #. Wavelength data #. Flux data It can have more than 2 columns but the rest is ignored. Comments are discarded. Parameters --------...
Read FITS spectrum.
def read_fits_spec(filename, ext=1, wave_col='WAVELENGTH', flux_col='FLUX', wave_unit=u.AA, flux_unit=units.FLAM): """Read FITS spectrum. Wavelength and flux units are extracted from ``TUNIT1`` and ``TUNIT2`` keywords, respectively, from data table (not primary) header. If these keyw...
Write FITS spectrum.
def write_fits_spec(filename, wavelengths, fluxes, pri_header={}, ext_header={}, overwrite=False, trim_zero=True, pad_zero_ends=True, precision=None, epsilon=0.00032, wave_col='WAVELENGTH', flux_col='FLUX', wave_unit=u.AA, flux_unit=units.F...
Flux equivalencies between PHOTLAM and VEGAMAG.
def spectral_density_vega(wav, vegaflux): """Flux equivalencies between PHOTLAM and VEGAMAG. Parameters ---------- wav : `~astropy.units.quantity.Quantity` Quantity associated with values being converted (e.g., wavelength or frequency). vegaflux : `~astropy.units.quantity.Quantity`...
Flux equivalencies between PHOTLAM and count/ OBMAG.
def spectral_density_count(wav, area): """Flux equivalencies between PHOTLAM and count/OBMAG. Parameters ---------- wav : `~astropy.units.quantity.Quantity` Quantity associated with values being converted (e.g., wavelength or frequency). area : `~astropy.units.quantity.Quantity` ...
Perform conversion for: ref: supported flux units <synphot - flux - units >.
def convert_flux(wavelengths, fluxes, out_flux_unit, **kwargs): """Perform conversion for :ref:`supported flux units <synphot-flux-units>`. Parameters ---------- wavelengths : array-like or `~astropy.units.quantity.Quantity` Wavelength values. If not a Quantity, assumed to be in Angstro...
Flux conversion for PHOTLAM < - > X.
def _convert_flux(wavelengths, fluxes, out_flux_unit, area=None, vegaspec=None): """Flux conversion for PHOTLAM <-> X.""" flux_unit_names = (fluxes.unit.to_string(), out_flux_unit.to_string()) if PHOTLAM.to_string() not in flux_unit_names: raise exceptions.SynphotError( ...
Validate unit.
def validate_unit(input_unit): """Validate unit. To be compatible with existing SYNPHOT data files: * 'angstroms' and 'inversemicrons' are accepted although unrecognized by astropy units * 'transmission', 'extinction', and 'emissivity' are converted to astropy dimensionless...
Like: func: validate_unit but specific to wavelength.
def validate_wave_unit(wave_unit): """Like :func:`validate_unit` but specific to wavelength.""" output_unit = validate_unit(wave_unit) unit_type = output_unit.physical_type if unit_type not in ('length', 'wavenumber', 'frequency'): raise exceptions.SynphotError( 'wavelength physical...
Validate quantity ( value and unit ).
def validate_quantity(input_value, output_unit, equivalencies=[]): """Validate quantity (value and unit). .. note:: For flux conversion, use :func:`convert_flux` instead. Parameters ---------- input_value : number, array-like, or `~astropy.units.quantity.Quantity` Quantity to vali...
Add device.
def add(self, device): """Add device.""" if not isinstance(device, Device): raise TypeError() self.__devices.append(device)
Import data from json response.
def data_import(self, json_response): """Import data from json response.""" if 'data' not in json_response: raise PyVLXException('no element data found: {0}'.format( json.dumps(json_response))) data = json_response['data'] for item in data: if 'ca...
Load window opener from JSON.
def load_window_opener(self, item): """Load window opener from JSON.""" window = Window.from_config(self.pyvlx, item) self.add(window)
Load roller shutter from JSON.
def load_roller_shutter(self, item): """Load roller shutter from JSON.""" rollershutter = RollerShutter.from_config(self.pyvlx, item) self.add(rollershutter)
Load blind from JSON.
def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind)
Return tuple containing columns and rows of controlling terminal trying harder than shutil. get_terminal_size to find a tty before returning fallback.
def get_terminal_size(fallback=(80, 24)): """ Return tuple containing columns and rows of controlling terminal, trying harder than shutil.get_terminal_size to find a tty before returning fallback. Theoretically, stdout, stderr, and stdin could all be different ttys that could cause us to get the wr...
Run checks on self. files printing diff of styled/ unstyled output to stdout.
def run_diff(self): """ Run checks on self.files, printing diff of styled/unstyled output to stdout. """ files = tuple(self.files) # Use same header as more. header, footer = (termcolor.colored("{0}\n{{}}\n{0}\n".format( ":" * 14), "cyan"), "\n") if len(files)...
Run checks on self. files printing json object containing information relavent to the CS50 IDE plugin at the end.
def run_json(self): """ Run checks on self.files, printing json object containing information relavent to the CS50 IDE plugin at the end. """ checks = {} for file in self.files: try: results = self._check(file) except Error as e: ...
Run checks on self. files printing raw percentage to stdout.
def run_score(self): """ Run checks on self.files, printing raw percentage to stdout. """ diffs = 0 lines = 0 for file in self.files: try: results = self._check(file) except Error as e: termcolor.cprint(e.msg, "yell...
Run apropriate check based on file s extension and return it otherwise raise an Error
def _check(self, file): """ Run apropriate check based on `file`'s extension and return it, otherwise raise an Error """ if not os.path.exists(file): raise Error("file \"{}\" not found".format(file)) _, extension = os.path.splitext(file) try: ...
Returns a generator yielding the side - by - side diff of old and new ).
def split_diff(old, new): """ Returns a generator yielding the side-by-side diff of `old` and `new`). """ return map(lambda l: l.rstrip(), icdiff.ConsoleDiff(cols=COLUMNS).make_table(old.splitlines(), new.splitlines()))
Returns a generator yielding a unified diff between old and new.
def unified(old, new): """ Returns a generator yielding a unified diff between `old` and `new`. """ for diff in difflib.ndiff(old.splitlines(), new.splitlines()): if diff[0] == " ": yield diff elif diff[0] == "?": continue ...
Return HTML formatted character - based diff between old and new ( used for CS50 IDE ).
def html_diff(self, old, new): """ Return HTML formatted character-based diff between old and new (used for CS50 IDE). """ def html_transition(old_type, new_type): tags = [] for tag in [("/", old_type), ("", new_type)]: if tag[1] not in ["+", "-"]:...
Return color - coded character - based diff between old and new.
def char_diff(self, old, new): """ Return color-coded character-based diff between `old` and `new`. """ def color_transition(old_type, new_type): new_color = termcolor.colored("", None, "on_red" if new_type == "-" else "on_green" if n...
Returns a char - based diff between old and new where each character is formatted by fmt and transitions between blocks are determined by transition.
def _char_diff(self, old, new, transition, fmt=lambda c: c): """ Returns a char-based diff between `old` and `new` where each character is formatted by `fmt` and transitions between blocks are determined by `transition`. """ differ = difflib.ndiff(old, new) # Type of di...
Count lines of code ( by default ignores empty lines but child could override to do more ).
def count_lines(self, code): """ Count lines of code (by default ignores empty lines, but child could override to do more). """ return sum(bool(line.strip()) for line in code.splitlines())
Run command passing it stdin from input throwing a DependencyError if comand is not found. Throws Error if exit code of command is not exit ( unless exit is None ).
def run(command, input=None, exit=0, shell=False): """ Run `command` passing it stdin from `input`, throwing a DependencyError if comand is not found. Throws Error if exit code of command is not `exit` (unless `exit` is None). """ if isinstance(input, str): input = in...
Create and return frame from raw bytes.
def frame_from_raw(raw): """Create and return frame from raw bytes.""" command, payload = extract_from_frame(raw) frame = create_frame(command) if frame is None: PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw)) return None fr...
Create and return empty Frame from Command.
def create_frame(command): """Create and return empty Frame from Command.""" # pylint: disable=too-many-branches,too-many-return-statements if command == Command.GW_ERROR_NTF: return FrameErrorNotification() if command == Command.GW_COMMAND_SEND_REQ: return FrameCommandSendRequest() ...
Handle incoming API frame return True if this was the expected frame.
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FramePasswordEnterConfirmation): return False if frame.status == PasswordEnterConfirmationStatus.FAILED: PYVLXLOG.warning('Failed to ...
Return Payload.
def get_payload(self): """Return Payload.""" return bytes( [self.major_version >> 8 & 255, self.major_version & 255, self.minor_version >> 8 & 255, self.minor_version & 255])
Init frame from binary data.
def from_payload(self, payload): """Init frame from binary data.""" self.major_version = payload[0] * 256 + payload[1] self.minor_version = payload[2] * 256 + payload[3]
Handle data received.
def data_received(self, data): """Handle data received.""" self.tokenizer.feed(data) while self.tokenizer.has_tokens(): raw = self.tokenizer.get_next_token() frame = frame_from_raw(raw) if frame is not None: self.frame_received_cb(frame)
Connect to gateway via SSL.
async def connect(self): """Connect to gateway via SSL.""" tcp_client = TCPTransport(self.frame_received_cb, self.connection_closed_cb) self.transport, _ = await self.loop.create_connection( lambda: tcp_client, host=self.config.host, port=self.config.port, ...
Write frame to Bus.
def write(self, frame): """Write frame to Bus.""" if not isinstance(frame, FrameBase): raise PyVLXException("Frame not of type FrameBase", frame_type=type(frame)) PYVLXLOG.debug("SEND: %s", frame) self.transport.write(slip_pack(bytes(frame)))
Create and return SSL Context.
def create_ssl_context(): """Create and return SSL Context.""" ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context
Received message.
def frame_received_cb(self, frame): """Received message.""" PYVLXLOG.debug("REC: %s", frame) for frame_received_cb in self.frame_received_cbs: # pylint: disable=not-callable self.loop.create_task(frame_received_cb(frame))
Read configuration file.
def read_config(self, path): """Read configuration file.""" self.pyvlx.logger.info('Reading config file: ', path) try: with open(path, 'r') as filehandle: doc = yaml.load(filehandle) if 'config' not in doc: raise PyVLXException('no ...
Update nodes via frame usually received by house monitor.
async def process_frame(self, frame): """Update nodes via frame, usually received by house monitor.""" if isinstance(frame, FrameNodeStatePositionChangedNotification): if frame.node_id not in self.pyvlx.nodes: return node = self.pyvlx.nodes[frame.node_id] ...
Add scene replace existing scene if scene with scene_id is present.
def add(self, scene): """Add scene, replace existing scene if scene with scene_id is present.""" if not isinstance(scene, Scene): raise TypeError() for i, j in enumerate(self.__scenes): if j.scene_id == scene.scene_id: self.__scenes[i] = scene ...
Load scenes from KLF 200.
async def load(self): """Load scenes from KLF 200.""" get_scene_list = GetSceneList(pyvlx=self.pyvlx) await get_scene_list.do_api_call() if not get_scene_list.success: raise PyVLXException("Unable to retrieve scene information") for scene in get_scene_list.scenes: ...
Return a bitmath instance representing the best human - readable representation of the number of bytes given by bytes. In addition to a numeric type the bytes parameter may also be a bitmath type.
def best_prefix(bytes, system=NIST): """Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` ...
Create bitmath instances of the capacity of a system block device
def query_device_capacity(device_fd): """Create bitmath instances of the capacity of a system block device Make one or more ioctl request to query the capacity of a block device. Perform any processing required to compute the final capacity value. Return the device capacity in bytes as a :class:`bitmath.Byte` inst...
Return a bitmath instance in the best human - readable representation of the file size at path. Optionally provide a preferred unit system by setting system to either bitmath. NIST ( default ) or bitmath. SI.
def getsize(path, bestprefix=True, system=NIST): """Return a bitmath instance in the best human-readable representation of the file size at `path`. Optionally, provide a preferred unit system by setting `system` to either `bitmath.NIST` (default) or `bitmath.SI`. Optionally, set ``bestprefix`` to ``False`` to get ...
This is a generator which recurses the directory tree search_base yielding 2 - tuples of:
def listdir(search_base, followlinks=False, filter='*', relpath=False, bestprefix=False, system=NIST): """This is a generator which recurses the directory tree `search_base`, yielding 2-tuples of: * The absolute/relative path to a discovered file * A bitmath instance representing the "apparent size" of...
Parse a string with units and try to make a bitmath object out of it.
def parse_string(s): """Parse a string with units and try to make a bitmath object out of it. String inputs may include whitespace characters between the value and the unit. """ # Strings only please if not isinstance(s, (str, unicode)): raise ValueError("parse_string only accepts string inputs...
Attempt to parse a string with ambiguous units and try to make a bitmath object out of it.
def parse_string_unsafe(s, system=SI): """Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate results if parsing shell output. For example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB ~= 2.666 KiB. See the documentation for all of...
Context manager for printing bitmath instances.
def format(fmt_str=None, plural=False, bestprefix=False): """Context manager for printing bitmath instances. ``fmt_str`` - a formatting mini-language compat formatting string. See the @properties (above) for a list of available items. ``plural`` - True enables printing instances with 's's if they're plural. False...
A command line interface to basic bitmath operations.
def cli_script_main(cli_args): """ A command line interface to basic bitmath operations. """ choices = ALL_UNIT_TYPES parser = argparse.ArgumentParser( description='Converts from one type of size to another.') parser.add_argument('--from-stdin', default=False, action='store_true', ...
Setup basic parameters for this class.
def _do_setup(self): """Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be...
Normalize the input value into the fundamental unit for this prefix type.
def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type. :param number value: The input value to be normalized :raises ValueError: if the input value is not a type of real number """ if isinstance(value, self.valid_types): self._byte_value =...
The system of units used to measure an instance
def system(self): """The system of units used to measure an instance""" if self._base == 2: return "NIST" elif self._base == 10: return "SI" else: # I don't expect to ever encounter this logic branch, but # hey, it's better to have extra te...
The string that is this instances prefix unit name in agreement with this instance value ( singular or plural ). Following the convention that only 1 is singular. This will always be the singular form when: attr: bitmath. format_plural is False ( default value ).
def unit(self): """The string that is this instances prefix unit name in agreement with this instance value (singular or plural). Following the convention that only 1 is singular. This will always be the singular form when :attr:`bitmath.format_plural` is ``False`` (default value). For example: >>> KiB(1)....
Factory function to return instances of item converted into a new instance of cls. Because this is a class method it may be called from any bitmath class object without the need to explicitly instantiate the class ahead of time.
def from_other(cls, item): """Factory function to return instances of `item` converted into a new instance of ``cls``. Because this is a class method, it may be called from any bitmath class object without the need to explicitly instantiate the class ahead of time. *Implicit Parameter:* * ``cls`` A bitmath cl...
Return a representation of this instance formatted with user supplied syntax
def format(self, fmt): """Return a representation of this instance formatted with user supplied syntax""" _fmt_params = { 'base': self.base, 'bin': self.bin, 'binary': self.binary, 'bits': self.bits, 'bytes': self.bytes, 'power': se...
Optional parameter system allows you to prefer NIST or SI in the results. By default the current system is used ( Bit/ Byte default to NIST ).
def best_prefix(self, system=None): """Optional parameter, `system`, allows you to prefer NIST or SI in the results. By default, the current system is used (Bit/Byte default to NIST). Logic discussion/notes: Base-case, does it need converting? If the instance is less than one Byte, return the instance as a B...
Normalize the input value into the fundamental unit for this prefix type
def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type""" self._bit_value = value * self._unit_value self._byte_value = self._bit_value / 8.0