code stringlengths 1 18.2k |
|---|
= [] if not cdbs_root.endswith(os.sep): cdbs_root += os.sep # See https://github.com/astropy/astropy/issues/8524 for cfgitem in conf.__class__.__dict__.values(): if (not isinstance(cfgitem, ConfigItem) or not cfgitem.name.endswith('file')): continue url = cfgitem() if not url.startswith(host): if verbose: # pragma: no ... |
# Create sub-directories, if needed. subdirs = os.path.dirname(dst) os.makedirs(subdirs, exist_ok=True) if not dry_run: # pragma: no cover try: src = download_file(url) copyfile(src, dst) except Exception as exc: print('Download failed - {}'.format(str(exc))) continue file_list.append(dst) if verbose: # pragma: no cove... |
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() # Changing position of windows: await pyvl... |
pyvlx.disconnect() |
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) |
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 self.__nodes.append(node) |
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() |
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 information") notification_frame = get_node_inform... |
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 information") self.clear() for notification_frame in g... |
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 FrameGetAllNodesInformationNotification return False if isinstance(fram... |
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 if isinstance(frame, FrameGetNodeInformati... |
def start(self): """Create loop task.""" self.run_task = self.pyvlx.loop.create_task( self.loop()) |
async def stop(self): """Stop heartbeat.""" self.stopped = True self.loop_event.set() # Waiting for shutdown of loop() await self.stopped_event.wait() |
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: self.loop_event.clear() await self.pulse() self.cancel_loop_timeout() ... |
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.") |
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 |
def from_payload(self, payload): """Init frame from binary data.""" self.gateway_state = GatewayState(payload[0]) self.gateway_sub_state = GatewaySubState(payload[1]) |
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)) |
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") |
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_position_fp2.raw) payload += bytes(self.current_position... |
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.current_position_fp2 = Parameter(payload[8:10]) self.curren... |
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.") |
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.") |
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 |
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 |
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 value I.e., `... |
type: >>> import bitmath >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument("--file-size", type=bitmath.BitmathType) >>> parser.parse_args("--file-size 1337MiB".split()) Namespace(file_size=MiB(1337.0)) Invalid usage includes any input that the bitmath.parse_string function already rejec... |
The following is ACCEPTABLE USAGE: ... >>> parser.parse_args(shlex.split("--file-size '1337 MiB'")) Namespace(file_size=MiB(1337.0)) >>> # The following is INCORRECT USAGE because the string "1337 MiB" is not quoted! ... >>> parser.parse_args(shlex.split("--file-size 1337 MiB")) error: argument --file-size: 1337 can no... |
else: return argvalue |
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: speed = pbar.currval / pbar.seconds_elapsed scale... |
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.success = True return not self.wait_for_completion... |
good for. # Ignoring these packets for now return False if isinstance(frame, FrameSessionFinishedNotification) and frame.session_id == self.session_id: return True return False |
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) |
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['config']['host'] self.password = doc['config']['password'] if 'port' in doc['config']: ... |
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) sip.setapi("QVariant", 2) except ValueError: logging.getLogger(__name__).critical... |
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 PyQt5 os.environ[QT_API] = PYQT5_API[0] logging.getLogg... |
PythonQtError('No Qt bindings could be found') |
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) |
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 True # We are still waiting for FrameGetSceneListNotificatio... |
received scenes does not match expected number") self.success = True return True return False |
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 |
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_length') self.scenes = [] for i in range(number_of_objec... |
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.data.get_readable_fileobj`. kwargs : dict Keywords acceptab... |
header, wavelengths, fluxes = read_spec(fd, fname=filename, **kwargs) return header, wavelengths, fluxes |
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 :func:`read_fits_spec` (if FITS) or :func:`read_as... |
Raises ------ synphot.exceptions.SynphotError Read failed. """ if isinstance(filename, str): fname = filename elif not fname: # pragma: no cover raise exceptions.SynphotError('Cannot determine filename.') if fname.endswith('fits') or fname.endswith('fit'): read_func = read_fits_spec else: read_func = read_ascii_spec re... |
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 ---------- filename : str or file pointer Spectrum f... |
respectively. kwargs : dict Keywords accepted by :func:`astropy.io.ascii.ui.read`. Returns ------- header : dict This is just an empty dictionary, so returned values are the same as :func:`read_fits_spec`. wavelengths, fluxes : `~astropy.units.quantity.Quantity` Wavelength and flux of the spectrum. They are set to 'flo... |
dat.columns[1].data.astype(np.float64) * flux_unit return header, wavelengths, fluxes |
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 keywords are not present, units are take... |
1. wave_col, flux_col : str Wavelength and flux column names (case-insensitive). wave_unit, flux_unit : str or `~astropy.units.core.Unit` Wavelength and flux units, which default to Angstrom and FLAM, respectively. These are *only* used if ``TUNIT1`` and ``TUNIT2`` keywords are not present in table (not primary) header... |
of the spectrum. """ fs = fits.open(filename) header = dict(fs[str('PRIMARY')].header) wave_dat = fs[ext].data.field(wave_col).copy() flux_dat = fs[ext].data.field(flux_col).copy() fits_wave_unit = fs[ext].header.get('TUNIT1') fits_flux_unit = fs[ext].header.get('TUNIT2') if fits_wave_unit is not None: try: wave_unit =... |
= units.validate_unit(fits_flux_unit) except (exceptions.SynphotError, ValueError) as e: # pragma: no cover warnings.warn( '{0} from FITS header is not valid flux unit, using ' '{1}: {2}'.format(fits_flux_unit, flux_unit, e), AstropyUserWarning) wave_unit = units.validate_unit(wave_unit) flux_unit = units.validate_unit... |
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.FLAM): """Write FITS spectrum. .. warning:: If data is being written out as singl... |
be added to primary and given extension FITS header, respectively. Do *not* use this to define column names and units. overwrite : bool Overwrite existing file. Defaults to `False`. trim_zero : bool Remove rows with zero-flux. Default is `True`. pad_zero_ends : bool Pad each end of the spectrum with a row of zero flux ... |
precision : {`None`, 'single', 'double'} Precision of values in output file. Use native flux precision by default. epsilon : float Single-precision :math:`\\epsilon` value, taken from IRAF SYNPHOT FAQ. This is the minimum separation in wavelengths necessary for SYNPHOT to read the entries as distinct single-precision n... |
flux_col : str Wavelength and flux column names (case-insensitive). wave_unit, flux_unit : str or `~astropy.units.core.Unit` Wavelength and flux units, which default to Angstrom and FLAM, respectively. These are *only* used if wavelengths and fluxes are not in astropy quantities. Raises ------ synphot.exceptions.Synpho... |
else: wave_value = wavelengths if isinstance(fluxes, u.Quantity): flux_unit = fluxes.unit flux_value = fluxes.value else: flux_value = fluxes wave_unit = units.validate_unit(wave_unit).to_string().upper() flux_unit = units.validate_unit(flux_unit).to_string().upper() if wave_value.shape != flux_value.shape: raise excep... |
np.where(flux_value != 0) wave_value = wave_value[idx] flux_value = flux_value[idx] n_thrown = wave_value.size - len(idx[0]) if n_thrown != 0: log.info('{0} zero-flux rows are thrown out'.format(n_thrown)) # Only these Numpy types are supported # 'f' np.float32 # 'd' np.float64 pcodes = {'d': 'D', 'f': 'E'} # Numpy to ... |
pcodes: raise exceptions.SynphotError('flux is not float32 or float64') # Use user specified precision else: precision = precision.lower() if precision == 'single': precision = 'f' elif precision == 'double': precision = 'd' else: raise exceptions.SynphotError( 'precision must be single or double') # Now check waveleng... |
is double-precision but data is written out as # single-precision, wavelength values have to be recalculated # so that they will still be sorted with no duplicates. if wave_precision == 'd' and precision == 'f': orig_size = wave_value.size idx = np.where(np.abs(wave_value[1:] - wave_value[:-1]) > epsilon) wave_value = ... |
rows are thrown out in converting wavelengths from ' 'double- to single-precision'.format(n_thrown), AstropyUserWarning) # Keep one zero at each end if pad_zero_ends: w1 = wave_value[0] ** 2 / wave_value[1] w2 = wave_value[-1] ** 2 / wave_value[-2] wave_value = np.insert(wave_value, [0, wave_value.size], [w1, w2]) flux... |
unit=flux_unit, format=pcodes[precision]) # These are written to the primary header: # 1. Filename # 2. Origin # 3. User dictionary (can overwrite defaults) hdr_hdu = fits.PrimaryHDU() hdr_hdu.header['filename'] = (os.path.basename(filename), 'name of file') hdr_hdu.header['origin'] = ('synphot', 'Version {0}'.format(_... |
in ext_header.items(): tab_hdu.header[key] = val # Write to file hdulist = fits.HDUList([hdr_hdu]) hdulist.append(tab_hdu) hdulist.writeto(filename, overwrite=overwrite) |
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 of Vega at ``wav``. Returns ----... |
- 99 mask = np.isfinite(val) if result.ndim > 0: result[mask] = val[mask] elif mask: result = np.asarray(val) return result def iconverter(x): return vega_photlam * 10**(-0.4 * x) return [(PHOTLAM, VEGAMAG, converter, iconverter)] |
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` Telescope collecting area. Returns -----... |
factor def iconverter_count(x): return x / factor def converter_obmag(x): return -2.5 * np.log10(x * factor) def iconverter_obmag(x): return 10**(-0.4 * x) / factor return [(PHOTLAM, u.count, converter_count, iconverter_count), (PHOTLAM, OBMAG, converter_obmag, iconverter_obmag)] |
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 Angstrom. fluxes : array-like or `~astro... |
not a Quantity, assumed to be in :math:`cm^{2}`. This value *must* be provided for conversions involving OBMAG and count, otherwise it is not needed. vegaspec : `~synphot.spectrum.SourceSpectrum` Vega spectrum from :func:`~synphot.spectrum.SourceSpectrum.from_vega`. This is *only* used for conversions involving VEGAMAG... |
not isinstance(fluxes, u.Quantity): fluxes = fluxes * PHOTLAM out_flux_unit = validate_unit(out_flux_unit) out_flux_unit_name = out_flux_unit.to_string() in_flux_unit_name = fluxes.unit.to_string() # No conversion necessary if in_flux_unit_name == out_flux_unit_name: return fluxes in_flux_type = fluxes.unit.physical_ty... |
unit except u.UnitConversionError: # Convert input unit to PHOTLAM if fluxes.unit == PHOTLAM: flux_photlam = fluxes elif in_flux_type != 'unknown': flux_photlam = fluxes.to(PHOTLAM, eqv) else: flux_photlam = _convert_flux( wavelengths, fluxes, PHOTLAM, **kwargs) # Convert PHOTLAM to output unit if out_flux_unit == PHOT... |
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( 'PHOTLAM must be one of the conversion units but ... |
OBMAG or count elif (u.count in (fluxes.unit, out_flux_unit) or OBMAG.to_string() in flux_unit_names): if area is None: raise exceptions.SynphotError( 'Area is compulsory for conversion involving count or OBMAG.') elif not isinstance(area, u.Quantity): area = area * AREA out_flux = fluxes.to( out_flux_unit, equivalenci... |
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 unit Parameters ---------- input_unit : str o... |
Backward-compatibility if input_unit_lowcase == 'angstroms': output_unit = u.AA elif input_unit_lowcase == 'inversemicrons': output_unit = u.micron ** -1 elif input_unit_lowcase in ('transmission', 'extinction', 'emissivity'): output_unit = THROUGHPUT elif input_unit_lowcase == 'jy': output_unit = u.Jy # Work around ma... |
except ValueError: # synphot is case-insensitive output_unit = u.Unit(input_unit_lowcase) elif isinstance(input_unit, (u.UnitBase, u.LogUnit)): output_unit = input_unit else: raise exceptions.SynphotError( '{0} must be a recognized string or ' 'astropy.units.core.Unit'.format(input_unit)) return output_unit |
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 type is not length, wave number, or ... |
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 validate. If not a Quantity, assumed to be ... |
given unit. """ output_unit = validate_unit(output_unit) if isinstance(input_value, u.Quantity): output_value = input_value.to(output_unit, equivalencies=equivalencies) else: output_value = input_value * output_unit return output_value |
def add(self, device): """Add device.""" if not isinstance(device, Device): raise TypeError() self.__devices.append(device) |
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 'category' not in item: raise PyVLXException('no element category: {0}'.form... |
not parse product: %s', category) |
def load_window_opener(self, item): """Load window opener from JSON.""" window = Window.from_config(self.pyvlx, item) self.add(window) |
def load_roller_shutter(self, item): """Load roller shutter from JSON.""" rollershutter = RollerShutter.from_config(self.pyvlx, item) self.add(rollershutter) |
def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind) |
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 wrong measurements (ins... |
sys.__stderr__, sys.__stdin__]: try: # Make WINSIZE call to terminal data = fcntl.ioctl(stream.fileno(), TIOCGWINSZ, b"\x00\x00\00\x00") except OSError: pass else: # Unpack two shorts from ioctl call lines, columns = struct.unpack("hh", data) break else: columns, lines = fallback return columns, lines |
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) > 1 else ("", "") for file in files: print(header.format(fi... |
print(*self.diff(results.original, results.styled), sep="\n") print() conjunction = "And" else: termcolor.cprint("Looks good!", "green") conjunction = "But" if results.diffs: for type, c in sorted(self._warn_chars): color, verb = ("on_green", "insert") if type == "+" else ("on_red", "delete") termcolor.cprint(c, None, ... |
if (results.comment_ratio < results.COMMENT_MIN or self._warn_chars) and results.diffs: print() |
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: checks[file] = { "error": e.msg } else: checks[file] = { "score": results.score, "comments... |
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, "yellow", file=sys.stderr) continue diffs += results.diffs lines += results.lines try: print(max(1 - diffs / l... |
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: check = self.extension_map[extension[1:]] except KeyError: magic_type = magic... |
f: code = "\n".join(line.rstrip() for line in f) except UnicodeDecodeError: raise Error("file does not seem to contain text, skipping...") # Ensure we don't warn about adding trailing newline try: if code[-1] != '\n': code += '\n' except IndexError: pass return check(code) |
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())) |
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 else: yield termcolor.colored(diff, "red" if diff[0] == "-" else "green", attrs=["bold"]) |
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 ["+", "-"]: continue tags.append("<{}{}>".format(tag[0], "ins" if tag[1] == "+" els... |
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 new_type == "+" else None) return "{}{}".format(termcolor.RESET, new_color[:-len(termco... |
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 difference. dtype = None # Buffer for current line. ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.