_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q237500
extract_conf_from
train
def extract_conf_from(mod, conf=ModuleConfig(CONF_SPEC), depth=0, max_depth=2): """recursively extract keys from module or object by passed config scheme """ # extract config keys from module or object for key, default_value in six.iteritems(conf): conf[key] = _get_key_from_module(mod, key,...
python
{ "resource": "" }
q237501
_get_correct_module
train
def _get_correct_module(mod): """returns imported module check if is ``leonardo_module_conf`` specified and then import them """ module_location = getattr( mod, 'leonardo_module_conf', getattr(mod, "LEONARDO_MODULE_CONF", None)) if module_location: mod = import_module(module...
python
{ "resource": "" }
q237502
get_conf_from_module
train
def get_conf_from_module(mod): """return configuration from module with defaults no worry about None type """ conf = ModuleConfig(CONF_SPEC) # get imported module mod = _get_correct_module(mod) conf.set_module(mod) # extarct from default object or from module if hasattr(mod, 'defaul...
python
{ "resource": "" }
q237503
get_anonymous_request
train
def get_anonymous_request(leonardo_page): """returns inicialized request """ request_factory = RequestFactory() request = request_factory.get( leonardo_page.get_absolute_url(), data={}) request.feincms_page = request.leonardo_page = leonardo_page request.frontend_editing = False req...
python
{ "resource": "" }
q237504
webfont_cookie
train
def webfont_cookie(request): '''Adds WEBFONT Flag to the context''' if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None): return { WEBFONT_COOKIE_NAME.upper(): True } return { WEBFONT_COOKIE_NAME.upper(): False }
python
{ "resource": "" }
q237505
get_all_widget_classes
train
def get_all_widget_classes(): """returns collected Leonardo Widgets if not declared in settings is used __subclasses__ which not supports widget subclassing """ from leonardo.module.web.models import Widget _widgets = getattr(settings, 'WIDGETS', Widget.__subclasses__())...
python
{ "resource": "" }
q237506
render_region
train
def render_region(widget=None, request=None, view=None, page=None, region=None): """returns rendered content this is not too clear and little tricky, because external apps needs calling process method """ # change the request if not isinstance(request, dict): request.q...
python
{ "resource": "" }
q237507
PageAdmin.get_feincms_inlines
train
def get_feincms_inlines(self, model, request): """ Generate genuine django inlines for registered content types. """ model._needs_content_types() inlines = [] for content_type in model._feincms_content_types: if not self.can_add_content(request, content_type): ...
python
{ "resource": "" }
q237508
PageAdmin.get_changeform_initial_data
train
def get_changeform_initial_data(self, request): '''Copy initial data from parent''' initial = super(PageAdmin, self).get_changeform_initial_data(request) if ('translation_of' in request.GET): original = self.model._tree_manager.get( pk=request.GET.get('translation_of'...
python
{ "resource": "" }
q237509
install_package
train
def install_package(package, upgrade=True, target=None): """Install a package on PyPi. Accepts pip compatible package strings. Return boolean if install successful. """ # Not using 'import pip; pip.main([])' because it breaks the logger with INSTALL_LOCK: if check_packag...
python
{ "resource": "" }
q237510
check_package_exists
train
def check_package_exists(package, lib_dir): """Check if a package is installed globally or in lib_dir. Returns True when the requirement is met. Returns False when the package is not installed or doesn't meet req. """ try: req = pkg_resources.Requirement.parse(package) except ValueError...
python
{ "resource": "" }
q237511
AJAXMixin.render_widget
train
def render_widget(self, request, widget_id): '''Returns rendered widget in JSON response''' widget = get_widget_from_id(widget_id) response = widget.render(**{'request': request}) return JsonResponse({'result': response, 'id': widget_id})
python
{ "resource": "" }
q237512
AJAXMixin.render_region
train
def render_region(self, request): '''Returns rendered region in JSON response''' page = self.get_object() try: region = request.POST['region'] except KeyError: region = request.GET['region'] request.query_string = None from leonardo.utils.widge...
python
{ "resource": "" }
q237513
AJAXMixin.handle_ajax_method
train
def handle_ajax_method(self, request, method): """handle ajax methods and return serialized reponse in the default state allows only authentificated users - Depends on method parameter render whole region or single widget - If widget_id is present then try to load this widget ...
python
{ "resource": "" }
q237514
add_bootstrap_class
train
def add_bootstrap_class(field): """Add a "form-control" CSS class to the field's widget. This is so that Bootstrap styles it properly. """ if not isinstance(field.field.widget, ( django.forms.widgets.CheckboxInput, django.forms.widgets.CheckboxSelectMultiple, django.forms.widget...
python
{ "resource": "" }
q237515
ClipboardAdmin.ajax_upload
train
def ajax_upload(self, request, folder_id=None): """ receives an upload from the uploader. Receives only one file at the time. """ mimetype = "application/json" if request.is_ajax() else "text/html" content_type_key = 'content_type' response_params = {content_type_key: mim...
python
{ "resource": "" }
q237516
Command.set_options
train
def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = False self.verbosity = options['verbosity'] self.symlink = "" self.clear = False ignore_patterns = [] self.ignore_patterns = list(set(ignor...
python
{ "resource": "" }
q237517
Command.collect
train
def collect(self): """ Load and save ``PageColorScheme`` for every ``PageTheme`` .. code-block:: bash static/themes/bootswatch/united/variables.scss static/themes/bootswatch/united/styles.scss """ self.ignore_patterns = [ '*.png', '*.jpg', ...
python
{ "resource": "" }
q237518
BaseImage.has_generic_permission
train
def has_generic_permission(self, request, permission_type): """ Return true if the current user has permission on this image. Return the string 'ALL' if the user has all rights. """ user = request.user if not user.is_authenticated(): return False elif ...
python
{ "resource": "" }
q237519
MediaGalleryWidget.get_template_data
train
def get_template_data(self, request, *args, **kwargs): '''Add image dimensions''' # little tricky with vertical centering dimension = int(self.get_size().split('x')[0]) data = {} if dimension <= 356: data['image_dimension'] = "row-md-13" if self.get_templa...
python
{ "resource": "" }
q237520
_decorate_urlconf
train
def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs): '''Decorate all urlpatterns by specified decorator''' if isinstance(urlpatterns, (list, tuple)): for pattern in urlpatterns: if getattr(pattern, 'callback', None): pattern._callback = decorator( ...
python
{ "resource": "" }
q237521
catch_result
train
def catch_result(task_func): """Catch printed result from Celery Task and return it in task response """ @functools.wraps(task_func, assigned=available_attrs(task_func)) def dec(*args, **kwargs): # inicialize orig_stdout = sys.stdout sys.stdout = content = StringIO() tas...
python
{ "resource": "" }
q237522
compress_monkey_patch
train
def compress_monkey_patch(): """patch all compress we need access to variables from widget scss for example we have:: /themes/bootswatch/cyborg/_variables but only if is cyborg active for this reasone we need dynamically append import to every scss file """ from compressor.templ...
python
{ "resource": "" }
q237523
output
train
def output(self, mode='file', forced=False, context=None): """ The general output method, override in subclass if you need to do any custom modification. Calls other mode specific methods or simply returns the content directly. """ output = '\n'.join(self.filter_input(forced, context=context)) ...
python
{ "resource": "" }
q237524
precompile
train
def precompile(self, content, kind=None, elem=None, filename=None, charset=None, **kwargs): """ Processes file using a pre compiler. This is the place where files like coffee script are processed. """ if not kind: return False, content attrs = self.parser.elem_attribs(elem...
python
{ "resource": "" }
q237525
MACAddr.decode
train
def decode(self,data): """Decode the MAC address from a byte array. This will take the first 6 bytes from data and transform them into a MAC address string representation. This will be assigned to the attribute "val". It then returns the data stream minus the bytes consumed ...
python
{ "resource": "" }
q237526
thumbnail
train
def thumbnail(parser, token): ''' This template tag supports both syntax for declare thumbanil in template ''' thumb = None if SORL: try: thumb = sorl_thumb(parser, token) except Exception: thumb = False if EASY and not thumb: thumb = easy_thumb...
python
{ "resource": "" }
q237527
handle_uploaded_file
train
def handle_uploaded_file(file, folder=None, is_public=True): '''handle uploaded file to folder match first media type and create media object and returns it file: File object folder: str or Folder isinstance is_public: boolean ''' _folder = None if folder and isinstance(folder, Folder)...
python
{ "resource": "" }
q237528
handle_uploaded_files
train
def handle_uploaded_files(files, folder=None, is_public=True): '''handle uploaded files to folder files: array of File objects or single object folder: str or Folder isinstance is_public: boolean ''' results = [] for f in files: result = handle_uploaded_file(f, folder, is_public) ...
python
{ "resource": "" }
q237529
serve_protected_file
train
def serve_protected_file(request, path): """ Serve protected files to authenticated users with read permissions. """ path = path.rstrip('/') try: file_obj = File.objects.get(file=path) except File.DoesNotExist: raise Http404('File not found %s' % path) if not file_obj.has_rea...
python
{ "resource": "" }
q237530
serve_protected_thumbnail
train
def serve_protected_thumbnail(request, path): """ Serve protected thumbnails to authenticated users. If the user doesn't have read permissions, redirect to a static image. """ source_path = thumbnail_to_original_filename(path) if not source_path: raise Http404('File not found') try: ...
python
{ "resource": "" }
q237531
Leonardo.get_app_modules
train
def get_app_modules(self, apps): """return array of imported leonardo modules for apps """ modules = getattr(self, "_modules", []) if not modules: from django.utils.module_loading import module_has_submodule # Try importing a modules from the module package ...
python
{ "resource": "" }
q237532
Leonardo.urlpatterns
train
def urlpatterns(self): '''load and decorate urls from all modules then store it as cached property for less loading ''' if not hasattr(self, '_urlspatterns'): urlpatterns = [] # load all urls # support .urls file and urls_conf = 'elephantblog.urls' on ...
python
{ "resource": "" }
q237533
cycle_app_reverse_cache
train
def cycle_app_reverse_cache(*args, **kwargs): """Does not really empty the cache; instead it adds a random element to the cache key generation which guarantees that the cache does not yet contain values for all newly generated keys""" value = '%07x' % (SystemRandom().randint(0, 0x10000000)) cache.se...
python
{ "resource": "" }
q237534
reverse
train
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): """monkey patched reverse path supports easy patching 3rd party urls if 3rd party app has namespace for example ``catalogue`` and you create FeinCMS plugin with same name as this namespace reverse returns url from Applic...
python
{ "resource": "" }
q237535
add_page_if_missing
train
def add_page_if_missing(request): """ Returns ``feincms_page`` for request. """ try: page = Page.objects.for_request(request, best_match=True) return { 'leonardo_page': page, # DEPRECATED 'feincms_page': page, } except Page.DoesNotExist: ...
python
{ "resource": "" }
q237536
render_in_page
train
def render_in_page(request, template): """return rendered template in standalone mode or ``False`` """ from leonardo.module.web.models import Page page = request.leonardo_page if hasattr( request, 'leonardo_page') else Page.objects.filter(parent=None).first() if page: try: ...
python
{ "resource": "" }
q237537
page_not_found
train
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ response = render_in_page(request, template_name) if response: ...
python
{ "resource": "" }
q237538
bad_request
train
def bad_request(request, template_name='400.html'): """ 400 error handler. Templates: :template:`400.html` Context: None """ response = render_in_page(request, template_name) if response: return response try: template = loader.get_template(template_name) except Te...
python
{ "resource": "" }
q237539
HorizonMiddleware.process_response
train
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] i...
python
{ "resource": "" }
q237540
HorizonMiddleware.process_exception
train
def process_exception(self, request, exception): """Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated))...
python
{ "resource": "" }
q237541
canonical
train
def canonical(request, uploaded_at, file_id): """ Redirect to the current url of a public file """ filer_file = get_object_or_404(File, pk=file_id, is_public=True) if (uploaded_at != filer_file.uploaded_at.strftime('%s') or not filer_file.file): raise Http404('No %s matches the g...
python
{ "resource": "" }
q237542
check_message
train
def check_message(keywords, message): """Checks an exception for given keywords and raises a new ``ActionError`` with the desired message if the keywords are found. This allows selective control over API error messages. """ exc_type, exc_value, exc_traceback = sys.exc_info() if set(str(exc_value...
python
{ "resource": "" }
q237543
SwitchableFormFieldMixin.get_switched_form_field_attrs
train
def get_switched_form_field_attrs(self, prefix, input_type, name): """Creates attribute dicts for the switchable theme form """ attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'} attributes['data-' + prefix + 'field-' + input_type] = name return attributes
python
{ "resource": "" }
q237544
PageCreateForm.clean_slug
train
def clean_slug(self): """slug title if is not provided """ slug = self.cleaned_data.get('slug', None) if slug is None or len(slug) == 0 and 'title' in self.cleaned_data: slug = slugify(self.cleaned_data['title']) return slug
python
{ "resource": "" }
q237545
get_widget_from_id
train
def get_widget_from_id(id): """returns widget object by id example web-htmltextwidget-2-2 """ res = id.split('-') try: model_cls = apps.get_model(res[0], res[1]) obj = model_cls.objects.get(parent=res[2], id=res[3]) except: obj = None return obj
python
{ "resource": "" }
q237546
get_widget_class_from_id
train
def get_widget_class_from_id(id): """returns widget class by id example web-htmltextwidget-2-2 """ res = id.split('-') try: model_cls = apps.get_model(res[1], res[2]) except: model_cls = None return model_cls
python
{ "resource": "" }
q237547
frontendediting_request_processor
train
def frontendediting_request_processor(page, request): """ Sets the frontend editing state in the cookie depending on the ``frontend_editing`` GET parameter and the user's permissions. """ if 'frontend_editing' not in request.GET: return response = HttpResponseRedirect(request.path) ...
python
{ "resource": "" }
q237548
Default.extra_context
train
def extra_context(self): """Add site_name to context """ from django.conf import settings return { "site_name": (lambda r: settings.LEONARDO_SITE_NAME if getattr(settings, 'LEONARDO_SITE_NAME', '') != '' else settings.SITE_...
python
{ "resource": "" }
q237549
ModuleConfig.get_property
train
def get_property(self, key): """Expect Django Conf property""" _key = DJANGO_CONF[key] return getattr(self, _key, CONF_SPEC[_key])
python
{ "resource": "" }
q237550
ModuleConfig.needs_sync
train
def needs_sync(self): """Indicates whater module needs templates, static etc.""" affected_attributes = [ 'css_files', 'js_files', 'scss_files', 'widgets'] for attr in affected_attributes: if len(getattr(self, attr)) > 0: return True r...
python
{ "resource": "" }
q237551
LeonardoConfig.get_attr
train
def get_attr(self, name, default=None, fail_silently=True): """try extra context """ try: return getattr(self, name) except KeyError: extra_context = getattr(self, "extra_context") if name in extra_context: value = extra_context[name] ...
python
{ "resource": "" }
q237552
find_all_templates
train
def find_all_templates(pattern='*.html', ignore_private=True): """ Finds all Django templates matching given glob in all TEMPLATE_LOADERS :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_ to match .. important:: At the moment egg loader is not supported. ...
python
{ "resource": "" }
q237553
flatten_template_loaders
train
def flatten_template_loaders(templates): """ Given a collection of template loaders, unwrap them into one flat iterable. :param templates: template loaders to unwrap :return: template loaders as an iterable of strings. :rtype: generator expression """ for loader in templates: if not...
python
{ "resource": "" }
q237554
SeekableFileProxy.seek
train
def seek(self, offset, whence=os.SEEK_SET): """Sets the file's current position. :param offset: the offset to set :type offset: :class:`numbers.Integral` :param whence: see the docs of :meth:`file.seek()`. default is :const:`os.SEEK_SET` """ self....
python
{ "resource": "" }
q237555
Store.put_file
train
def put_file(self, file, object_type, object_id, width, height, mimetype, reproducible): """Puts the ``file`` of the image. :param file: the image file to put :type file: file-like object, :class:`file` :param object_type: the object type of the image to put ...
python
{ "resource": "" }
q237556
Store.delete
train
def delete(self, image): """Delete the file of the given ``image``. :param image: the image to delete :type image: :class:`sqlalchemy_imageattach.entity.Image` """ from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sq...
python
{ "resource": "" }
q237557
Store.locate
train
def locate(self, image): """Gets the URL of the given ``image``. :param image: the image to get its url :type image: :class:`sqlalchemy_imageattach.entity.Image` :returns: the url of the image :rtype: :class:`str` """ from .entity import Image if not isi...
python
{ "resource": "" }
q237558
Image.identity_attributes
train
def identity_attributes(cls): """A list of the names of primary key fields. :returns: A list of the names of primary key fields :rtype: :class:`typing.Sequence`\ [:class:`str`] .. versionadded:: 1.0.0 """ columns = inspect(cls).primary_key names = [c.name for c...
python
{ "resource": "" }
q237559
Image.make_blob
train
def make_blob(self, store=current_store): """Gets the byte string of the image from the ``store``. :param store: the storage which contains the image. :data:`~sqlalchemy_imageattach.context.current_store` by default :type store: :class:`~sqlalchemy_im...
python
{ "resource": "" }
q237560
Image.locate
train
def locate(self, store=current_store): """Gets the URL of the image from the ``store``. :param store: the storage which contains the image. :data:`~sqlalchemy_imageattach.context.current_store` by default :type store: :class:`~sqlalchemy_imageattach.s...
python
{ "resource": "" }
q237561
BaseImageQuery._original_images
train
def _original_images(self, **kwargs): """A list of the original images. :returns: A list of the original images. :rtype: :class:`typing.Sequence`\ [:class:`Image`] """ def test(image): if not image.original: return False for filter, value...
python
{ "resource": "" }
q237562
BaseImageSet.from_file
train
def from_file(self, file, store=current_store, extra_args=None, extra_kwargs=None): """Stores the ``file`` for the image into the ``store``. :param file: the readable file of the image :type file: file-like object, :class:`file` :param store: the storage to store the f...
python
{ "resource": "" }
q237563
World.clear_database
train
def clear_database(self) -> None: """Remove all Entities and Components from the World.""" self._next_entity_id = 0 self._dead_entities.clear() self._components.clear() self._entities.clear() self.clear_cache()
python
{ "resource": "" }
q237564
World.add_processor
train
def add_processor(self, processor_instance: Processor, priority=0) -> None: """Add a Processor instance to the World. :param processor_instance: An instance of a Processor, subclassed from the Processor class :param priority: A higher number is processed first. """ asser...
python
{ "resource": "" }
q237565
World.remove_processor
train
def remove_processor(self, processor_type: Processor) -> None: """Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove. """ for processor in self._processors: if type(processor) == processor_type: proces...
python
{ "resource": "" }
q237566
World.get_processor
train
def get_processor(self, processor_type: Type[P]) -> P: """Get a Processor instance, by type. This method returns a Processor instance by type. This could be useful in certain situations, such as wanting to call a method on a Processor, from within another Processor. :param proc...
python
{ "resource": "" }
q237567
World.create_entity
train
def create_entity(self, *components) -> int: """Create a new Entity. This method returns an Entity ID, which is just a plain integer. You can optionally pass one or more Component instances to be assigned to the Entity. :param components: Optional components to be assigned to t...
python
{ "resource": "" }
q237568
World.delete_entity
train
def delete_entity(self, entity: int, immediate=False) -> None: """Delete an Entity from the World. Delete an Entity and all of it's assigned Component instances from the world. By default, Entity deletion is delayed until the next call to *World.process*. You can request immediate delet...
python
{ "resource": "" }
q237569
World.component_for_entity
train
def component_for_entity(self, entity: int, component_type: Type[C]) -> C: """Retrieve a Component instance for a specific Entity. Retrieve a Component instance for a specific Entity. In some cases, it may be necessary to access a specific Component instance. For example: directly modif...
python
{ "resource": "" }
q237570
World.components_for_entity
train
def components_for_entity(self, entity: int) -> Tuple[C, ...]: """Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing ...
python
{ "resource": "" }
q237571
World.has_component
train
def has_component(self, entity: int, component_type: Any) -> bool: """Check if a specific Entity has a Component of a certain type. :param entity: The Entity you are querying. :param component_type: The type of Component to check for. :return: True if the Entity has a Component of this ...
python
{ "resource": "" }
q237572
World.add_component
train
def add_component(self, entity: int, component_instance: Any) -> None: """Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the ...
python
{ "resource": "" }
q237573
World.remove_component
train
def remove_component(self, entity: int, component_type: Any) -> int: """Remove a Component instance from an Entity, by type. A Component instance can be removed by providing it's type. For example: world.delete_component(enemy_a, Velocity) will remove the Velocity instance from the Enti...
python
{ "resource": "" }
q237574
World._get_component
train
def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]: """Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples. """ entity_db = self._entities for e...
python
{ "resource": "" }
q237575
World._get_components
train
def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]: """Get an iterator for Entity and multiple Component sets. :param component_types: Two or more Component types. :return: An iterator for Entity, (Component1, Component2, etc) tuples. """ entit...
python
{ "resource": "" }
q237576
World.try_component
train
def try_component(self, entity: int, component_type: Type): """Try to get a single component type for an Entity. This method will return the requested Component if it exists, but will pass silently if it does not. This allows a way to access optional Componen...
python
{ "resource": "" }
q237577
World._clear_dead_entities
train
def _clear_dead_entities(self): """Finalize deletion of any Entities that are marked dead. In the interest of performance, this method duplicates code from the `delete_entity` method. If that method is changed, those changes should be duplicated here as well. """ ...
python
{ "resource": "" }
q237578
World._timed_process
train
def _timed_process(self, *args, **kwargs): """Track Processor execution time for benchmarking.""" for processor in self._processors: start_time = _time.process_time() processor.process(*args, **kwargs) process_time = int(round((_time.process_time() - start_time) * 100...
python
{ "resource": "" }
q237579
World.process
train
def process(self, *args, **kwargs): """Call the process method on all Processors, in order of their priority. Call the *process* method on all assigned Processors, respecting their optional priority setting. In addition, any Entities that were marked for deletion since the last call to ...
python
{ "resource": "" }
q237580
texture_from_image
train
def texture_from_image(renderer, image_name): """Create an SDL2 Texture from an image file""" soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
python
{ "resource": "" }
q237581
setup_tree
train
def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None): ''' Sets up the SDSS tree enviroment ''' print('Setting up the tree') ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))
python
{ "resource": "" }
q237582
Tree.set_roots
train
def set_roots(self, uproot_with=None): ''' Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable ''' # Check for TREE_DIR self.treedir = os.envir...
python
{ "resource": "" }
q237583
Tree.load_config
train
def load_config(self, config=None): ''' loads a config file Parameters: config (str): Optional name of manual config file to load ''' # Read the config file cfgname = (config or self.config_name) cfgname = 'sdsswork' if cfgname is None else c...
python
{ "resource": "" }
q237584
Tree.branch_out
train
def branch_out(self, limb=None): ''' Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into the os environment. Parameters: ...
python
{ "resource": "" }
q237585
Tree.add_limbs
train
def add_limbs(self, key=None): ''' Add a new section from the tree into the existing os environment Parameters: key (str): The section name to grab from the environment ''' self.branch_out(limb=key) self.add_paths_to_os(key=key)
python
{ "resource": "" }
q237586
Tree.get_paths
train
def get_paths(self, key): ''' Retrieve a set of environment paths from the config Parameters: key (str): The section name to grab from the environment Returns: self.environ[newkey] (OrderedDict): An ordered dict containing all of the path...
python
{ "resource": "" }
q237587
Tree.add_paths_to_os
train
def add_paths_to_os(self, key=None, update=None): ''' Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): The section name to check agains...
python
{ "resource": "" }
q237588
Tree.check_paths
train
def check_paths(self, paths, update=None): ''' Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:val = name:path update (bool): ...
python
{ "resource": "" }
q237589
Tree.replant_tree
train
def replant_tree(self, config=None, exclude=None): ''' Replant the tree with a different config setup Parameters: config (str): The config name to reload exclude (list): A list of environment variables to exclude from forced update...
python
{ "resource": "" }
q237590
print_exception_formatted
train
def print_exception_formatted(type, value, tb): """A custom hook for printing tracebacks with colours.""" tbtext = ''.join(traceback.format_exception(type, value, tb)) lexer = get_lexer_by_name('pytb', stripall=True) formatter = TerminalFormatter() sys.stderr.write(highlight(tbtext, lexer, formatte...
python
{ "resource": "" }
q237591
colored_formatter
train
def colored_formatter(record): """Prints log messages with colours.""" colours = {'info': ('blue', 'normal'), 'debug': ('magenta', 'normal'), 'warning': ('yellow', 'normal'), 'print': ('green', 'normal'), 'error': ('red', 'bold')} levelname = rec...
python
{ "resource": "" }
q237592
MyLogger._catch_exceptions
train
def _catch_exceptions(self, exctype, value, tb): """Catches all exceptions and logs them.""" # Now we log it. self.error('Uncaught exception', exc_info=(exctype, value, tb)) # First, we print to stdout with some colouring. print_exception_formatted(exctype, value, tb)
python
{ "resource": "" }
q237593
MyLogger._set_defaults
train
def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False): """Reset logger to its initial state.""" # Remove all previous handlers for handler in self.handlers[:]: self.removeHandler(handler) # Set levels self.setLevel(logging.DEBUG) # Set up t...
python
{ "resource": "" }
q237594
MyLogger.start_file_logger
train
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'): """Start file logging.""" log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name) logdir = log_file_path.parent try: logdir.mkdir(parents=True, exist_ok=True) ...
python
{ "resource": "" }
q237595
create_index_page
train
def create_index_page(environ, defaults, envdir): ''' create the env index html page Builds the index.html page containing a table of symlinks to datamodel directories Parameters: environ (dict): A tree environment dictionary defaults (dict): The defaults di...
python
{ "resource": "" }
q237596
create_env
train
def create_env(environ, mirror=None, verbose=None): ''' create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file. Parameters: environ (dict): A tree environment dictionary mirror (bool...
python
{ "resource": "" }
q237597
check_sas_base_dir
train
def check_sas_base_dir(root=None): ''' Check for the SAS_BASE_DIR environment variable Will set the SAS_BASE_DIR in your local environment or prompt you to define one if is undefined Parameters: root (str): Optional override of the SAS_BASE_DIR envvar ''' sasbasedir = root...
python
{ "resource": "" }
q237598
write_file
train
def write_file(environ, term='bash', out_dir=None, tree_dir=None): ''' Write a tree environment file Loops over the tree environ and writes them out to a bash, tsch, or modules file Parameters: environ (dict): The tree dictionary environment term (str): The type...
python
{ "resource": "" }
q237599
get_tree
train
def get_tree(config=None): ''' Get the tree for a given config Parameters: config (str): The name of the tree config to load Returns: a Python Tree instance ''' path = os.path.dirname(os.path.abspath(__file__)) pypath = os.path.realpath(os.path.join(path, '..', 'pyt...
python
{ "resource": "" }