_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52200
Document.load
train
def load(cls, database, doc_id): """Load a specific document from the given database. :param database: the `Database` object to retrieve the document from :param doc_id: the document ID :return: the `Document` instance, or `None` if no document with the given ID was fou...
python
{ "resource": "" }
q52201
Document.store
train
def store(self, database, validate=True, role=None): """Store the document in the given database. :param database: the `Database` object source for storing the document. :return: an updated instance of `Document` / self. """ if validate: self.validate() self....
python
{ "resource": "" }
q52202
Document.hydrate
train
def hydrate(self, database, recursive=True): """ By default, recursively reloads all instances of Document in the model. Recursion can be turned off. :param database: the `Database` object source for rehydrating. :return: an updated instance of `Document` / self. """ ...
python
{ "resource": "" }
q52203
Document.query
train
def query(cls, database, map_fun, reduce_fun, language='javascript', **options): """Execute a CouchDB temporary view and map the result values back to objects of this mapping. Note that by default, any properties of the document that are not included in the values of the v...
python
{ "resource": "" }
q52204
Document.view
train
def view(cls, database, viewname, **options): """Execute a CouchDB named view and map the result values back to objects of this mapping. Note that by default, any properties of the document that are not included in the values of the view will be treated as if they were missing f...
python
{ "resource": "" }
q52205
Document._wrap_row
train
def _wrap_row(cls, row): """Wrap ViewField or ViewDefinition Rows.""" doc = row.get('doc') if doc is not None: return cls.wrap(doc) data = row['value'] data['_id'] = row['id'] return cls.wrap(data)
python
{ "resource": "" }
q52206
BaseTransformer._only_shifts
train
def _only_shifts(self, modifiers): """Check if modifiers pressed are only shifts""" if not modifiers or len(modifiers) > 2: return False if len(modifiers) == 2: return 'left shift' in modifiers and 'right shift' in modifiers if len(modifiers) == 1: ret...
python
{ "resource": "" }
q52207
SpanishTransformer.transform
train
def transform(self, keys): """Apply Spanish layout to the pressed keys""" key = keys['regular'][0] modifiers = keys['modifiers'] try: if not modifiers: if key in self._letters or key in self._digits: res = key elif key in s...
python
{ "resource": "" }
q52208
Keymap.get_keymap
train
def get_keymap(self): """Returns X11 Keymap as a list of integers""" self._x11.XQueryKeymap(self._display, self._raw_keymap) try: keyboard = [ord(byte) for byte in self._raw_keymap] except TypeError: return None return keyboard
python
{ "resource": "" }
q52209
Keymap.get_keys
train
def get_keys(self, keymap): """Extract keys pressed from transformed keymap""" keys = dict(modifiers=[], regular=[]) # loop on keymap bytes for keymap_index, keymap_byte in enumerate(keymap): try: keymap_values = self._keymap_values_dict[keymap_index] ...
python
{ "resource": "" }
q52210
T.close
train
def close(self): """This method closes the canvas and writes contents to the associated file. Calling this procedure is optional, because Pychart calls this procedure for every open canvas on normal exit.""" for i in range(0, len(active_canvases)): if active_canvases[...
python
{ "resource": "" }
q52211
T._path_polygon
train
def _path_polygon(self, points): "Low-level polygon-drawing routine." (xmin, ymin, xmax, ymax) = _compute_bounding_box(points) if invisible_p(xmax, ymax): return self.setbb(xmin, ymin) self.setbb(xmax, ymax) self.newpath() self.moveto(xscale(points[0]...
python
{ "resource": "" }
q52212
T.endclip
train
def endclip(self): """End the current clip region. When clip calls are nested, it ends the most recently created crip region.""" self.__clip_box = self.__clip_stack[-1] del self.__clip_stack[-1] self.grestore()
python
{ "resource": "" }
q52213
ListServiceMixin.list
train
def list(self, **filters): """ Returns a queryset filtering object by user permission. If you want, you can specify filter arguments. See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details """ LOG.debug(u'Querying %s by filters=%s', self.model_cl...
python
{ "resource": "" }
q52214
ListServiceMixin.get
train
def get(self, pk=None, **filters): """ Retrieve an object instance. If a single argument is supplied, object is queried by primary key, else filter queries will be applyed. If more than one object was found raise MultipleObjectsReturned. If no object found, raise DoesNotExist. Ra...
python
{ "resource": "" }
q52215
magic_contract
train
def magic_contract(*args, **kwargs): """Drop-in replacement for ``pycontracts.contract`` decorator, except that it supports locally-visible types :param args: Arguments to pass to the ``contract`` decorator :param kwargs: Keyword arguments to pass to the ``contract`` decorator :return: The contracted f...
python
{ "resource": "" }
q52216
HL7Dict.toString
train
def toString(self): """ Return a printable view of the dictionary """ result = [] k, v = self.optimalRepr() longest = reduce(lambda x, y: x if x > len(y) else len(y), k, 0) for ind in range(len(k)): result.append("%s : %s" % (k[ind].ljust(longest),...
python
{ "resource": "" }
q52217
name
train
def name(value): """Get the string title for a particular type. Given a value, get an appropriate string title for the type that can be used to re-cast the value later. """ if value is None: return 'any' for (test, name) in TESTS: if isinstance(value, test): return n...
python
{ "resource": "" }
q52218
MetaEnum.get
train
def get(cls, key): """ str, int or Enum => Enum """ if isinstance(key, Enum) and not isinstance(key, cls): raise TypeError("Cannot type cast between enums") if isinstance(key, int): if not int(key) in cls._values: raise KeyError("There is n...
python
{ "resource": "" }
q52219
_compose_func
train
def _compose_func(func, args_func=lambda req_info: [req_info.index]): """ Compose function used to compose arguments to function. Arguments for the functions are composed from the :class:`.RequestInfo` object from the ZODB. """ return FuncInfo(func=func, args_func=args_func)
python
{ "resource": "" }
q52220
Model.get_mapping
train
def get_mapping(self): # TODO: rename to _as_dict """ Convert the class to dict. Returns: dict: Copy of ``self.__dict__``. """ return { key: val for key, val in self.__dict__.iteritems() if val }
python
{ "resource": "" }
q52221
timed_call
train
def timed_call(func, *args, log_level='DEBUG', **kwargs): """Logs a function's run time :param func: The function to run :param args: The args to pass to the function :param kwargs: The keyword args to pass to the function :param log_level: The log level at which to print the run time :return: ...
python
{ "resource": "" }
q52222
tic
train
def tic(log_level='DEBUG', fmt="{file}:{line} - {message} - {diff:0.6f}s (total={total:0.1f}s)", verbose=True): """A minimalistic ``printf``-type timing utility. Call this function to start timing individual sections of code :param log_level: The level at which to log block run times :param fmt: The format...
python
{ "resource": "" }
q52223
source_set
train
def source_set(method_name): """ Creates a setter that will call the source method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the source. @type method_name: str """ def source_set(value, context, **_para...
python
{ "resource": "" }
q52224
source_attr
train
def source_attr(attr_name): """ Creates a setter that will set the specified source attribute to the current value. @param attr_name: the name of an attribute belonging to the source. @type attr_name: str """ def source_attr(value, context, **_params): setattr(context["model"].sourc...
python
{ "resource": "" }
q52225
source_setattr
train
def source_setattr(): """ Creates a setter that will set the source attribute with context's key for name to the current value. """ def source_setattr(value, context, **_params): setattr(context["model"].source, context["key"], value) return _attr() return source_setattr
python
{ "resource": "" }
q52226
model_set
train
def model_set(method_name): """ Creates a setter that will call the model method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the model. @type method_name: str """ def model_set(value, context, **_params):...
python
{ "resource": "" }
q52227
model_attr
train
def model_attr(attr_name): """ Creates a setter that will set the specified model attribute to the current value. @param attr_name: the name of an attribute belonging to the model. @type attr_name: str """ def model_attr(value, context, **_params): setattr(context["model"], attr_nam...
python
{ "resource": "" }
q52228
model_setattr
train
def model_setattr(): """ Creates a setter that will set the model attribute with context's key for name to the current value. """ def model_setattr(value, context, **_params): setattr(context["model"], context["key"], value) return _attr() return model_setattr
python
{ "resource": "" }
q52229
action_set
train
def action_set(method_name): """ Creates a setter that will call the action method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the action. @type method_name: str """ def action_set(value, context, **_para...
python
{ "resource": "" }
q52230
action_attr
train
def action_attr(attr_name): """ Creates a setter that will set the specified action attribute to the current value. @param attr_name: the name of an attribute belonging to the action. @type attr_name: str """ def action_attr(value, context, **_params): setattr(context["action"], att...
python
{ "resource": "" }
q52231
action_setattr
train
def action_setattr(): """ Creates a setter that will set the action attribute with context's key for name to the current value. """ def action_setattr(value, context, **_params): setattr(context["action"], context["key"], value) return _attr() return action_setattr
python
{ "resource": "" }
q52232
view_set
train
def view_set(method_name): """ Creates a setter that will call the view method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the view. @type method_name: str """ def view_set(value, context, **_params): ...
python
{ "resource": "" }
q52233
view_attr
train
def view_attr(attr_name): """ Creates a setter that will set the specified view attribute to the current value. @param attr_name: the name of an attribute belonging to the view. @type attr_name: str """ def view_attr(value, context, **_params): setattr(context["view"], attr_name, va...
python
{ "resource": "" }
q52234
view_setattr
train
def view_setattr(): """ Creates a setter that will set the view attribute with context's key for name to the current value. """ def view_setattr(value, context, **_params): setattr(context["view"], context["key"], value) return _attr() return view_setattr
python
{ "resource": "" }
q52235
Table.cells
train
def cells(self): """A dictionary of dictionaries containing all cells. """ return {row_key: {column_key:cell for column_key, cell in zip(self._column_keys, cells)} for row_key, cells in self._rows_mapping.items()}
python
{ "resource": "" }
q52236
InitDetectorNetwork
train
def InitDetectorNetwork(numDets, detNetwork, LIGO3FLAG=0): """ InitDetectorNetwork - function to initialise desired detector network specified as input. numDets - Number of IFOs in the detector network to be considered, can take any value in the range [1,5]. detNetwork - 5 character string...
python
{ "resource": "" }
q52237
GetDetectorPSD
train
def GetDetectorPSD(detectorName, LIGO3FLAG=0): """ GetDetectorPSD - function to return the PSD of the detector described by detectorName. detectorName - Name of required GW IFO. Can be 'H1', 'L1', 'V1', 'I1', or 'K1'. LIGO3FLAG - Set to 1 to use LIGO3 PSD instead of aLIGO PSD for H1, L1 ...
python
{ "resource": "" }
q52238
GenerateGaussianNoise
train
def GenerateGaussianNoise(PSD): """ GenerateGaussianNoise - function to generate Fourier domain Gaussian detector noise colored by a detector PSD. PSD - Noise power spectral density with which to color the Gaussian noise. Returns Noise - complex Fourier domain Gaussian det...
python
{ "resource": "" }
q52239
ComputeLightTravelTime
train
def ComputeLightTravelTime(Det1Pos, Det2Pos): """ ComputeLightTravelTime - function to compute light travel time between two GW detectors at positions Det1Pos and Det2Pos. Det1Pos - (3,) array. Position vector of detector 1. Det2Pos - (3,) array. Position vector of detector 2. Returns travelTime - Light trave...
python
{ "resource": "" }
q52240
ConvertRADecToThetaPhi
train
def ConvertRADecToThetaPhi(RA, Dec, GPSTime): """ ConvertRADecToThetaPhi - function to convert right ascension and declination of an astronomical source to theta and phi in the geocentric coordinate system. RA - Right ascension of source. Dec - Declination of source...
python
{ "resource": "" }
q52241
ComputeGMST
train
def ComputeGMST(GPSTime): """ ComputeGMST - function to compute the Greenwich mean sidereal time from the GPS time. GPSTime - GPS time that the GW signal from the source reached the geocenter. Returns GMST - the Greenwich mean sidereal time corresponding to ...
python
{ "resource": "" }
q52242
LikelihoodFunction
train
def LikelihoodFunction(Template, Data, PSD, detRespP, detGCDelay=0): """ LikelihoodFunction - function to calculate the likelihood of livePoint, given Data. Template - (N_fd) complex array containing Fourier domain trial signal. Data - (N_fd) complex array containing Fourier domain GW data....
python
{ "resource": "" }
q52243
lazy_import
train
def lazy_import(module_name, to_import): """Return the importing module and a callable for lazy importing. The module named by module_name represents the module performing the import to help facilitate resolving relative imports. to_import is an iterable of the modules to be potentially imported (abso...
python
{ "resource": "" }
q52244
filtered_attrs
train
def filtered_attrs(module, *, modules=False, private=False, dunder=False, common=False): """Return a collection of attributes on 'module'. If 'modules' is false then module instances are excluded. If 'private' is false then attributes starting with, but not ending in, '_' will be exc...
python
{ "resource": "" }
q52245
Key.get_type
train
def get_type(self): """ Get the type name of key """ for typechar, typename in self.KEY_TYPE_CHOICES: if typechar == self.key_type: return typename
python
{ "resource": "" }
q52246
Key.is_suitable
train
def is_suitable(self, request): """ Checks if key is suitable for given request according to key type and request's user agent. """ if self.key_type: validation = KEY_TYPE_VALIDATIONS.get( self.get_type() ) return validation( request ) if validation else None ...
python
{ "resource": "" }
q52247
Key.extend_expiration_date
train
def extend_expiration_date(self, days=KEY_EXPIRATION_DELTA): """ Extend expiration date a number of given years """ delta = timedelta_days(days) self.expiration_date = self.expiration_date + delta self.save()
python
{ "resource": "" }
q52248
Key.refresh_token
train
def refresh_token(self, pattern=KEY_PATTERN): """ Replace token with a new generated one """ self.token = generate_token(pattern) self.save()
python
{ "resource": "" }
q52249
Key.add_consumer
train
def add_consumer(self, ip): """ Add consumer based on its ip address """ Consumer.objects.get_or_create(key=self, ip=ip)
python
{ "resource": "" }
q52250
Key.has_perm
train
def has_perm(self, perm): """ Checks if key has the given django's auth Permission """ if '.' in perm: app_label, codename = perm.split('.') permissions = self.permissions.filter( content_type__app_label = app_label, codename = cod...
python
{ "resource": "" }
q52251
StorageQueueModel.getmessage
train
def getmessage(self) -> str: """ parse self into unicode string as message content """ image = {} for key, default in vars(self.__class__).items(): if not key.startswith('_') and key !='' and (not key in vars(QueueMessage).items()): ...
python
{ "resource": "" }
q52252
StorageQueueModel.mergemessage
train
def mergemessage(self, message): """ parse OueueMessage in Model vars """ if isinstance(message, QueueMessage): """ merge queue message vars """ for key, value in vars(message).items(): if not value is None: setattr(self, key, value) ...
python
{ "resource": "" }
q52253
StorageQueueContext.put
train
def put(self, storagemodel:object, modeldefinition = None) -> StorageQueueModel: """ insert queue message into storage """ try: message = modeldefinition['queueservice'].put_message(storagemodel._queuename, storagemodel.getmessage()) storagemodel.mergemessage(message) ex...
python
{ "resource": "" }
q52254
StorageQueueContext.peek
train
def peek(self, storagemodel:object, modeldefinition = None) -> StorageQueueModel: """ lookup the next message in queue """ try: messages = modeldefinition['queueservice'].peek_messages(storagemodel._queuename, num_messages=1) """ parse retrieved message """ for mess...
python
{ "resource": "" }
q52255
StorageQueueContext.get
train
def get(self, storagemodel:object, modeldefinition = None, hide = 0) -> StorageQueueModel: """ get the next message in queue """ try: if hide > 0: messages = modeldefinition['queueservice'].get_messages(storagemodel._queuename, num_messages=1, visibility_timeout = hide) ...
python
{ "resource": "" }
q52256
StorageQueueContext.update
train
def update(self, storagemodel:object, modeldefinition = None, hide = 0) -> StorageQueueModel: """ update the message in queue """ if (storagemodel.id != '') and (storagemodel.pop_receipt != '') and (not storagemodel.id is None) and (not storagemodel.pop_receipt is None): try: ...
python
{ "resource": "" }
q52257
StorageQueueContext.delete
train
def delete(self, storagemodel:object, modeldefinition = None) -> bool: """ delete the message in queue """ deleted = False if (storagemodel.id != '') and (storagemodel.pop_receipt != '') and (not storagemodel.id is None) and (not storagemodel.pop_receipt is None): try: ...
python
{ "resource": "" }
q52258
DjangoServicesAdmin.has_add_permission
train
def has_add_permission(self, request): """ Returns True if the given request has permission to add an object. Can be overriden by the user in subclasses. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
python
{ "resource": "" }
q52259
should_exclude
train
def should_exclude(type_or_instance, exclusion_list): """ Tests whether an object should be simply returned when being wrapped """ if type_or_instance in exclusion_list: # Check class definition return True if type(type_or_instance) in exclusion_list: # Check instance type return Tr...
python
{ "resource": "" }
q52260
Facade
train
def Facade( some_instance=None, exclusion_list=[], cls=None, args=tuple(), kwargs={} ): """ Top-level interface to the Facade functionality. Determines what to return when passed arbitrary objects. :param mixed some_instance: Anything. :param list exclusion_list: The list of types NOT to wrap :par...
python
{ "resource": "" }
q52261
patch
train
def patch(*args, **kwargs): """ Deprecated. Patch should now be imported from caliendo.patch.patch """ from caliendo.patch import patch as p return p(*args, **kwargs)
python
{ "resource": "" }
q52262
Wrapper.wrapper__ignore
train
def wrapper__ignore(self, type_): """ Selectively ignore certain types when wrapping attributes. :param class type: The class/type definition to ignore. :rtype list(type): The current list of ignored types """ if type_ not in self.__exclusion_list: self.__ex...
python
{ "resource": "" }
q52263
Wrapper.wrapper__unignore
train
def wrapper__unignore(self, type_): """ Stop selectively ignoring certain types when wrapping attributes. :param class type: The class/type definition to stop ignoring. :rtype list(type): The current list of ignored types """ if type_ in self.__exclusion_list: ...
python
{ "resource": "" }
q52264
Wrapper.__wrap
train
def __wrap( self, method_name ): """ This method actually does the wrapping. When it's given a method to copy it returns that method with facilities to log the call so it can be repeated. :param str method_name: The name of the method precisely as it's called on the object to wr...
python
{ "resource": "" }
q52265
Wrapper.__store_other
train
def __store_other(self, o, method_name, member): """ Stores a reference to an attribute on o :param mixed o: Some object :param str method_name: The name of the attribute :param mixed member: The attribute """ self.__store__[ method_name ] = eval( "o." + method_...
python
{ "resource": "" }
q52266
Wrapper.__save_reference
train
def __save_reference(self, o, cls, args, kwargs): """ Saves a reference to the original object Facade is passed. This will either be the object itself or a LazyBones instance for lazy-loading later :param mixed o: The original object :param class cls: The class definition for th...
python
{ "resource": "" }
q52267
Wrapper.__store_any
train
def __store_any(self, o, method_name, member): """ Determines type of member and stores it accordingly :param mixed o: Any parent object :param str method_name: The name of the method or attribuet :param mixed member: Any child object """ if should_exclude( eval...
python
{ "resource": "" }
q52268
_import_symbol
train
def _import_symbol(import_path, setting_name): """ Import a class or function by name. """ mod_name, class_name = import_path.rsplit('.', 1) # import module try: mod = import_module(mod_name) cls = getattr(mod, class_name) except ImportError as e: __, __, exc_traceba...
python
{ "resource": "" }
q52269
construct
train
def construct(args): '''Construct a queue-name from a set of arguments and a delimiter''' # make everything unicode name = u'' delimiter, encodeseq = delimiter_encodeseq(_c.FSQ_DELIMITER, _c.FSQ_ENCODE, _c.FSQ_CHARSET) if len(args) == 0: return ...
python
{ "resource": "" }
q52270
deconstruct
train
def deconstruct(name): '''Deconstruct a queue-name to a set of arguments''' name = coerce_unicode(name, _c.FSQ_CHARSET) new_arg = sep = u'' args = [] # can't get delimiter, if string is empty if 1 > len(name): raise FSQMalformedEntryError(errno.EINVAL, u'cannot derive delimiter'\ ...
python
{ "resource": "" }
q52271
SceneMember.delete
train
async def delete(self): """Deletes a scene from a shade""" _val = await self.request.delete( self._base_path, params={ ATTR_SCENE_ID: self._raw_data.get(ATTR_SCENE_ID), ATTR_SHADE_ID: self._raw_data.get(ATTR_SHADE_ID), }, ) ...
python
{ "resource": "" }
q52272
drop_param
train
def drop_param(_param, _method, *args, **kwargs): """ Used as a callback to ignore the result from the previous callback added to this fiber. """ assert callable(_method), "method %r is not callable" % (_method, ) return _method(*args, **kwargs)
python
{ "resource": "" }
q52273
bridge_param
train
def bridge_param(_param, _method, *args, **kwargs): """ Used as a callback to keep the result from the previous callback and use that instead of the result of the given callback when chaining to the next callback in the fiber. """ assert callable(_method), "method %r is not callable" % (_method,...
python
{ "resource": "" }
q52274
woven
train
def woven(fun): '''Decorator that will initialize and eventually start nested fibers.''' def wrapper(*args, **kwargs): section = WovenSection() section.enter() result = fun(*args, **kwargs) return section.exit(result) return wrapper
python
{ "resource": "" }
q52275
get_stack_var
train
def get_stack_var(name, depth=0): '''This function may fiddle with the locals of the calling function, to make it the root function of the fiber. If called from a short-lived function be sure to use a bigger frame depth. Returns the fiber state or None.''' base_frame = _get_base_frame(depth) if...
python
{ "resource": "" }
q52276
tabulate
train
def tabulate( obj, v_level_indexes=None, h_level_indexes=None, v_level_visibility=None, h_level_visibility=None, v_level_sort_keys=None, h_level_sort_keys=None, v_level_titles=None, h_level_titles=None, empty="", ): """Render a nested data structure into a two-dimensional tab...
python
{ "resource": "" }
q52277
validate_level_indexes
train
def validate_level_indexes(num_levels, v_level_indexes, h_level_indexes): """Ensure that v_level_indexes and h_level_indexes are consistent. Args: num_levels: The number of levels of keys in the data structure being tabulated. v_level_indexes: A sequence of level indexes between zero and num_le...
python
{ "resource": "" }
q52278
strip_hidden
train
def strip_hidden(key_tuples, visibilities): """Filter each tuple according to visibility. Args: key_tuples: A sequence of tuples of equal length (i.e. rectangular) visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples. Returns: A sequence equal ...
python
{ "resource": "" }
q52279
readme
train
def readme(): """Try converting the README to an RST document. Return it as is on failure.""" try: import pypandoc readme_content = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): print("Warning: no pypandoc module found.") try: readme_content =...
python
{ "resource": "" }
q52280
T.x_tic_points
train
def x_tic_points(self, interval): "Return the list of X values for which tick marks and grid lines are drawn." if type(interval) == FunctionType: return interval(*self.x_range) return self.x_coord.get_tics(self.x_range[0], self.x_range[1], interval)
python
{ "resource": "" }
q52281
T.y_tic_points
train
def y_tic_points(self, interval): "Return the list of Y values for which tick marks and grid lines are drawn." if type(interval) == FunctionType: return interval(*self.y_range) return self.y_coord.get_tics(self.y_range[0], self.y_range[1], interval)
python
{ "resource": "" }
q52282
T.draw
train
def draw(self, can=None): "Draw the charts." if can == None: can = canvas.default_canvas() assert self.check_integrity() for plot in self.__plots: plot.check_integrity() self.x_range, self.x_grid_interval = \ self.__get_data_range(self.x_ra...
python
{ "resource": "" }
q52283
_sanitizeFilename
train
def _sanitizeFilename(filename): """Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.""" global _sanitize_trans out = filename.translate(_sanitize_trans) # leading dot becomes "_" if out and out[0] == '.': ou...
python
{ "resource": "" }
q52284
DPTreeWidget._checkDragDropEvent
train
def _checkDragDropEvent(self, ev): """Checks if event contains a file URL, accepts if it does, ignores if it doesn't""" mimedata = ev.mimeData() if mimedata.hasUrls(): urls = [str(url.toLocalFile()) for url in mimedata.urls() if url.toLocalFile()] else: urls = [] ...
python
{ "resource": "" }
q52285
DPTreeWidget.dropEvent
train
def dropEvent(self, ev): """Process drop event.""" # use function above to accept event if it contains a file URL files = self._checkDragDropEvent(ev) if files: pos = ev.pos() dropitem = self.itemAt(pos) dprint(1, "dropped on", pos.x(), pos.y(), dropit...
python
{ "resource": "" }
q52286
DPTreeWidget._itemComboBox
train
def _itemComboBox(self, item, column): """This returns the QComboBox associated with item and column, or creates a new one if it hasn't been created yet. The reason we don't create a combobox immediately is because the item needs to be inserted into its QTreeWidget first.""" if item.tree...
python
{ "resource": "" }
q52287
DPTreeWidget.setItemPolicy
train
def setItemPolicy(self, item, policy): """Sets the policy of the given item""" index = item._combobox_indices[self.ColAction].get(policy, 0) self._updateItemComboBoxIndex(item, self.ColAction, index) combobox = self.itemWidget(item, self.ColAction) if combobox: combob...
python
{ "resource": "" }
q52288
DPTreeWidget.getItemDPList
train
def getItemDPList(self): """Returns list of item,dp pairs corresponding to content of listview. Not-yet-saved items will have dp=None.""" itemlist = [(item, item._dp) for item in self.iterator()] return itemlist
python
{ "resource": "" }
q52289
DPTreeWidget.focusOutEvent
train
def focusOutEvent(self, ev): """Redefine focusOut events to stop editing""" Kittens.widgets.ClickableTreeWidget.focusOutEvent(self, ev) # if focus is going to a child of ours, do nothing wid = QApplication.focusWidget() while wid: if wid is self: retur...
python
{ "resource": "" }
q52290
DPTreeWidget.keyPressEvent
train
def keyPressEvent(self, ev): """Stop editing if enter is pressed""" if ev.key() in (Qt.Key_Enter, Qt.Key_Return): self._startOrStopEditing() elif ev.key() == Qt.Key_Escape: self._cancelEditing() else: Kittens.widgets.ClickableTreeWidget.keyPressEvent(s...
python
{ "resource": "" }
q52291
DPTreeWidget.fillDataProducts
train
def fillDataProducts(self, dps): """Fills listview with existing data products""" item = None for dp in dps: if not dp.ignored: item = self._makeDPItem(self, dp, item) # ensure combobox widgets are made self._itemComboBox(item, self.Col...
python
{ "resource": "" }
q52292
DPTreeWidget.resolveFilenameConflicts
train
def resolveFilenameConflicts(self): """Goes through list of DPs to make sure that their destination names do not clash. Adjust names as needed. Returns True if some conflicts were resolved. """ taken_names = set() resolved = False # iterate through items for item,...
python
{ "resource": "" }
q52293
DPTreeWidget.buildDPList
train
def buildDPList(self): """Builds list of data products.""" updated = False dps = [] itemlist = self.getItemDPList() # first remove all items marked for removal, in case their names clash with new or renamed items for item, dp in itemlist: item._policy = item._...
python
{ "resource": "" }
q52294
LogEntryEditor.suggestTitle
train
def suggestTitle(self, title): """Suggests a title for the entry. If title has been manually edited, suggestion is ignored.""" if not self._title_changed or not str(self.wtitle.text()): self.wtitle.setText(title) self._title_changed = False
python
{ "resource": "" }
q52295
LogEntryEditor.countRemovedDataProducts
train
def countRemovedDataProducts(self): """Returns number of DPs marked for removal""" return len([item for item, dp in self.wdplv.getItemDPList() if dp.policy == "remove"])
python
{ "resource": "" }
q52296
LogEntryEditor.updateIgnoredEntry
train
def updateIgnoredEntry(self): """Updates an ignore-entry object with current content of dialog, by marking all data products for ignore.""" # collect new DPs from items dps = [] for item, dp in self.wdplv.getItemDPList(): if dp and not dp.archived: # None means a new...
python
{ "resource": "" }
q52297
LogEntryEditor.setEntry
train
def setEntry(self, entry=None): """Populates the dialog with contents of an existing entry.""" busy = Purr.BusyIndicator() self.entry = entry self.setEntryTitle(entry.title) self.setEntryComment(entry.comment.replace("\n", "\n\n").replace("<BR>", "\n")) self.wdplv.clear()...
python
{ "resource": "" }
q52298
vizarray
train
def vizarray(x, cmap=None, scale=None, vmin=None, vmax=None, block_size=None): """Visualize a NumPy array using ipythonblocks.""" if not (x.ndim == 2 or x.ndim == 1): raise TypeError('This function only works with 1 or 2 dimensional arrays') global _cmap, _scale, _vmin, _vmax, _block_size cmap =...
python
{ "resource": "" }
q52299
enable_notebook
train
def enable_notebook(): """Enable automatic visualization of NumPy arrays in the IPython Notebook.""" try: from IPython.core.getipython import get_ipython except ImportError: raise ImportError('This feature requires IPython 1.0+') ip = get_ipython() f = ip.display_formatter.formatters...
python
{ "resource": "" }