code
stringlengths
1
18.2k
def parser(parser_type=basic_parser, functions=None, patterns=None, expressions=None, patterns_yaml_path=None, expressions_yaml_path=None): """ A Reparse parser description. Simply provide the functions, patterns, & expressions to build. If you are using YAML for expressions + patterns, you can use ``expressions_yaml_p...
yaml.safe_load(f) assert expressions or expressions_yaml_path, "Reparse can't build a parser without expressions" assert patterns or patterns_yaml_path, "Reparse can't build a parser without patterns" assert functions, "Reparse can't build without a functions" if patterns_yaml_path: patterns = _load_yaml(patterns_yaml_...
def _translate(self, input_filename, output_filename): """Translate KML file to geojson for import""" command = [ self.translate_binary, '-f', 'GeoJSON', output_filename, input_filename ] result = self._runcommand(command) self.log('Result (Translate): ', result, lvl=debug)
def _update_guide(self, guide, update=False, clear=True): """Update a single specified guide""" kml_filename = os.path.join(self.cache_path, guide + '.kml') geojson_filename = os.path.join(self.cache_path, guide + '.geojson') if not os.path.exists(geojson_filename) or update: try: data = request.urlopen(self.guides[gui...
len(json_data['features']) == 0: self.log('No features found!', lvl=warn) return layer = objectmodels['layer'].find_one({'name': guide}) if clear and layer is not None: layer.delete() layer = None if layer is None: layer_uuid = std_uuid() layer = objectmodels['layer']({ 'uuid': layer_uuid, 'name': guide, 'type': 'geoob...
json_data['features']: self.log('Adding new guide location:', item, lvl=verbose) location = objectmodels['geoobject']({ 'uuid': std_uuid(), 'layer': layer_uuid, 'geojson': item, 'type': 'Skipperguide', 'name': 'Guide for %s' % (item['properties']['Name']) }) locations.append(location) self.log('Bulk inserting guide loc...
def send_mail_worker(config, mail, event): """Worker task to send out an email, which is a blocking process unless it is threaded""" log = "" try: if config.get('ssl', True): server = SMTP_SSL(config['server'], port=config['port'], timeout=30) else: server = SMTP(config['server'], port=config['port'], timeout=30) if co...
'No username, trying anonymous access\n' log += 'Sending Mail\n' response_send = server.send_message(mail) server.quit() except timeout as e: log += 'Could not send email: ' + str(e) + "\n" return False, log, event log += 'Server response:' + str(response_send) return True, log, event
def send_mail(self, event): """Connect to mail server and send actual email""" mime_mail = MIMEText(event.text) mime_mail['Subject'] = event.subject if event.account == 'default': account_name = self.config.default_account else: account_name = event.account account = list(filter(lambda account: account['name'] == accou...
sending mail, here it is for debugging info:', mime_mail, pretty=True)
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a system user""" from hfos.provisions.base import provisionList from hfos.database import objectmodels # TODO: Add a root user and make sure owner can access it later. # Setting up details and asking for a...
emitter='PROVISIONS') overwrite = False system_user_count = objectmodels['user'].count({'name': 'System'}) if system_user_count == 0 or clear is False: provisionList(Users, 'user', overwrite, clear, skip_user_check=True) hfoslog('Provisioning: Users: Done.', emitter="PROVISIONS") else: hfoslog('System user already pres...
def AlternatesGroup(expressions, final_function, name=""): """ Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> grouping.regex # doctes...
def Group(expressions, final_function, inbetweens, name=""): """ Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. """ lengths = [] functions = [] regex = "" i = 0 for expression in expressions: regex += inbetweens[i] regex += "(?:" + expression.regex + ")" lengths.append(sum(...
def findall(self, string): """ Parse string, returning all outputs as parsed by functions """ output = [] for match in self.pattern.findall(string): if hasattr(match, 'strip'): match = [match] self._list_add(output, self.run(match)) return output
def scan(self, string): """ Like findall, but also returning matching start and end string locations """ return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
def run(self, matches): """ Run group functions over matches """ def _run(matches): group_starting_pos = 0 for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)): start_pos = current_pos + group_starting_pos end_pos = current_pos + group_starting_pos + group_length y...
def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
def is_muted(what): """ Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return: """ state = False for item in solo: if item not in what: state = True else: state = False break for item in mute: if item in what: state = T...
break return state
def hfoslog(*what, **kwargs): """Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, where this can't be determined automa...
give a hint at too high log level) global count global verbosity count += 1 lvl = kwargs.get('lvl', info) if lvl < verbosity['global']: return emitter = kwargs.get('emitter', 'UNKNOWN') traceback = kwargs.get('tb', False) frame_ref = kwargs.get('frame_ref', 0) output = None timestamp = time.time() runtime = timestamp -...
verbosity['global'] <= debug or traceback: # Automatically log the current function details. if 'sourceloc' not in kwargs: frame = kwargs.get('frame', frame_ref) # Get the previous frame in the stack, otherwise it would # be this function current_frame = inspect.currentframe() while frame > 0: frame -= 1 current_frame ...
log. if exception: line_no = exc_tb.tb_lineno if lvl <= error: lvl = error else: line_no = func.co_firstlineno callee = "[%.10s@%s:%i]" % ( func.co_name, func.co_filename, line_no ) else: callee = kwargs['sourceloc'] now = time.asctime() msg = "[%s] : %5s : %.5f : %3i : [%5s]" % (now, lvldata[lvl][0], runtime, count, e...
"%-60s" % callee else: msg += "%s" % callee for thing in what: content += " " if kwargs.get('pretty', False): content += pprint.pformat(thing) else: content += str(thing) msg += content if exception: msg += "\n" + "".join(format_exception(exc_type, exc_obj, exc_tb)) if is_muted(msg): return if not uncut and lvl > 10 an...
"a") f.write(msg + '\n') f.flush() f.close() except IOError: print("Can't open logfile %s for writing!" % logfile) # sys.exit(23) if is_marked(msg): lvl = hilight if lvl >= verbosity['console']: output = str(msg) if six.PY3 and color: output = lvldata[lvl][1] + output + terminator try: print(output) except UnicodeEncod...
lvl=warn) if live: item = [now, lvl, runtime, count, emitter, str(content)] LiveLog.append(item)
def get_tagged(self, event): """Return a list of tagged objects for a schema""" self.log("Tagged objects request for", event.data, "from", event.user, lvl=debug) if event.data in self.tags: tagged = self._get_tagged(event.data) response = { 'component': 'hfos.events.schemamanager', 'action': 'get', 'data': tagged } sel...
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions the default system vessel""" from hfos.provisions.base import provisionList from hfos.database import objectmodels vessel = objectmodels['vessel'].find_one({'name': 'Default System Vessel'}) if vessel i...
Vessel: Done.', emitter='PROVISIONS')
def get_tile(url): """ Threadable function to retrieve map tiles from the internet :param url: URL of tile to get """ log = "" connection = None try: if six.PY3: connection = urlopen(url=url, timeout=2) # NOQA else: connection = urlopen(url=url) except Exception as e: log += "MTST: ERROR Tilegetter error: %s " % str([t...
if connection: try: content = connection.read() except (socket.timeout, socket.error) as e: log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e]) connection.close() else: log += "MTST: ERROR Got no connection." return content, log
def tilecache(self, event, *args, **kwargs): """Checks and caches a requested tile to disk, then delivers it to client""" request, response = event.args[:2] self.log(request.path, lvl=verbose) try: filename, url = self._split_cache_url(request.path, 'tilecache') except UrlError: return # self.log('CACHE QUERY:', filena...
filename) finally: event.stop() else: # We will have to get it first. self.log("Tile not cached yet. Tile data: ", filename, url, lvl=verbose) if url in self._tiles: self.log("Getting a tile for the second time?!", lvl=error) else: self._tiles += url try: tile, log = yield self.call(task(get_tile, url), "tcworkers") if...
= os.path.dirname(filename) if tile: try: os.makedirs(tile_path) except OSError as e: if e.errno != errno.EEXIST: self.log( "Couldn't create path: %s (%s)" % (e, type(e)), lvl=error) self.log("Caching tile.", lvl=verbose) try: with open(filename, "wb") as tile_file: try: tile_file.write(bytes(tile)) except Exception as...
try: self.log("Delivering tile.", lvl=verbose) yield serve_file(request, response, filename) except Exception as e: self.log("Couldn't deliver tile: ", e, lvl=error) event.stop() self.log("Tile stored and delivered.", lvl=verbose) else: self.log("Got no tile, serving default tile: %s" % url) if self.default_tile: try: ...
def todegdec(origin): """ Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD """ # if the input is already a float (or can be converted to float) try: return float(origin) except ValueError: pass # DMS format m = dms_re.search(origin) if m: degrees = int(m.group('degrees')) minutes = float(m.gr...
= mindec_re.search(origin) if m: degrees = int(m.group('degrees')) minutes = float(m.group('minutes')) return degrees + minutes / 60
def tomindec(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) """ origin = float(origin) degrees = int(origin) minutes = (origin % 1) * 60 return degrees, minutes
def tomindecstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' """ degrees, minutes = tomindec(origin) return u'%d°%f\'' % (degrees, minutes)
def todms(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) """ degrees, minutes = tomindec(origin) seconds = (minutes % 1) * 60 return degrees, int(minutes), seconds
def todmsstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" """ degrees, minutes, seconds = todms(origin) return u'%d°%d\'%f"' % (degrees, minutes, seconds)
def towgs84(E, N, pkm=False, presentation=None): """ Convert coordintes from TWD97 to WGS84 The east and north coordinates should be in meters and in float pkm true for Penghu, Kinmen and Matsu area You can specify one of the following presentations of the returned values: dms - A tuple with degrees (int), minutes (int...
with degrees (int) and minutes (float) mindecstr - [+/-]DDD°MMM.MMMMM' (unicode) (default)degdec - DDD.DDDDD (float) """ _lng0 = lng0pkm if pkm else lng0 E /= 1000.0 N /= 1000.0 epsilon = (N-N0) / (k0*A) eta = (E-E0) / (k0*A) epsilonp = epsilon - beta1*sin(2*1*epsilon)*cosh(2*1*eta) - \ beta2*sin(2*2*epsilon)*cosh(2*2*...
2*1*beta1*cos(2*1*epsilon)*cosh(2*1*eta) - \ 2*2*beta2*cos(2*2*epsilon)*cosh(2*2*eta) - \ 2*3*beta3*cos(2*3*epsilon)*cosh(2*3*eta) taup = 2*1*beta1*sin(2*1*epsilon)*sinh(2*1*eta) + \ 2*2*beta2*sin(2*2*epsilon)*sinh(2*2*eta) + \ 2*3*beta3*sin(2*3*epsilon)*sinh(2*3*eta) chi = asin(sin(epsilonp) / cosh(etap)) latitude = c...
'todegdec': return func(degrees(latitude)), func(degrees(longitude)) return (degrees(latitude), degrees(longitude))
def fromwgs84(lat, lng, pkm=False): """ Convert coordintes from WGS84 to TWD97 pkm true for Penghu, Kinmen and Matsu area The latitude and longitude can be in the following formats: [+/-]DDD°MMM'SSS.SSSS" (unicode) [+/-]DDD°MMM.MMMM' (unicode) [+/-]DDD.DDDDD (string, unicode or float) The returned coordinates are in me...
= atan(t/cos(lng-_lng0)) etap = atan(sin(lng-_lng0) / pow(1+t*t, 0.5)) E = E0 + k0*A*(etap + alpha1*cos(2*1*epsilonp)*sinh(2*1*etap) + alpha2*cos(2*2*epsilonp)*sinh(2*2*etap) + alpha3*cos(2*3*epsilonp)*sinh(2*3*etap)) N = N0 + k0*A*(epsilonp + alpha1*sin(2*1*epsilonp)*cosh(2*1*etap) + alpha2*sin(2*2*epsilonp)*cosh(2*2*...
def clipValue(self, value, minValue, maxValue): ''' Makes sure that value is within a specific range. If not, then the lower or upper bounds is returned ''' return min(max(value, minValue), maxValue)
def getGroundResolution(self, latitude, level): ''' returns the ground resolution for based on latitude and zoom level. ''' latitude = self.clipValue(latitude, self.min_lat, self.max_lat); mapSize = self.getMapDimensionsByZoomLevel(level) return math.cos( latitude * math.pi / 180) * 2 * math.pi * self.earth_radius / \ ...
def getMapScale(self, latitude, level, dpi=96): ''' returns the map scale on the dpi of the screen ''' dpm = dpi / 0.0254 # convert to dots per meter return self.getGroundResolution(latitude, level) * dpm
def convertLatLngToPixelXY(self, lat, lng, level): ''' returns the x and y values of the pixel corresponding to a latitude and longitude. ''' mapSize = self.getMapDimensionsByZoomLevel(level) lat = self.clipValue(lat, self.min_lat, self.max_lat) lng = self.clipValue(lng, self.min_lng, self.max_lng) x = (lng + 180) / 36...
pixelX = int(self.clipValue(x * mapSize + 0.5, 0, mapSize - 1)) pixelY = int(self.clipValue(y * mapSize + 0.5, 0, mapSize - 1)) return (pixelX, pixelY)
def convertPixelXYToLngLat(self, pixelX, pixelY, level): ''' converts a pixel x, y to a latitude and longitude. ''' mapSize = self.getMapDimensionsByZoomLevel(level) x = (self.clipValue(pixelX, 0, mapSize - 1) / mapSize) - 0.5 y = 0.5 - (self.clipValue(pixelY, 0, mapSize - 1) / mapSize) lat = 90 - 360 * math.atan(math....
def tileXYZToQuadKey(self, x, y, z): ''' Computes quadKey value based on tile x, y and z values. ''' quadKey = '' for i in range(z, 0, -1): digit = 0 mask = 1 << (i - 1) if (x & mask) != 0: digit += 1 if (y & mask) != 0: digit += 2 quadKey += str(digit) return quadKey
def quadKeyToTileXYZ(self, quadKey): ''' Computes tile x, y and z values based on quadKey. ''' tileX = 0 tileY = 0 tileZ = len(quadKey) for i in range(tileZ, 0, -1): mask = 1 << (i - 1) value = quadKey[tileZ - i] if value == '0': continue elif value == '1': tileX |= mask elif value == '2': tileY |= mask elif value ==
'3': tileX |= mask tileY |= mask else: raise Exception('Invalid QuadKey') return (tileX, tileY, tileZ)
def getTileOrigin(self, tileX, tileY, level): ''' Returns the upper-left hand corner lat/lng for a tile ''' pixelX, pixelY = self.convertTileXYToPixelXY(tileX, tileY) lng, lat = self.convertPixelXYToLngLat(pixelX, pixelY, level) return (lat, lng)
def getTileUrlsByLatLngExtent(self, xmin, ymin, xmax, ymax, level): ''' Returns a list of tile urls by extent ''' # Upper-Left Tile tileXMin, tileYMin = self.tileUtils.convertLngLatToTileXY(xmin, ymax, level) # Lower-Right Tile tileXMax, tileYMax = self.tileUtils.convertLngLatToTileXY(xmax, ymin, level) tileUrls = [] f...
def createTileUrl(self, x, y, z): ''' returns new tile url based on template ''' return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str( y)).replace('{{z}}', str(z))
def referenceframe(self, event): """Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message """ self.log("Got a reference frame update! ", event, lvl=events) self.reference_frame = event.data
def userlogin(self, event): """Checks if an alert is ongoing and alerts the newly connected client, if so.""" client_uuid = event.clientuuid self.log(event.user, pretty=True, lvl=verbose) self.log('Adding client') self.clients[event.clientuuid] = event.user for topic, alert in self.alerts.items(): self.alert(client_uui...
def trigger(self, event): """AlertManager event handler for incoming events :param event with incoming AlertManager message """ topic = event.data.get('topic', None) if topic is None: self.log('No alert topic to trigger', lvl=warn) return alert = { 'topic': topic, 'message': event.data.get('msg', 'Alert has been trigge...
def cancel(self, event): """AlertManager event handler for incoming events :param event with incoming AlertManager message """ topic = event.data.get('topic', None) if topic is None: self.log('No alert topic to cancel', lvl=warn) return self._cancel(topic)
def cli(ctx, instance, quiet, verbose, log_level, dbhost, dbname): """Isomer Management Tool This tool supports various operations to manage isomer instances. Most of the commands are grouped. To obtain more information about the groups' available sub commands/groups, try iso [group] To display details of a command or ...
try iso cmdmap """ ctx.obj['instance'] = instance if dbname == db_default and instance != 'default': dbname = instance ctx.obj['quiet'] = quiet ctx.obj['verbose'] = verbose verbosity['console'] = log_level verbosity['global'] = log_level ctx.obj['dbhost'] = dbhost ctx.obj['dbname'] = dbname
def main(): """Primary entry point for all AstroCats catalogs. From this entry point, all internal catalogs can be accessed and their public methods executed (for example: import scripts). """ from datetime import datetime # Initialize Command-Line and User-Config Settings, Log # ---------------------------------------...
args, sub_clargs = load_command_line_args() if args is None: return # Create a logging object log = load_log(args) # Run configuration/setup interactive script if args.command == 'setup': setup_user_config(log) return # Make sure configuration file exists, or that's what we're doing # (with the 'setup' subcommand) if n...
"Astrocats, version: {}, SHA: {}".format(__version__, git_vers) log.warning("\n\n{}\n{}\n{}\n".format(title_str, '=' * len(title_str), beg_time.ctime())) # Load the user settings from the home directory args = load_user_config(args, log) # Choose Catalog and Operation(s) to perform # -----------------------------------...
log_raise(log, str(err), type(err)) # Run the `main.main` method of the specified module log.debug("Running `main.main()`") mod.main.main(args, sub_clargs, log) end_time = datetime.now() log.warning("\nAll complete at {}, After {}".format(end_time, end_time - beg_time)) return
def setup_user_config(log): """Setup a configuration file in the user's home directory. Currently this method stores default values to a fixed configuration filename. It should be modified to run an interactive prompt session asking for parameters (or at least confirming the default ones). Arguments --------- log : `lo...
os.path.split(_CONFIG_PATH)[0] if not os.path.exists(config_path_dir): log.debug("Creating config directory '{}'".format(config_path_dir)) os.makedirs(config_path_dir) if not os.path.isdir(config_path_dir): log_raise(log, "Configure path error '{}'".format(config_path_dir)) # Determine default settings # Get this conta...
return
def load_user_config(args, log): """Load settings from the user's confiuration file, and add them to `args`. Settings are loaded from the configuration file in the user's home directory. Those parameters are added (as attributes) to the `args` object. Arguments --------- args : `argparse.Namespace` Namespace object to ...
os.path.exists(_CONFIG_PATH): err_str = ( "Configuration file does not exists ({}).\n".format(_CONFIG_PATH) + "Run `python -m astrocats setup` to configure.") log_raise(log, err_str) config = json.load(open(_CONFIG_PATH, 'r')) setattr(args, _BASE_PATH_KEY, config[_BASE_PATH_KEY]) log.debug("Loaded configuration: {}: {}...
def load_command_line_args(clargs=None): """Load and parse command-line arguments. Arguments --------- args : str or None 'Faked' commandline arguments passed to `argparse`. Returns ------- args : `argparse.Namespace` object Namespace in which settings are stored - default values modified by the given command-line argu...
SHA: {}'.format(__version__, git_vers)) parser.add_argument( '--verbose', '-v', dest='verbose', default=False, action='store_true', help='Print more messages to the screen.') parser.add_argument( '--debug', '-d', dest='debug', default=False, action='store_true', help='Print excessive messages to the screen.') parser.ad...
this depth ' '(default: 0 = all levels).')) parser.add_argument( '--purge-outputs', dest='purge_outputs', default=False, action='store_true', help=('Purge git outputs after cloning.')) parser.add_argument( '--log', dest='log_filename', default=None, help='Filename to which to store logging information.') # If output fi...
# If previously cleared output files should be deleted or not # ----------------------------------------------------------- delete_group = parser.add_mutually_exclusive_group() delete_group.add_argument( '--predelete', action='store_true', dest='delete_old', default=True, help='Delete all old event files to begin [defa...
None return args, sub_clargs
def load_log(args): """Load a `logging.Logger` object. Arguments --------- args : `argparse.Namespace` object Namespace containing required settings: {`args.debug`, `args.verbose`, and `args.log_filename`}. Returns ------- log : `logging.Logger` object """ from astrocats.catalog.utils import logger # Determine verbosit...
args.debug return log
def compare_dicts(old_full, new_full, old_data, new_data, depth=0): """Function compares dictionaries by key-value recursively. Old and new input data are both dictionaries """ depth = depth + 1 indent = " "*depth # Print with an indentation matching the nested-dictionary depth def my_print(str): print("{}{}".format(in...
order doesnt matter for key in old_keys: # Remove elements as we go old_vals = old_data.pop(key) # Current key my_print("{}".format(key)) # If `new_data` doesnt also have this key, return False if key not in new_data: my_print("Key '{}' not in new_data.".format(key)) my_print("Old:") my_print(pprint(new_data)) my_print...
If these values are a sub-dictionary, compare those if isinstance(old_vals, dict) and isinstance(new_vals, dict): # If the sub-dictionary are not the same, return False if not compare_dicts(old_full, new_full, old_vals, new_vals, depth=depth): return False # If these values are a list of sub-dictionaries, compare each ...
# If one or the other has extra elements, print message, but # continue on if old_elem is None or new_elem is None: my_print("Missing element!") my_print("\tOld: '{}'".format(old_elem)) my_print("\tNew: '{}'".format(new_elem)) else: if not compare_dicts(old_full, new_full, old_elem, new_elem, depth=depth): return False...
(not isinstance(old_vals, list) and not isinstance(new_vals, list)): old_vals = [old_vals] new_vals = [new_vals] # Sort both lists old_vals = sorted(old_vals) new_vals = sorted(new_vals) for oldv, newv in zip_longest(old_vals, new_vals): # If one or the other has extra elements, print message, but # continue on if oldv...
oldv == newv: my_print("Good Match: '{}'".format(key)) # If values dont match, return False else: my_print("Bad Match: '{}'".format(key)) my_print("\tOld: '{}'".format(oldv)) my_print("\tNew: '{}'".format(newv)) return False return True
def cohensutherland(xmin, ymax, xmax, ymin, x1, y1, x2, y2): """Clips a line to a rectangular area. This implements the Cohen-Sutherland line clipping algorithm. xmin, ymax, xmax and ymin denote the clipping area, into which the line defined by x1, y1 (start point) and x2, y2 (end point) will be clipped. If the line do...
will be returned as tuple. Otherwise a tuple of the clipped line points will be returned in the form (cx1, cy1, cx2, cy2). """ INSIDE, LEFT, RIGHT, LOWER, UPPER = 0, 1, 2, 4, 8 def _getclip(xa, ya): #if dbglvl>1: print('point: '),; print(xa,ya) p = INSIDE # default is inside # consider x if xa < xmin: p |= LEFT elif xa...
p |= RIGHT # consider y if ya < ymin: p |= LOWER # bitwise OR elif ya > ymax: p |= UPPER # bitwise OR return p # check for trivially outside lines k1 = _getclip(x1, y1) k2 = _getclip(x2, y2) # %% examine non-trivially outside points # bitwise OR | while (k1 | k2) != 0: # if both points are inside
box (0000) , ACCEPT trivial whole line in box # if line trivially outside window, REJECT if (k1 & k2) != 0: # bitwise AND & #if dbglvl>1: print(' REJECT trivially outside box') # return nan, nan, nan, nan return None, None, None, None # non-trivial case, at least one point outside window # this is not a bitwise or, it'...
opt = k1 or k2 # take first non-zero point, short circuit logic if opt & UPPER: # these are bitwise ANDS x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1) y = ymax elif opt & LOWER: x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1) y = ymin elif opt
& RIGHT: y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1) x = xmax elif opt & LEFT: y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1) x = xmin else: raise RuntimeError('Undefined clipping state') if opt == k1: x1, y1 = x, y k1 = _getclip(x1, y1) #if dbglvl>1: print('checking k1:
' + str(x) + ',' + str(y) + ' ' + str(k1)) elif opt == k2: #if dbglvl>1: print('checking k2: ' + str(x) + ',' + str(y) + ' ' + str(k2)) x2, y2 = x, y k2 = _getclip(x2, y2) return x1, y1, x2, y2
def setupuv(rc): """ Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array """ if cv is not None: (r, c) = rc u = cv.CreateMat(r, c, cv.CV_32FC1) v = cv.CreateMat(r, c, cv.CV_32FC1) return (u, v) else: return [None]*2
def _init_cat_dict(self, cat_dict_class, key_in_self, **kwargs): """Initialize a CatDict object, checking for errors. """ # Catch errors associated with crappy, but not unexpected data try: new_entry = cat_dict_class(self, key=key_in_self, **kwargs) except CatDictError as err: if err.warn: self._log.info("'{}' Not addi...
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, **kwargs): """Add a CatDict to this Entry if initialization succeeds and it doesn't already exist within the Entry. """ # Try to create a new instance of this subclass of `CatDict` new_entry = self._init_cat_dict(cat_dict_class, key_in_self, **k...
Error: for item in self.get(key_in_self, []): if new_entry.is_duplicate_of(item): item.append_sources_from(new_entry) # Return the entry in case we want to use any additional # tags to augment the old entry return new_entry self.setdefault(key_in_self, []).append(new_entry) return True
def pbar(iter, desc='', **kwargs): """Wrapper for `tqdm` progress bar. """ return tqdm( iter, desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '> ' + desc), dynamic_ncols=True, **kwargs)