Search is not available for this dataset
text
stringlengths
75
104k
def IOR(type, nr, size): """ An ioctl with read parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size))
def IOW(type, nr, size): """ An ioctl with write parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_WRITE, type, nr, IOC_TYPECHECK(size))
def IOWR(type, nr, size): """ An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size))
def _get_last_dirs(path, num=1): """Get a path including only the trailing `num` directories. Returns ------- last_path : str """ head, tail = os.path.split(path) last_path = str(tail) for ii in range(num): head, tail = os.path.split(head) last_path = os.path.join(tail,...
def analyze(self, args): """Run the analysis routines determined from the given `args`. """ self.log.info("Running catalog analysis") if args.count: self.count() return
def count(self): """Analyze the counts of ...things. Returns ------- retvals : dict Dictionary of 'property-name: counts' pairs for further processing """ self.log.info("Running 'count'") retvals = {} # Numbers of 'tasks' num_tasks =...
def _count_tasks(self): """Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in the `tasks.json` file. """ self.log.warning("Tasks:") tasks, task_names = self.catalog._lo...
def _count_repo_files(self): """Count the number of files in the data repositories. `_COUNT_FILE_TYPES` are used to determine which file types are checked explicitly. `_IGNORE_FILES` determine which files are ignored in (most) counts. Returns ------- repo_files ...
def _file_nums_str(self, n_all, n_type, n_ign): """Construct a string showing the number of different file types. Returns ------- f_str : str """ # 'other' is the difference between all and named n_oth = n_all - np.sum(n_type) f_str = "{} Files".format(n...
def _count_files_by_type(self, path, pattern, ignore=True): """Count files in the given path, with the given pattern. If `ignore = True`, skip files in the `_IGNORE_FILES` list. Returns ------- num_files : int """ # Get all files matching the given path and pat...
def bibcode_from_url(cls, url): """Given a URL, try to find the ADS bibcode. Currently: only `ads` URLs will work, e.g. Returns ------- code : str or 'None' The Bibcode if found, otherwise 'None' """ try: code = url.split('/abs/') ...
def _get_save_path(self, bury=False): """Return the path that this Entry should be saved to.""" filename = self.get_filename(self[self._KEYS.NAME]) # Put objects that shouldn't belong in this catalog in the boneyard if bury: outdir = self.catalog.get_repo_boneyard() ...
def _ordered(self, odict): """Convert the object into a plain OrderedDict.""" ndict = OrderedDict() if isinstance(odict, CatDict) or isinstance(odict, Entry): key = odict.sort_func else: key = None nkeys = list(sorted(odict.keys(), key=key)) for ...
def get_hash(self, keys=[]): """Return a unique hash associated with the listed keys.""" if not len(keys): keys = list(self.keys()) string_rep = '' oself = self._ordered(deepcopy(self)) for key in keys: string_rep += json.dumps(oself.get(key, ''), sort_ke...
def _clean_quantity(self, quantity): """Clean quantity value before it is added to entry.""" value = quantity.get(QUANTITY.VALUE, '').strip() error = quantity.get(QUANTITY.E_VALUE, '').strip() unit = quantity.get(QUANTITY.U_VALUE, '').strip() kind = quantity.get(QUANTITY.KIND, ''...
def _convert_odict_to_classes(self, data, clean=False, merge=True, pop_schema=True, compare_to_existing=True, filter...
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs): """Check that a source exists and that a quantity isn't erroneous.""" # Make sure that a source is given source = kwargs.get(cat_dict_class._KEYS.SOURCE, None) if source is None: raise CatDictError( ...
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add a `CatDict` to this `Entry`. CatDict only added if initialization succeeds...
def init_from_file(cls, catalog, name=None, path=None, clean=False, merge=True, pop_schema=True, ignore_keys=[], compare_to_existing=Tru...
def add_alias(self, alias, source, clean=True): """Add an alias, optionally 'cleaning' the alias string. Calls the parent `catalog` method `clean_entry_name` - to apply the same name-cleaning as is applied to entry names themselves. Returns ------- alias : str ...
def add_error(self, value, **kwargs): """Add an `Error` instance to this entry.""" kwargs.update({ERROR.VALUE: value}) self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs) return
def add_photometry(self, compare_to_existing=True, **kwargs): """Add a `Photometry` instance to this entry.""" self._add_cat_dict( Photometry, self._KEYS.PHOTOMETRY, compare_to_existing=compare_to_existing, **kwargs) return
def merge_dupes(self): """Merge two entries that correspond to the same entry.""" for dupe in self.dupe_of: if dupe in self.catalog.entries: if self.catalog.entries[dupe]._stub: # merge = False to avoid infinite recursion self.catalog.l...
def add_quantity(self, quantities, value, source, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add an `Quantity` instance to this entry.""" success = True ...
def add_self_source(self): """Add a source that refers to the catalog itself. For now this points to the Open Supernova Catalog by default. """ return self.add_source( bibcode=self.catalog.OSC_BIBCODE, name=self.catalog.OSC_NAME, url=self.catalog.OSC_...
def add_source(self, allow_alias=False, **kwargs): """Add a `Source` instance to this entry.""" if not allow_alias and SOURCE.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) rais...
def add_model(self, allow_alias=False, **kwargs): """Add a `Model` instance to this entry.""" if not allow_alias and MODEL.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) raise R...
def add_spectrum(self, compare_to_existing=True, **kwargs): """Add a `Spectrum` instance to this entry.""" spec_key = self._KEYS.SPECTRA # Make sure that a source is given, and is valid (nor erroneous) source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs) if source i...
def check(self): """Check that the entry has the required fields.""" # Make sure there is a schema key in dict if self._KEYS.SCHEMA not in self: self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL # Make sure there is a name key in dict if (self._KEYS.NAME not in self o...
def get_aliases(self, includename=True): """Retrieve the aliases of this object as a list of strings. Arguments --------- includename : bool Include the 'name' parameter in the list of aliases. """ # empty list if doesnt exist alias_quanta = self.get(...
def get_entry_text(self, fname): """Retrieve the raw text from a file.""" if fname.split('.')[-1] == 'gz': with gz.open(fname, 'rt') as f: filetext = f.read() else: with codecs.open(fname, 'r') as f: filetext = f.read() return filet...
def get_source_by_alias(self, alias): """Given an alias, find the corresponding source in this entry. If the given alias doesn't exist (e.g. there are no sources), then a `ValueError` is raised. Arguments --------- alias : str The str-integer (e.g. '8') of t...
def get_stub(self): """Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_st...
def is_erroneous(self, field, sources): """Check if attribute has been marked as being erroneous.""" if self._KEYS.ERRORS in self: my_errors = self[self._KEYS.ERRORS] for alias in sources.split(','): source = self.get_source_by_alias(alias) bib_err...
def is_private(self, key, sources): """Check if attribute is private.""" # aliases are always public. if key == ENTRY.ALIAS: return False return all([ SOURCE.PRIVATE in self.get_source_by_alias(x) for x in sources.split(',') ])
def sanitize(self): """Sanitize the data (sort it, etc.) before writing it to disk. Template method that can be overridden in each catalog's subclassed `Entry` object. """ name = self[self._KEYS.NAME] aliases = self.get_aliases(includename=False) if name not in ...
def save(self, bury=False, final=False): """Write entry to JSON file in the proper location. Arguments --------- bury : bool final : bool If this is the 'final' save, perform additional sanitization and cleaning operations. """ outdir, f...
def sort_func(self, key): """Used to sort keys when writing Entry to JSON format. Should be supplemented/overridden by inheriting classes. """ if key == self._KEYS.SCHEMA: return 'aaa' if key == self._KEYS.NAME: return 'aab' if key == self._KEYS.S...
def set_pd_mag_from_counts(photodict, c='', ec='', lec='', uec='', zp=DEFAULT_ZP, sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a counts measur...
def set_pd_mag_from_flux_density(photodict, fd='', efd='', lefd='', uefd='', sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a flux density me...
def _check(self): """Check that entry attributes are legal.""" # Run the super method super(Photometry, self)._check() err_str = None has_flux = self._KEYS.FLUX in self has_flux_dens = self._KEYS.FLUX_DENSITY in self has_u_flux = self._KEYS.U_FLUX in self ...
def sort_func(self, key): """Specify order for attributes.""" if key == self._KEYS.TIME: return 'aaa' if key == self._KEYS.MODEL: return 'zzy' if key == self._KEYS.SOURCE: return 'zzz' return key
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine(get_url()) connection = engine.connect() context.configure( connection=connection, target_m...
def by_resource_user_and_perm( cls, user_id, perm_name, resource_id, db_session=None ): """ return all instances by user name, perm name and resource id :param user_id: :param perm_name: :param resource_id: :param db_session: :return: """ ...
def tdSensor(self): """Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. """ protocol = create_string_buffer(20) model = create_string_buffer(20) sid = c_int() datatypes = c_int() self._lib.tdSensor(proto...
def tdSensorValue(self, protocol, model, sid, datatype): """Get the sensor value for a given sensor. :return: a dict with the keys: value, timestamp. """ value = create_string_buffer(20) timestamp = c_int() self._lib.tdSensorValue(protocol, model, sid, datatype, ...
def tdController(self): """Get the next controller while iterating. :return: a dict with the keys: id, type, name, available. """ cid = c_int() ctype = c_int() name = create_string_buffer(255) available = c_int() self._lib.tdController(byref(cid), byref(...
def make_passwordmanager(schemes=None): """ schemes contains a list of replace this list with the hash(es) you wish to support. this example sets pbkdf2_sha256 as the default, with support for legacy bcrypt hashes. :param schemes: :return: CryptContext() """ from passlib.context imp...
def ziggurat_model_init( user=None, group=None, user_group=None, group_permission=None, user_permission=None, user_resource_permission=None, group_resource_permission=None, resource=None, external_identity=None, *args, **kwargs ): """ This function handles attaching m...
def messages(request, year=None, month=None, day=None, template="gnotty/messages.html"): """ Show messages for the given query or day. """ query = request.REQUEST.get("q") prev_url, next_url = None, None messages = IRCMessage.objects.all() if hide_joins_and_leaves(request): ...
def calendar(request, year=None, month=None, template="gnotty/calendar.html"): """ Show calendar months for the given year/month. """ try: year = int(year) except TypeError: year = datetime.now().year lookup = {"message_time__year": year} if month: lookup["message_ti...
def decorate_client(api_client, func, name): """A helper for decorating :class:`bravado.client.SwaggerClient`. :class:`bravado.client.SwaggerClient` can be extended by creating a class which wraps all calls to it. This helper is used in a :func:`__getattr__` to check if the attr exists on the api_client...
def delete_expired_locks(self): """ Deletes all expired mutex locks if a ttl is provided. """ ttl_seconds = self.get_mutex_ttl_seconds() if ttl_seconds is not None: DBMutex.objects.filter(creation_time__lte=timezone.now() - timedelta(seconds=ttl_seconds)).delete()
def start(self): """ Acquires the db mutex lock. Takes the necessary steps to delete any stale locks. Throws a DBMutexError if it can't acquire the lock. """ # Delete any expired locks first self.delete_expired_locks() try: with transaction.atomic(): ...
def stop(self): """ Releases the db mutex lock. Throws an error if the lock was released before the function finished. """ if not DBMutex.objects.filter(id=self.lock.id).exists(): raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id)) ...
def decorate_callable(self, func): """ Decorates a function with the db_mutex decorator by using this class as a context manager around it. """ def wrapper(*args, **kwargs): try: with self: result = func(*args, **kwargs) ...
def groupfinder(userid, request): """ Default groupfinder implementaion for pyramid applications :param userid: :param request: :return: """ if userid and hasattr(request, "user") and request.user: groups = ["group:%s" % g.id for g in request.user.groups] return groups r...
def force_atlas2_layout(graph, pos_list=None, node_masses=None, iterations=100, outbound_attraction_distribution=False, lin_log_mode=False, prevent_overlapping=False, ...
def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=None, barnes_hut_theta=1.2): """ Iterate through the nodes or edges and apply the forces directly to the node objects. """ if not barnes_hut_optimize: for i in range(0, len(nodes)): for j in range(0, i): ...
def apply_gravity(repulsion, nodes, gravity, scaling_ratio): """ Iterate through the nodes or edges and apply the gravity directly to the node objects. """ for i in range(0, len(nodes)): repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio)
def get(cls, external_id, local_user_id, provider_name, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param external_id: :param local_user_id: :param provider_name: :param db_session: :return: ...
def by_external_id_and_provider(cls, external_id, provider_name, db_session=None): """ Returns ExternalIdentity instance based on search params :param external_id: :param provider_name: :param db_session: :return: ExternalIdentity """ db_session = get_db_...
def user_by_external_id_and_provider( cls, external_id, provider_name, db_session=None ): """ Returns User instance based on search params :param external_id: :param provider_name: :param db_session: :return: User """ db_session = get_db_sessi...
def by_user_and_perm(cls, user_id, perm_name, db_session=None): """ return by user and permission name :param user_id: :param perm_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).fi...
def node_is_subclass(cls, *subclass_names): """Checks if cls node has parent with subclass_name.""" if not isinstance(cls, (ClassDef, Instance)): return False # if cls.bases == YES: # return False for base_cls in cls.bases: try: for inf in base_cls.inferred(): # pra...
def is_field_method(node): """Checks if a call to a field instance method is valid. A call is valid if the call is a method of the underlying type. So, in a StringField the methods from str are valid, in a ListField the methods from list are valid and so on...""" name = node.attrname parent = no...
def get_node_parent_class(node): """Supposes that node is a mongoengine field in a class and tries to get its parent class""" while node.parent: # pragma no branch if isinstance(node, ClassDef): return node node = node.parent
def get_field_definition(node): """"node is a class attribute that is a mongoengine. Returns the definition statement for the attribute """ name = node.attrname cls = get_node_parent_class(node) definition = cls.lookup(name)[1][0].statement() return definition
def get_field_embedded_doc(node): """Returns de ClassDef for the related embedded document in a embedded document field.""" definition = get_field_definition(node) cls_name = definition.last_child().last_child() cls = next(cls_name.infer()) return cls
def node_is_embedded_doc_attr(node): """Checks if a node is a valid field or method in a embedded document. """ embedded_doc = get_field_embedded_doc(node.last_child()) name = node.attrname try: r = bool(embedded_doc.lookup(name)[1][0]) except IndexError: r = False return r
def _dispatcher(self, connection, event): """ This is the method in ``SimpleIRCClient`` that all IRC events get passed through. Here we map events to our own custom event handlers, and call them. """ super(BaseBot, self)._dispatcher(connection, event) for handler ...
def message_channel(self, message): """ We won't receive our own messages, so log them manually. """ self.log(None, message) super(BaseBot, self).message_channel(message)
def on_pubmsg(self, connection, event): """ Log any public messages, and also handle the command event. """ for message in event.arguments(): self.log(event, message) command_args = filter(None, message.split()) command_name = command_args.pop(0) ...
def handle_command_event(self, event, command, args): """ Command handler - treats each word in the message that triggered the command as an argument to the command, and does some validation to ensure that the number of arguments match. """ argspec = getargspec(co...
def handle_timer_event(self, handler): """ Runs each timer handler in a separate greenlet thread. """ while True: handler(self) sleep(handler.event.args["seconds"])
def handle_webhook_event(self, environ, url, params): """ Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response. ...
def DeviceFactory(id, lib=None): """Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) re...
def process_callback(self, block=True): """Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False. """ try: (callback, args) = self._queue.get(...
def devices(self): """Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. """ devices = [] count = self.lib.tdGetNumberOfDevices() for i in range(count): device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)...
def sensors(self): """Return all known sensors. :return: list of :class:`Sensor` instances. """ sensors = [] try: while True: sensor = self.lib.tdSensor() sensors.append(Sensor(lib=self.lib, **sensor)) except TelldusError as e:...
def controllers(self): """Return all known controllers. Requires Telldus core library version >= 2.1.2. :return: list of :class:`Controller` instances. """ controllers = [] try: while True: controller = self.lib.tdController() ...
def add_device(self, name, protocol, model=None, **parameters): """Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ device = Device(self.lib.tdAddDevice(), lib=self.lib) try: device.name = name device.protocol = protocol ...
def add_group(self, name, devices): """Add a new device group. :return: a :class:`DeviceGroup` instance. """ device = self.add_device(name, "group") device.add_to_group(devices) return device
def connect_controller(self, vid, pid, serial): """Connect a controller.""" self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial): """Disconnect a controller.""" self.lib.tdDisconnectTellStickController(vid, pid, serial)
def parameters(self): """Get dict with all set parameters.""" parameters = {} for name in self.PARAMETERS: try: parameters[name] = self.get_parameter(name) except AttributeError: pass return parameters
def get_parameter(self, name): """Get a parameter.""" default_value = "$%!)(INVALID)(!%$" value = self.lib.tdGetDeviceParameter(self.id, name, default_value) if value == default_value: raise AttributeError(name) return value
def set_parameter(self, name, value): """Set a parameter.""" self.lib.tdSetDeviceParameter(self.id, name, str(value))
def add_to_group(self, devices): """Add device(s) to the group.""" ids = {d.id for d in self.devices_in_group()} ids.update(self._device_ids(devices)) self._set_group(ids)
def remove_from_group(self, devices): """Remove device(s) from the group.""" ids = {d.id for d in self.devices_in_group()} ids.difference_update(self._device_ids(devices)) self._set_group(ids)
def devices_in_group(self): """Fetch list of devices in group.""" try: devices = self.get_parameter('devices') except AttributeError: return [] ctor = DeviceFactory return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
def value(self, datatype): """Return the :class:`SensorValue` for the given data type. sensor.value(TELLSTICK_TEMPERATURE) is identical to calling sensor.temperature(). """ value = self.lib.tdSensorValue( self.protocol, self.model, self.id, datatype) return S...
def _prepPointsForSegments(points): """ Move any off curves at the end of the contour to the beginning of the contour. This makes segmentation easier. """ while 1: point = points[-1] if point.segmentType: break else: point = points.pop() ...
def _reversePoints(points): """ Reverse the points. This differs from the reversal point pen in RoboFab in that it doesn't worry about maintaing the start point position. That has no benefit within the context of this module. """ # copy the points points = _copyPoints(points) # find ...
def _convertPointsToSegments(points, willBeReversed=False): """ Compile points into InputSegment objects. """ # get the last on curve previousOnCurve = None for point in reversed(points): if point.segmentType is not None: previousOnCurve = point.coordinates break ...
def _tValueForPointOnCubicCurve(point, cubicCurve, isHorizontal=0): """ Finds a t value on a curve from a point. The points must be originaly be a point on the curve. This will only back trace the t value, needed to split the curve in parts """ pt1, pt2, pt3, pt4 = cubicCurve a, b, c, d = be...
def _scalePoints(points, scale=1, convertToInteger=True): """ Scale points and optionally convert them to integers. """ if convertToInteger: points = [ (int(round(x * scale)), int(round(y * scale))) for (x, y) in points ] else: points = [(x * scale, y ...
def _scaleSinglePoint(point, scale=1, convertToInteger=True): """ Scale a single point """ x, y = point if convertToInteger: return int(round(x * scale)), int(round(y * scale)) else: return (x * scale, y * scale)
def _flattenSegment(segment, approximateSegmentLength=_approximateSegmentLength): """ Flatten the curve segment int a list of points. The first and last points in the segment must be on curves. The returned list of points will not include the first on curve point. false curves (where the off cur...