code
stringlengths
1
18.2k
def init(deb1, deb2=False): """Initialize DEBUG and DEBUGALL. Allows other modules to set DEBUG and DEBUGALL, so their call to dprint or dprintx generate output. Args: deb1 (bool): value of DEBUG to set deb2 (bool): optional - value of DEBUGALL to set, defaults to False. """ global DEBUG # pylint: disable=global-statem...
def dprintx(passeditem, special=False): """Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print. """ if DEBUGALL: if special: from pprint import pprint pprint(passeditem) else: print("%s%s%s" % (C_TI, p...
def get(url, **kwargs): """ Wrapper for `request.get` function to set params. """ headers = kwargs.get('headers', {}) headers['User-Agent'] = config.USER_AGENT # overwrite kwargs['headers'] = headers timeout = kwargs.get('timeout', config.TIMEOUT) kwargs['timeout'] = timeout kwargs['verify'] = False # no SSLError logge...
def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT dcap["phantomjs.page.settings.loadImag...
def get_software_package_compilation_timestamp(cls,calc,**kwargs): """ Returns the timestamp of package/program compilation in ISO 8601 format. """ from dateutil.parser import parse try: date = calc.out.job_info.get_dict()['compiled'] return parse(date.replace('_', ' ')).isoformat() except Exception: return None
def get_atom_type_symbol(cls,calc,**kwargs): """ Returns a list of atom types. Each atom site MUST occur only once in this list. List MUST be sorted. """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictionary.keys(): return None return sorted(dictionary['basis_set'].keys())
def get_atom_type_basisset(cls,calc,**kwargs): """ Returns a list of basisset names for each atom type. The list order MUST be the same as of get_atom_type_symbol(). """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictionary.keys(): return None return [dictionary['basis_set'][x...
def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.blobs[cmd.id] = cmd self.keep = False
def commit_handler(self, cmd): """Process a CommitCommand.""" # These pass through if they meet the filtering conditions interesting_filecmds = self._filter_filecommands(cmd.iter_files) if interesting_filecmds or not self.squash_empty_commits: # If all we have is a single deleteall, skip this commit if len(interesting_...
None: self.parents[b':' + cmd.mark] = parents
def reset_handler(self, cmd): """Process a ResetCommand.""" if cmd.from_ is None: # We pass through resets that init a branch because we have to # assume the branch might be interesting. self.keep = True else: # Keep resets if they indirectly reference something we kept cmd.from_ = self._find_interesting_from(cmd.from_...
def tag_handler(self, cmd): """Process a TagCommand.""" # Keep tags if they indirectly reference something we kept cmd.from_ = self._find_interesting_from(cmd.from_) self.keep = cmd.from_ is not None
def _print_command(self, cmd): """Wrapper to avoid adding unnecessary blank lines.""" text = helpers.repr_bytes(cmd) self.outf.write(text) if not text.endswith(b'\n'): self.outf.write(b'\n')
def _filter_filecommands(self, filecmd_iter): """Return the filecommands filtered by includes & excludes. :return: a list of FileCommand objects """ if self.includes is None and self.excludes is None: return list(filecmd_iter()) # Do the filtering, adjusting for the new_root result = [] for fc in filecmd_iter(): if (is...
def _path_to_be_kept(self, path): """Does the given path pass the filtering criteria?""" if self.excludes and (path in self.excludes or helpers.is_inside_any(self.excludes, path)): return False if self.includes: return (path in self.includes or helpers.is_inside_any(self.includes, path)) return True
def _adjust_for_new_root(self, path): """Adjust a path given the new root directory of the output.""" if self.new_root is None: return path elif path.startswith(self.new_root): return path[len(self.new_root):] else: return path
def _convert_rename(self, fc): """Convert a FileRenameCommand into a new FileCommand. :return: None if the rename is being ignored, otherwise a new FileCommand based on the whether the old and new paths are inside or outside of the interesting locations. """ old = fc.old_path new = fc.new_path keep_old = self._path_to_...
# remember all renames and a config file can be passed # into here ala fast-import? self.warning("cannot turn rename of %s into an add of %s yet" % (old, new)) return None
def _convert_copy(self, fc): """Convert a FileCopyCommand into a new FileCommand. :return: None if the copy is being ignored, otherwise a new FileCommand based on the whether the source and destination paths are inside or outside of the interesting locations. """ src = fc.src_path dest = fc.dest_path keep_src = self._p...
copies and a config file can be passed # into here ala fast-import? self.warning("cannot turn copy of %s into an add of %s yet" % (src, dest)) return None
def bundle(context, yes, bundle_name): """Delete the latest bundle version.""" bundle_obj = context.obj['store'].bundle(bundle_name) if bundle_obj is None: click.echo(click.style('bundle not found', fg='red')) context.abort() version_obj = bundle_obj.versions[0] if version_obj.included_at: question = f"remove bundle ve...
def files(context, yes, tag, bundle, before, notondisk): """Delete files based on tags.""" file_objs = [] if not tag and not bundle: click.echo("I'm afraid I can't let you do that.") context.abort() if bundle: bundle_obj = context.obj['store'].bundle(bundle) if bundle_obj is None: click.echo(click.style('bundle not fou...
def file_cmd(context, yes, file_id): """Delete a file.""" file_obj = context.obj['store'].File.get(file_id) if file_obj.is_included: question = f"remove file from file system and database: {file_obj.full_path}" else: question = f"remove file from database: {file_obj.full_path}" if yes or click.confirm(question): if fil...
def sam_readline(sock, partial = None): """read a line from a sam control socket""" response = b'' exception = None while True: try: c = sock.recv(1) if not c: raise EOFError('SAM connection died. Partial response %r %r' % (partial, response)) elif c == b'\n': break else: response += c except (BlockingIOError, pysocket...
def sam_parse_reply(line): """parse a reply line into a dict""" parts = line.split(' ') opts = {k: v for (k, v) in split_kv(parts[2:])} return SAMReply(parts[0], opts)
def sam_send(sock, line_and_data): """Send a line to the SAM controller, but don't read it""" if isinstance(line_and_data, tuple): line, data = line_and_data else: line, data = line_and_data, b'' line = bytes(line, encoding='ascii') + b' \n' # print('-->', line, data) sock.sendall(line + data)
def sam_cmd(sock, line, parse=True): """Send a line to the SAM controller, returning the parsed response""" sam_send(sock, line) reply_line = sam_readline(sock) if parse: return sam_parse_reply(reply_line) else: return reply_line
def handshake(timeout, sam_api, max_version): """handshake with sam via a socket.socket instance""" sock = controller_connect(sam_api, timeout=timeout) response = sam_cmd(sock, greet(max_version)) if response.ok: return sock else: raise HandshakeError("Failed to handshake with SAM: %s" % repr(response))
def lookup(sock, domain, cache = None): """lookup an I2P domain name, returning a Destination instance""" domain = normalize_domain(domain) # cache miss, perform lookup reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain) b64_dest = reply.get('VALUE') if b64_dest: dest = Dest(b64_dest, encoding='base64') if cache: c...
async def create_table(**data): """ RPC method for creating table with custom name and fields :return event id """ table = data.get('table') try: clickhouse_queries.create_table(table, data) return 'Table was successfully created' except ServerException as e: exception_code = int(str(e)[5:8].strip()) if exception_code ...
async def insert(**data): """ RPC method for inserting data to the table :return: None """ table = data.get('table') try: clickhouse_queries.insert_into_table(table, data) return 'Data was successfully inserted into table' except ServerException as e: exception_code = int(str(e)[5:8].strip()) if exception_code == 60: r...
async def select(**data): """ RPC method for selecting data from the database :return selected data """ try: select_data = clickhouse_queries.select_from_table(table=data['table'], query=data['query'], fields=data['fields']) return str(select_data) except ServerException as e: exception_code = int(str(e)[5:8].strip()) ...
async def drop(**data): """ RPC method for deleting table from the database :return None """ table = data['table'] try: clickhouse_queries.drop_table(table) return 'Table was successfully deleted' except ServerException as e: exception_code = int(str(e)[5:8].strip()) if exception_code == 60: return 'Table does not exis...
async def post(self): """ Accepts json-rpc post request. Retrieves data from request body. Calls defined method in field 'method_name' """ request = self.request.body.decode() response = await methods.dispatch(request) if not response.is_notification: self.write(response)
def read_file(filename): """Read a file into a string""" p = path.abspath(path.dirname(__file__)) filepath = path.join(p, filename) try: return open(filepath).read() except IOError: return ''
def get_template_directories(): """This function tries to figure out where template directories are located. It first inspects the TEMPLATES setting, and if that exists and is not empty, uses its values. Otherwise, the values from all of the defined DIRS within TEMPLATES are used. Returns a set of template directories....
def _format_as_url(path): """Make sure ``path`` takes the form of ``/some/url/``.""" path = sub(r"\.html$", '', path) # remove any ending .html # Make sure it starts/ends with a slash. if not path.startswith("/"): path = "/{0}".format(path) if not path.endswith("/"): path = "{0}/".format(path) return path
def urls_from_file_tree(template_dir): """Generates a list of URL strings that would match each staticflatpage.""" urls = [] # keep a list of of all the files/paths # Should be somethign like: # /path/to/myproject/templates/staticflatpages root_dir = join(template_dir, 'staticflatpages') for root, dirs, files in walk(t...
def get_terminal_size(defaultw=80): """ Checks various methods to determine the terminal size Methods: - shutil.get_terminal_size (only Python3) - fcntl.ioctl - subprocess.check_output - os.environ Parameters ---------- defaultw : int Default width of terminal. Returns ------- width, height : int Width and height of th...
def terminal_reserve(progress_obj, terminal_obj=None, identifier=None): """ Registers the terminal (stdout) for printing. Useful to prevent multiple processes from writing progress bars to stdout. One process (server) prints to stdout and a couple of subprocesses do not print to the same stdout, because the server has ...
TERMINAL_RESERVATION[terminal_obj] is progress_obj: log.debug("we %s have already reserved this terminal %s", progress_obj, terminal_obj) return True else: log.debug("someone else %s has already reserved this terminal %s", TERMINAL_RESERVATION[terminal_obj], terminal_obj) return False else: # terminal not yet registere...
def terminal_unreserve(progress_obj, terminal_obj=None, verbose=0, identifier=None): """ Unregisters the terminal (stdout) for printing. an instance (progress_obj) can only unreserve the tty (terminal_obj) when it also reserved it see terminal_reserved for more information Returns ------- None """ if terminal_obj is No...
def compress(self, data_list): """ Return the cleaned_data of the form, everything should already be valid """ data = {} if data_list: return dict( (f.name, data_list[i]) for i, f in enumerate(self.form)) return data
def clean(self, value): """ Call the form is_valid to ensure every value supplied is valid """ if not value: raise ValidationError( 'Error found in Form Field: Nothing to validate') data = dict((bf.name, value[i]) for i, bf in enumerate(self.form)) self.form = form = self.form.__class__(data) if not form.is_valid(): er...
def run(self, params): """Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object. """ self.params = list(reversed(params)) if not self.params: self.help() return while self.params: p = self.params.pop() if p in self.command: # If ...
def read_moc(self, filename): """Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported. """ if self.moc is None: self.moc = MOC(filename=filename) else: self...
def catalog(self): """Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file should contain either "RA" and "Dec" columns (for...
assumed to be commented header, e.g.: :: # RA Dec 01:30:00 +45:00:00 22:30:00 +45:00:00 """ from .catalog import catalog_to_moc, read_ascii_catalog filename = self.params.pop() order = 12 radius = 3600 unit = None format_ = 'commented_header' kwargs = {} while self.params: if self.params[-1] == 'order': self.params.pop...
def help(self): """Display command usage information.""" if self.params: command = self.params.pop().lstrip('-') if command in self.command.documentation: (aliases, doc) = self.command.documentation[command] (synopsis, body) = self._split_docstring(doc) print(synopsis) if body: print() print(body) else: raise CommandEr...
def identifier(self): """Set the identifier of the current MOC. The new identifier should be given after this option. :: pymoctool ... --id 'New MOC identifier' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.id = self.params.pop()
def display_info(self): """Display basic information about the running MOC.""" if self.moc is None: print('No MOC information present') return if self.moc.name is not None: print('Name:', self.moc.name) if self.moc.id is not None: print('Identifier:', self.moc.id) print('Order:', self.moc.order) print('Cells:', self.mo...
def intersection(self): """Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits """ if self.moc is None: raise CommandError('No MOC information present for...
def name(self): """Set the name of the current MOC. The new name should be given after this option. :: pymoctool ... --name 'New MOC name' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.name = self.params.pop()
def normalize(self): """Normalize the MOC to a given order. This command takes a MOC order (0-29) and normalizes the MOC so that its maximum order is the given order. :: pymoctool a.fits --normalize 10 --output a_10.fits """ if self.moc is None: raise CommandError('No MOC information present for normalization') order =...
def write_moc(self): """Write the MOC to a given file.""" if self.moc is None: raise CommandError('No MOC information present for output') filename = self.params.pop() self.moc.write(filename)
def subtract(self): """Subtract the given MOC from the running MOC. This command takes the name of a MOC file to be subtracted from the running MOC. :: pymoctool a.fits --subtract b.fits --output difference.fits """ if self.moc is None: raise CommandError('No MOC information present for subtraction') filename = self.pa...
def plot(self): """Show the running MOC on an all-sky map. This command requires that the Healpy and matplotlib libraries be available. It plots the running MOC, which should be normalized to a lower order first if it would generate an excessively large pixel array. :: pymoctool a.moc --normalize 8 --plot It also accep...
[file <filename>] ... """ if self.moc is None: raise CommandError('No MOC information present for plotting') from .plot import plot_moc order = self.moc.order antialias = 0 filename = None while self.params: if self.params[-1] == 'order': self.params.pop() order = int(self.params.pop()) elif self.params[-1] == 'antiali...
def _split_docstring(self, docstring): """Separate a docstring into the synopsis (first line) and body.""" lines = docstring.strip().splitlines() synopsis = lines[0].strip() body = textwrap.dedent('\n'.join(lines[2:])) # Remove RST preformatted text markers. body = body.replace('\n::\n', '') body = body.replace('::\n',...
def default(self, obj): """This is slightly different than json.JSONEncoder.default(obj) in that it should returned the serialized representation of the passed object, not a serializable representation. """ if isinstance(obj, (datetime.date, datetime.time, datetime.datetime)): return '"%s"' % obj.isoformat() elif isins...
def load_synapses(path=HOME + "/Downloads/pinky100_final.df", scaling=(1, 1, 1)): """ Test scenario using real synapses """ scaling = np.array(list(scaling)) df = pd.read_csv(path) locs = np.array(df[["presyn_x", "centroid_x", "postsyn_x"]]) mask = ~np.any(np.isnan(locs), axis=1) df = df[mask] df['pre_pt.position'] = l...
def include(context, bundle_name, version): """Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version. """ store = Store(context.obj['database'], context.obj['root']) if version: version_obj = store.Version.get(version) if version_obj is None: click.echo(clic...
def ingress_filter(self, response): """ Flatten a response with meta and data keys into an object. """ data = self.data_getter(response) if isinstance(data, dict): data = m_data.DictResponse(data) elif isinstance(data, list): data = m_data.ListResponse(data) else: return data data.meta = self.meta_getter(response) retu...
def get_pager(self, *path, **kwargs): """ A generator for all the results a resource can provide. The pages are lazily loaded. """ page_arg = kwargs.pop('page_size', None) limit_arg = kwargs.pop('limit', None) kwargs['limit'] = page_arg or limit_arg or self.default_page_size return self.adapter.get_pager(self.get, path...
def track_heads(self, cmd): """Track the repository heads given a CommitCommand. :param cmd: the CommitCommand :return: the list of parents in terms of commit-ids """ # Get the true set of parents if cmd.from_ is not None: parents = [cmd.from_] else: last_id = self.last_ids.get(cmd.ref) if last_id is not None: parents ...
def metasay(ctx, inputfile, item): """Moo some dataset metadata to stdout. Python module: rio-metasay (https://github.com/sgillies/rio-plugin-example). """ with rasterio.open(inputfile) as src: meta = src.profile click.echo(moothedata(meta, key=item))
def load_pdb(pdb, path=True, pdb_id='', ignore_end=False): """Converts a PDB file into an AMPAL object. Parameters ---------- pdb : str Either a path to a PDB file or a string containing PDB format structural data. path : bool, optional If `true`, flags `pdb` as a path and not a PDB string. pdb_id : str, optional Ident...
def proc_line_coordinate(self, line): """Extracts data from columns in ATOM/HETATM record.""" at_type = line[0:6].strip() # 0 at_ser = int(line[6:11].strip()) # 1 at_name = line[12:16].strip() # 2 alt_loc = line[16].strip() # 3 res_name = line[17:20].strip() # 4 chain_id = line[21].strip() # 5 res_seq = int(line[22:26]...
def gen_states(self, monomer_data, parent): """Generates the `states` dictionary for a `Monomer`. monomer_data : list A list of atom data parsed from the input PDB. parent : ampal.Monomer `Monomer` used to assign `parent` on created `Atoms`. """ states = {} for atoms in monomer_data: for atom in atoms: state = 'A' if n...
k, v in states[sorted(states_len, key=lambda x: x[0])[0][0]].items(): if k not in t_state_d: c_atom = Atom( v._vector, v.element, atom_id=v.id, res_label=v.res_label, occupancy=v.tags['occupancy'], bfactor=v.tags['bfactor'], charge=v.tags['charge'], state=t_state[0], parent=v.parent) new_s_dict[k] = c_atom else: new_s_...
def check_for_non_canonical(residue): """Checks to see if the residue is non-canonical.""" res_label = list(residue[0])[0][2] atom_labels = {x[2] for x in itertools.chain( *residue[1].values())} # Used to find unnatural aas if (all(x in atom_labels for x in ['N', 'CA', 'C', 'O'])) and ( len(res_label) == 3): return Res...
def get_inst_info(qry_string): """Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict): raw information returned from AWS. ...
def get_all_aminames(i_info): """Get Image_Name for each instance in i_info. Args: i_info (dict): information on instances and details. Returns: i_info (dict): i_info is returned with the aminame added for each instance. """ for i in i_info: try: # pylint: disable=maybe-no-member i_info[i]['aminame'] = EC2R.Image(i_inf...
def get_one_aminame(inst_img_id): """Get Image_Name for the image_id specified. Args: inst_img_id (str): image_id to get name value from. Returns: aminame (str): name of the image. """ try: aminame = EC2R.Image(inst_img_id).name except AttributeError: aminame = "Unknown" return aminame
def startstop(inst_id, cmdtodo): """Start or Stop the Specified Instance. Args: inst_id (str): instance-id to perform command against cmdtodo (str): command to perform (start or stop) Returns: response (dict): reponse returned from AWS after performing specified action. """ tar_inst = EC2R.Instance(inst_id) thecmd = ge...
def addCity(self, fileName): """Add a JSON file and read the users. :param fileName: path to the JSON file. This file has to have a list of users, called users. :type fileName: str. """ with open(fileName) as data_file: data = load(data_file) for u in data["users"]: if not any(d["name"] == u["name"] for d in self.__use...
def export(self, template_file_name, output_file_name, sort="public", data=None, limit=0): """Export ranking to a file. Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with the ranking sort (str): field to sort the users """ exportedData = {} expo...
def __getTemplate(template_file_name): """Get temaplte to save the ranking. :param template_file_name: path to the template. :type template_file_name: str. :return: template for the file. :rtype: pystache's template. """ with open(template_file_name) as template_file: template_raw = template_file.read() template = pars...
def getSortedUsers(self, order="public"): """Return a list with sorted users. :param order: the field to sort the users. - contributions (total number of contributions) - public (public contributions) - private (private contributions) - name - followers - join - organizations - repositories :type order: str. :return: a...
def setup_logging(logging_config, debug=False): """Setup logging config.""" if logging_config is not None: logging.config.fileConfig(logging_config) else: logging.basicConfig(level=debug and logging.DEBUG or logging.ERROR)
def loop(sock, config=None): """Loops over all docker events and executes subscribed callbacks with an optional config value. :param config: a dictionary with external config values """ if config is None: config = {} client = docker.Client(base_url=sock) # fake a running event for all running containers for container i...
def join_configs(configs): """Join all config files into one config.""" joined_config = {} for config in configs: joined_config.update(yaml.load(config)) return joined_config
def load_modules(modules): """Load a module.""" for dotted_module in modules: try: __import__(dotted_module) except ImportError as e: LOG.error("Unable to import %s: %s", dotted_module, e)
def load_files(files): """Load and execute a python file.""" for py_file in files: LOG.debug("exec %s", py_file) execfile(py_file, globals(), locals())
def summarize_events(): """Some information about active events and callbacks.""" for ev in event.events: if ev.callbacks: LOG.info("subscribed to %s by %s", ev, ', '.join(imap(repr, ev.callbacks)))
def cli(sock, configs, modules, files, log, debug): """The CLI.""" setup_logging(log, debug) config = join_configs(configs) # load python modules load_modules(modules) # load python files load_files(files) # summarize active events and callbacks summarize_events() gloop = gevent.Greenlet.spawn(loop, sock=sock, config=c...
def type(self, value): """Set the type of the MOC. The value should be either "IMAGE" or "CATALOG". """ self._type = None if value is None: return value = value.upper() if value in MOC_TYPES: self._type = value else: raise ValueError('MOC type must be one of ' + ', '.join(MOC_TYPES))
def area(self): """The area enclosed by the MOC, in steradians. >>> m = MOC(0, (0, 1, 2)) >>> round(m.area, 2) 3.14 """ self.normalize() area = 0.0 for (order, cells) in self: area += (len(cells) * pi) / (3 * 4 ** order) return area
def cells(self): """The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2 """ n = 0 for (order, cells) in self: n += len(cells) return n
def add(self, order, cells, no_validation=False): """Add cells at a given order to the MOC. The cells are inserted into the MOC at the specified order. This leaves the MOC in an un-normalized state. The cells are given as a collection of integers (or types which can be converted to integers). >>> m = MOC() >>> m.add(4,...
in cells: cell = self._validate_cell(order, cell) cell_set.add(cell) self._orders[order].update(cell_set)
def remove(self, order, cells): """Remove cells at a given order from the MOC. """ self._normalized = False order = self._validate_order(order) for cell in cells: cell = self._validate_cell(order, cell) self._compare_operation(order, cell, True, 'remove')
def clear(self): """Clears all cells from a MOC. >>> m = MOC(4, (5, 6)) >>> m.clear() >>> m.cells 0 """ for order in range(0, MAX_ORDER + 1): self._orders[order].clear() self._normalized = True
def copy(self): """Return a copy of a MOC. >>> p = MOC(4, (5, 6)) >>> q = p.copy() >>> repr(q) '<MOC: [(4, [5, 6])]>' """ copy = MOC(name=self.name, mocid=self.id, origin=self.origin, moctype=self.type) copy += self return copy
def contains(self, order, cell, include_smaller=False): """Test whether the MOC contains the given cell. If the include_smaller argument is true then the MOC is considered to include a cell if it includes part of that cell (at a higher order). >>> m = MOC(1, (5,)) >>> m.contains(0, 0) False >>> m.contains(0, 1, True) T...
def _compare_operation(self, order, cell, include_smaller, operation): """General internal method for comparison-based operations. This is a private method, and does not update the normalized flag. """ # Check for a larger cell (lower order) which contains the # given cell. for order_i in range(0, order): shift = 2 * (...
but only after looking at larger # cells because for the "remove" operation we may have broken up # one of the large cells so that it subsequently matches. if cell in self._orders[order]: if operation == 'check': return True elif operation == 'remove': self._orders[order].remove(cell) elif operation == 'inter': return ...
'inter': if cells: result.append((order_i, cells)) if operation == 'check': return False elif operation == 'inter': return result
def intersection(self, other): """Returns a MOC representing the intersection with another MOC. >>> p = MOC(2, (3, 4, 5)) >>> q = MOC(2, (4, 5, 6)) >>> p.intersection(q) <MOC: [(2, [4, 5])]> """ inter = MOC() for (order, cells) in other: for cell in cells: for i in self._compare_operation(order, cell, True, 'inter'): i...
def normalize(self, max_order=MAX_ORDER): """Ensure that the MOC is "well-formed". This structures the MOC as is required for the FITS and JSON representation. This method is invoked automatically when writing to these formats. The number of cells in the MOC will be minimized, so that no area of the sky is covered mult...