repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
rosshamish/hexgrid
hexgrid.py
nodes_touching_edge
python
def nodes_touching_edge(edge_coord): a, b = hex_digit(edge_coord, 1), hex_digit(edge_coord, 2) if a % 2 == 0 and b % 2 == 0: return [coord_from_hex_digits(a, b + 1), coord_from_hex_digits(a + 1, b)] else: return [coord_from_hex_digits(a, b), coord_from_hex_dig...
Returns the two node coordinates which are on the given edge coordinate. :return: list of 2 node coordinates which are on the given edge coordinate, list(int)
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L386-L398
[ "def hex_digit(coord, digit=1):\n \"\"\"\n Returns either the first or second digit of the hexadecimal representation of the given coordinate.\n :param coord: hexadecimal coordinate, int\n :param digit: 1 or 2, meaning either the first or second digit of the hexadecimal\n :return: int, either the fir...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
legal_edge_coords
python
def legal_edge_coords(): edges = set() for tile_id in legal_tile_ids(): for edge in edges_touching_tile(tile_id): edges.add(edge) logging.debug('Legal edge coords({})={}'.format(len(edges), edges)) return edges
Return all legal edge coordinates on the grid.
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L401-L410
[ "def legal_tile_ids():\n \"\"\"\n Return all legal tile identifiers on the grid. In the range [1,19] inclusive.\n \"\"\"\n return set(_tile_id_to_coord.keys())\n", "def edges_touching_tile(tile_id):\n \"\"\"\n Get a list of edge coordinates touching the given tile.\n\n :param tile_id: tile id...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
legal_node_coords
python
def legal_node_coords(): nodes = set() for tile_id in legal_tile_ids(): for node in nodes_touching_tile(tile_id): nodes.add(node) logging.debug('Legal node coords({})={}'.format(len(nodes), nodes)) return nodes
Return all legal node coordinates on the grid
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L413-L422
[ "def legal_tile_ids():\n \"\"\"\n Return all legal tile identifiers on the grid. In the range [1,19] inclusive.\n \"\"\"\n return set(_tile_id_to_coord.keys())\n", "def nodes_touching_tile(tile_id):\n \"\"\"\n Get a list of node coordinates touching the given tile.\n\n :param tile_id: tile id...
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
hex_digit
python
def hex_digit(coord, digit=1): if digit not in [1,2]: raise ValueError('hex_digit can only get the first or second digit of a hex number, was passed digit={}'.format( digit )) return int(hex(coord)[1+digit], 16)
Returns either the first or second digit of the hexadecimal representation of the given coordinate. :param coord: hexadecimal coordinate, int :param digit: 1 or 2, meaning either the first or second digit of the hexadecimal :return: int, either the first or second digit
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L439-L450
null
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
rosshamish/hexgrid
hexgrid.py
rotate_direction
python
def rotate_direction(hexgrid_type, direction, ccw=True): if hexgrid_type in [TILE, EDGE]: directions = ['NW', 'W', 'SW', 'SE', 'E', 'NE', 'NW'] if ccw \ else ['NW', 'NE', 'E', 'SE', 'SW', 'W', 'NW'] return directions[directions.index(direction) + 1] elif hexgrid_type in [NODE]: ...
Takes a direction string associated with a type of hexgrid element, and rotates it one tick in the given direction. :param direction: string, eg 'NW', 'N', 'SE' :param ccw: if True, rotates counter clockwise. Otherwise, rotates clockwise. :return: the rotated direction string, eg 'SW', 'NW', 'S'
train
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L469-L485
null
""" module hexgrid provides functions for working with a hexagonal settlers of catan grid. This module implements the coordinate system described in Robert S. Thomas's PhD dissertation on JSettlers2, Appendix A. See the project at https://github.com/jdmonin/JSettlers2 for details. Grids have tiles, nodes, and edges...
weijia/djangoautoconf
djangoautoconf/django_zip_template_loader.py
load_template_source
python
def load_template_source(template_name, template_dirs=None): template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", []) # Try each ZIP file in TEMPLATE_ZIP_FILES. for fname in template_zipfiles: try: z = zipfile.ZipFile(fname) source = z.read(template_name) exce...
Template loader that loads templates from a ZIP file.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/django_zip_template_loader.py#L6-L23
null
import zipfile from django.conf import settings from django.template import TemplateDoesNotExist # This loader is always usable (since zipfile is included with Python) load_template_source.is_usable = True
weijia/djangoautoconf
djangoautoconf/django_autoconf.py
DjangoAutoConf.set_settings_env
python
def set_settings_env(executable_folder=None): executable_folder = executable_folder or get_executable_folder() # print "!!!!!!!!!!!!!! executable:", executable_folder if os.path.exists(os.path.join(executable_folder, "local/total_settings.py")): print("Using total settings") ...
Add all application folders :param executable_folder: the folder that contains local and external_app_repos :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/django_autoconf.py#L111-L127
null
class DjangoAutoConf(DjangoSettingManager): """ external_app_repos repo folder server app folders/modules may be imported """ AUTO_DETECT_CONFIG_FILENAME = "default_settings.py" def __init__(self, default_settings_import_str=None): super(DjangoAutoConf, self).__init__(de...
weijia/djangoautoconf
djangoautoconf/class_based_views/detail_with_inline_view.py
all_valid
python
def all_valid(formsets): valid = True for formset in formsets: if not formset.is_valid(): valid = False return valid
Returns true if every formset in formsets is valid.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L7-L13
null
from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseRedirect from django.utils.encoding import force_text from django.views.generic import DetailView class DetailWithInlineView(DetailView): template_name = "detail_with_inline_view.html" inlines = [] model = None ...
weijia/djangoautoconf
djangoautoconf/class_based_views/detail_with_inline_view.py
DetailWithInlineView.forms_valid
python
def forms_valid(self, inlines): for formset in inlines: formset.save() return HttpResponseRedirect(self.get_success_url())
If the form and formsets are valid, save the associated models.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L34-L40
null
class DetailWithInlineView(DetailView): template_name = "detail_with_inline_view.html" inlines = [] model = None success_url = "" def get_context_data(self, **kwargs): context = super(DetailWithInlineView, self).get_context_data(**kwargs) inlines = self.construct_inlines() c...
weijia/djangoautoconf
djangoautoconf/class_based_views/detail_with_inline_view.py
DetailWithInlineView.post
python
def post(self, request, *args, **kwargs): self.object = self.get_object() self.get_context_data() inlines = self.construct_inlines() if all_valid(inlines): return self.forms_valid(inlines) return self.forms_invalid(inlines)
Handles POST requests, instantiating a form and formset instances with the passed POST variables and then checked for validity.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L60-L71
[ "def all_valid(formsets):\n \"\"\"Returns true if every formset in formsets is valid.\"\"\"\n valid = True\n for formset in formsets:\n if not formset.is_valid():\n valid = False\n return valid\n" ]
class DetailWithInlineView(DetailView): template_name = "detail_with_inline_view.html" inlines = [] model = None success_url = "" def get_context_data(self, **kwargs): context = super(DetailWithInlineView, self).get_context_data(**kwargs) inlines = self.construct_inlines() c...
weijia/djangoautoconf
djangoautoconf/class_based_views/detail_with_inline_view.py
DetailWithInlineView.get_success_url
python
def get_success_url(self): if self.success_url: # Forcing possible reverse_lazy evaluation url = force_text(self.success_url) else: raise ImproperlyConfigured( "No URL to redirect to. Provide a success_url.") return url
Returns the supplied success URL.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L78-L88
null
class DetailWithInlineView(DetailView): template_name = "detail_with_inline_view.html" inlines = [] model = None success_url = "" def get_context_data(self, **kwargs): context = super(DetailWithInlineView, self).get_context_data(**kwargs) inlines = self.construct_inlines() c...
weijia/djangoautoconf
djangoautoconf/class_based_views/create_view_factory.py
create_ajaxable_view_from_model_inherit_parent_class
python
def create_ajaxable_view_from_model_inherit_parent_class(model_class, parent_class_list, operation="Create"): generic_module = importlib.import_module("django.views.generic") view_class_name = "%sView" % operation view_class = getattr(generic_module, view_class_name) # parent_class_tuple = (ajax_mixin, ...
:param model_class: the django model class :param operation: "Create" or "Update" :param ajax_mixin: user may pass a sub class of AjaxableResponseMixin to put more info in the ajax response :return: dynamically generated class based view. The instance of the view class has as_view method.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/create_view_factory.py#L33-L53
null
import importlib # from compat import JsonResponse # from django.views.generic import CreateView, UpdateView from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin # def get_ajax_create_view_from_model(model_class): # create_view_class = type(model_class.__name__ + "CreateView", # ...
weijia/djangoautoconf
djangoautoconf/auto_conf_admin_tools/admin_register.py
AdminRegister.register_all_models
python
def register_all_models(self, module_instance, exclude_name_list=[]): for class_instance in class_enumerator(module_instance, exclude_name_list): if is_inherit_from_model(class_instance): self.register(class_instance)
:param module_instance: the module instance that containing models.Model inherited classes, mostly the models module :param exclude_name_list: class does not need to register or is already registered :return: N/A
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/auto_conf_admin_tools/admin_register.py#L143-L152
[ "def is_inherit_from_model(class_inst):\n if models.Model in class_inst.__bases__:\n return True\n for parent_class in class_inst.__bases__:\n if parent_class is object:\n continue\n return is_inherit_from_model(parent_class)\n return False\n", "def register(self, class_in...
class AdminRegister(object): default_feature_list = [] default_feature_list_base = [ListAndSearch, ImportExportFeature, GuardianFeature # , ReversionFeature ] for feature in default_feature_list_base: if feature is ...
weijia/djangoautoconf
djangoautoconf/ajax_select_utils/channel_creator_for_model.py
create_channels_for_related_fields_in_model
python
def create_channels_for_related_fields_in_model(model_class): need_to_create_channel = [] for field in enum_model_fields(model_class): if type(field) in get_relation_field_types(): if field.related_model == 'self': need_to_create_channel.append(model_class) elif f...
Create channel for the fields of the model, the channel name can be got by calling get_ajax_config_for_relation_fields :param model_class: :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/ajax_select_utils/channel_creator_for_model.py#L9-L30
[ "def enum_model_fields(class_inst):\n \"\"\"\n ManyToManyField is not returned. If needed, use enum_model_fields_with_many_to_many instead\n :param class_inst:\n :return:\n \"\"\"\n return class_inst.__dict__['_meta'].fields\n", "def register_channel(model_class, search_fields=()):\n \"\"\"\n...
from ajax_select.registry import registry from djangoautoconf.ajax_select_utils.ajax_select_channel_generator import register_channel from djangoautoconf.model_utils.model_attr_utils import enum_model_fields, get_relation_field_types, \ enum_model_fields_with_many_to_many, enum_model_many_to_many, model_enumerator...
weijia/djangoautoconf
djangoautoconf/ajax_select_utils/ajax_select_channel_generator.py
register_channel
python
def register_channel(model_class, search_fields=()): if len(search_fields) == 0: search_fields = get_fields_with_icontains_filter(model_class) channel_class = type(model_class.__name__ + "LookupChannel", (AutoLookupChannelBase,), {"model": model_class, ...
Register channel for model :param model_class: model to register channel for :param search_fields: :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/ajax_select_utils/ajax_select_channel_generator.py#L38-L53
[ "def get_fields_with_icontains_filter(model_class):\n text_fields = []\n for field in enum_model_fields(model_class):\n if type(field) in (models.TextField, models.CharField, models.IntegerField):\n text_fields.append(field.name)\n return text_fields\n" ]
from ajax_select import LookupChannel from ajax_select.registry import registry from django.conf.urls import url, include from ajax_select import urls as ajax_select_urls from django.db import models from django.db.models import Q from djangoautoconf.auto_conf_urls import add_to_root_url_pattern from ufs_tools.string_...
weijia/djangoautoconf
djangoautoconf/obs/auto_conf_admin_utils.py
register_to_sys_with_admin_list
python
def register_to_sys_with_admin_list(class_inst, admin_list=None, is_normal_admin_needed=False): if admin_list is None: admin_class = get_valid_admin_class_with_list([], class_inst) else: admin_class = get_valid_admin_class_with_list(admin_list, class_inst) if is_normal_admin_needed: ...
:param class_inst: model class :param admin_list: admin class :param is_normal_admin_needed: is normal admin registration needed :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/obs/auto_conf_admin_utils.py#L61-L75
[ "def get_valid_admin_class_with_list(admin_list, class_inst):\n #print admin_list\n copied_admin_list = copy.copy(admin_list)\n copied_admin_list.append(SingleModelAdmin)\n #print ModelAdmin\n #print final_parents\n admin_class = type(class_inst.__name__ + \"Admin\", tuple(copied_admin_list), {})\...
import copy import inspect from django.conf import settings if "guardian" in settings.INSTALLED_APPS: from guardian.admin import GuardedModelAdmin as SingleModelAdmin else: from django.contrib.admin import ModelAdmin as SingleModelAdmin #from django.contrib.admin import ModelAdmin from django.contrib import ...
weijia/djangoautoconf
djangoautoconf/obs/auto_conf_admin_utils.py
register_all_in_module
python
def register_all_in_module(module_instance, exclude_name_list=[], admin_class_list=None): class_list = [] for name, obj in inspect.getmembers(module_instance): if inspect.isclass(obj): if obj.__name__ in exclude_name_list: continue class_list.append(obj) #prin...
:param module_instance: mostly the models module :param exclude_name_list: class does not need to register or is already registered :param admin_class_list: :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/obs/auto_conf_admin_utils.py#L88-L102
[ "def register_all(class_list, admin_class_list=None):\n \"\"\"\n :param class_list: list of class need to be registered to admin\n :param admin_class_list: parent of admin model class\n :return: no\n \"\"\"\n for i in class_list:\n register_to_sys_with_admin_list(i, admin_class_list)\n" ]
import copy import inspect from django.conf import settings if "guardian" in settings.INSTALLED_APPS: from guardian.admin import GuardedModelAdmin as SingleModelAdmin else: from django.contrib.admin import ModelAdmin as SingleModelAdmin #from django.contrib.admin import ModelAdmin from django.contrib import ...
weijia/djangoautoconf
djangoautoconf/django_adv_zip_template_loader.py
Loader.load_template_source
python
def load_template_source(self, template_name, template_dirs=None): #Get every app's folder log.error("Calling zip loader") for folder in app_template_dirs: if ".zip/" in folder.replace("\\", "/"): lib_file, relative_folder = get_zip_file_and_relative_path(folder) ...
Template loader that loads templates from zipped modules.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/django_adv_zip_template_loader.py#L44-L71
[ "def get_zip_file_and_relative_path(full_path_into_zip):\n full_path_into_zip = full_path_into_zip.replace(\"\\\\\", \"/\")\n zip_ext = \".zip\"\n zip_ext_start_index = full_path_into_zip.find(zip_ext + \"/\")\n lib_path = full_path_into_zip[0:zip_ext_start_index] + zip_ext\n inner_path = full_path_i...
class Loader(BaseLoader): is_usable = True
weijia/djangoautoconf
djangoautoconf/local_key_manager.py
get_local_key
python
def get_local_key(module_and_var_name, default_module=None): if "-" in module_and_var_name: raise ModuleAndVarNameShouldNotHaveDashCharacter key_name_module_path = module_and_var_name.split(".") module_name = ".".join(key_name_module_path[0:-1]) attr_name = key_name_module_path[-1] c = Confi...
Get local setting for the keys. :param module_and_var_name: for example: admin_account.admin_user, then you need to put admin_account.py in local/local_keys/ and add variable admin_user="real admin username", module_name_and_var_name should not contain "-" because :param default_module: If the t...
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/local_key_manager.py#L37-L52
[ "def get_attr(self, attr_name):\n try:\n m = self.get_module_of_local_keys()\n # return getattr(m, attr_name)\n except ImportError:\n # from management.commands.keys_default.admin_pass import default_admin_password, default_admin_user\n if self.default_module is None:\n ...
import importlib class ConfigurableAttributeGetter(object): def __init__(self, module_of_attribute, default_module=None): super(ConfigurableAttributeGetter, self).__init__() self.module_of_attribute = module_of_attribute self.default_module = default_module def get_module_of_local_key...
weijia/djangoautoconf
djangoautoconf/class_based_views/ajax_views.py
AjaxableViewMixin.render_to_response
python
def render_to_response(self, context, **response_kwargs): context["ajax_form_id"] = self.ajax_form_id # context["base_template"] = "towel_bootstrap/modal.html" return self.response_class( request=self.request, template=self.get_template_names(), context=contex...
Returns a response with a template rendered with the given context.
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/ajax_views.py#L47-L58
[ "def get_template_names(self):\n return [self.ajax_base_template]\n" ]
class AjaxableViewMixin(object): is_ajax_view = False ajax_form_id = "ajaxFormId" ajax_base_template = "ajax_base.html" def get_template_names(self): return [self.ajax_base_template]
weijia/djangoautoconf
djangoautoconf/model_utils/model_duplicator.py
get_duplicated_model
python
def get_duplicated_model(class_inst, new_class_name): # Ref: http://www.cnblogs.com/Jerryshome/archive/2012/12/21/2827492.html # get caller stack frame # caller_frame = inspect.currentframe() caller_frame_record = inspect.stack()[1] # parse module name module = inspect.getmodule(caller_frame_re...
Duplicate the model fields from class_inst to new_class_name, example: NewClass = get_duplicated_model(OldClass, "NewClass") :param class_inst: :param new_class_name: :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/model_utils/model_duplicator.py#L11-L26
[ "def get_duplicated_model(self, class_inst, new_class_name):\n \"\"\"\n Duplicate the model fields from class_inst to new_class_name, example:\n NewClass = get_duplicated_model(OldClass, \"NewClass\")\n :param class_inst:\n :param new_class_name:\n :return:\n \"\"\"\n # Ref: http://www.cnblo...
import inspect from django.db import models from djangoautoconf.model_utils.model_attr_utils import is_relation_field import copy from django.db import models __author__ = 'weijia' # Ref: # https://stackoverflow.com/questions/12222003/copying-a-django-field-description-from-an-existing-model-to-a-new-one def copy_...
weijia/djangoautoconf
djangoautoconf/model_utils/model_duplicator.py
ModelDuplicator.get_duplicated_model
python
def get_duplicated_model(self, class_inst, new_class_name): # Ref: http://www.cnblogs.com/Jerryshome/archive/2012/12/21/2827492.html attr_dict = {'__module__': self.module_name} for field in class_inst.__dict__['_meta'].fields: if self.is_relation_field_needed: attr_d...
Duplicate the model fields from class_inst to new_class_name, example: NewClass = get_duplicated_model(OldClass, "NewClass") :param class_inst: :param new_class_name: :return:
train
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/model_utils/model_duplicator.py#L58-L81
[ "def is_relation_field(field):\n if type(field) in get_relation_field_types():\n return True\n return False\n", "def copy_field(f):\n fp = copy.copy(f)\n\n fp.creation_counter = models.Field.creation_counter\n models.Field.creation_counter += 1\n\n if hasattr(f, \"model\"):\n del f...
class ModelDuplicator(object): def __init__(self, module_name=None): super(ModelDuplicator, self).__init__() self.is_relation_field_needed = True if module_name is None: caller_frame_record = inspect.stack()[1] # parse module name module = inspect.getmodul...
OpenGov/og-python-utils
ogutils/loggers/default.py
build_default_logger
python
def build_default_logger( logger_name='logger', log_level=None, log_dir=None, console_enabled=True, max_log_size=5*1024*1024, max_backup_logs=5): ''' Generates a logger that outputs messages in the same format as default Flask applications. ''' old_logger_class = loggin...
Generates a logger that outputs messages in the same format as default Flask applications.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/default.py#L117-L135
null
import os import sys import logging import logging.handlers DEFAULT_LOGGER_FORMAT = logging.Formatter('[%(asctime)s] %(message)s') NO_FILE_INDICATOR = {'file': False} NO_CONSOLE_INDICATOR = {'console': False} class ExtraAttributeLogger(logging.Logger): def __init__(self, name, level=logging.NOTSET, extra_record_a...
OpenGov/og-python-utils
ogutils/loggers/default.py
DebugEvalLogger.debug_generate
python
def debug_generate(self, debug_generator, *gen_args, **gen_kwargs): ''' Used for efficient debug logging, where the actual message isn't evaluated unless it will actually be accepted by the logger. ''' if self.isEnabledFor(logging.DEBUG): message = debug_generat...
Used for efficient debug logging, where the actual message isn't evaluated unless it will actually be accepted by the logger.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/default.py#L22-L31
null
class DebugEvalLogger(logging.Logger): def debug_generate(self, debug_generator, *gen_args, **gen_kwargs): ''' Used for efficient debug logging, where the actual message isn't evaluated unless it will actually be accepted by the logger. ''' if self.isEnabledFor(logging.DEBUG)...
OpenGov/og-python-utils
ogutils/collections/checks.py
any_shared
python
def any_shared(enum_one, enum_two): ''' Truthy if any element in enum_one is present in enum_two ''' if not is_collection(enum_one) or not is_collection(enum_two): return False enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one) enum_two = enum_two if isins...
Truthy if any element in enum_one is present in enum_two
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/checks.py#L13-L21
[ "def is_collection(elem):\n '''\n Truthy if the argument is a collection object\n '''\n return hasattr(elem, '__iter__') or hasattr(elem, '__getitem__')\n" ]
def is_collection(elem): ''' Truthy if the argument is a collection object ''' return hasattr(elem, '__iter__') or hasattr(elem, '__getitem__') def is_empty(elem): ''' Truthy if the argument is empty, but falsy for non-collection falsy elements ''' return is_collection(elem) and not any...
OpenGov/og-python-utils
ogutils/functions/decorators.py
listify
python
def listify(generator_func): ''' Converts generator functions into list returning functions. @listify def test(): yield 1 test() # => [1] ''' def list_func(*args, **kwargs): return degenerate(generator_func(*args, **kwargs)) return list_func
Converts generator functions into list returning functions. @listify def test(): yield 1 test() # => [1]
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/decorators.py#L3-L15
null
from ..collections.transformations import degenerate
OpenGov/og-python-utils
ogutils/functions/operators.py
restrict_args
python
def restrict_args(func, *args, **kwargs): ''' Restricts the possible arguements to a method to match the func argument. restrict_args(lambda a: a, 1, 2) # => 1 ''' callargs = getargspec(func) if not callargs.varargs: args = args[0:len(callargs.args)] return func(*args,...
Restricts the possible arguements to a method to match the func argument. restrict_args(lambda a: a, 1, 2) # => 1
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/operators.py#L3-L13
[ "self.assertEquals(operators.restrict_args(lambda: '', 'a', 'b'), '')\n", "self.assertEquals(operators.restrict_args(lambda a: a, 'a'), 'a')\n", "self.assertEquals(operators.restrict_args(lambda a: a, 'a', 'b'), 'a')\n", "self.assertEquals(operators.restrict_args(lambda a, b: a + b, 'a', 'b'), 'ab')\n", "se...
from inspect import getargspec def restrict_args(func, *args, **kwargs): ''' Restricts the possible arguements to a method to match the func argument. restrict_args(lambda a: a, 1, 2) # => 1 ''' callargs = getargspec(func) if not callargs.varargs: args = args[0:len(callargs.args)] ...
OpenGov/og-python-utils
ogutils/functions/operators.py
repeat_call
python
def repeat_call(func, retries, *args, **kwargs): ''' Tries a total of 'retries' times to execute callable before failing. ''' retries = max(0, int(retries)) try_num = 0 while True: if try_num == retries: return func(*args, **kwargs) else: try: ...
Tries a total of 'retries' times to execute callable before failing.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/operators.py#L15-L30
[ "return repeat_call(lambda: urllib2.urlopen(req).read(), retries)\n", "return repeat_call(lambda: json.loads(urllib2.urlopen(req).read()), retries)\n", "def fail_count_down():\n if fail_count_down.fail_count == 0:\n return 'success'\n else:\n fail_count_down.fail_count -= 1\n raise Ty...
from inspect import getargspec def restrict_args(func, *args, **kwargs): ''' Restricts the possible arguements to a method to match the func argument. restrict_args(lambda a: a, 1, 2) # => 1 ''' callargs = getargspec(func) if not callargs.varargs: args = args[0:len(callargs.args)] ...
OpenGov/og-python-utils
ogutils/web/operators.py
repeat_read_url_request
python
def repeat_read_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times ''' if logger: logger.debug("Retrieving url content: {}".format(url)) req = urllib2.Request(url, data, headers=headers or {}) ret...
Allows for repeated http requests up to retries additional times
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L6-L13
[ "def repeat_call(func, retries, *args, **kwargs):\n '''\n Tries a total of 'retries' times to execute callable before failing.\n '''\n retries = max(0, int(retries))\n try_num = 0\n while True:\n if try_num == retries:\n return func(*args, **kwargs)\n else:\n tr...
import urllib2 import json from ..functions.operators import repeat_call def repeat_read_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times ''' if logger: logger.debug("Retrieving url content: {}".format(url))...
OpenGov/og-python-utils
ogutils/web/operators.py
repeat_read_json_url_request
python
def repeat_read_json_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response ''' if logger: logger.debug("Retrieving url json content: {}".format(url)) ...
Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L15-L23
[ "def repeat_call(func, retries, *args, **kwargs):\n '''\n Tries a total of 'retries' times to execute callable before failing.\n '''\n retries = max(0, int(retries))\n try_num = 0\n while True:\n if try_num == retries:\n return func(*args, **kwargs)\n else:\n tr...
import urllib2 import json from ..functions.operators import repeat_call def repeat_read_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times ''' if logger: logger.debug("Retrieving url content: {}".format(url))...
OpenGov/og-python-utils
ogutils/checks.py
booleanize
python
def booleanize(truthy): ''' Smartly converts argument to true or false. Strings and variants of 'true' and 'false' convert to appropriate types, along with normal bool() like conversions. ''' if truthy is None: return False elif isinstance(truthy, basestring): if tru...
Smartly converts argument to true or false. Strings and variants of 'true' and 'false' convert to appropriate types, along with normal bool() like conversions.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/checks.py#L4-L23
[ "def is_collection(elem):\n '''\n Truthy if the argument is a collection object\n '''\n return hasattr(elem, '__iter__') or hasattr(elem, '__getitem__')\n", "def is_empty(elem):\n '''\n Truthy if the argument is empty, but falsy for non-collection falsy elements\n '''\n return is_collectio...
import distutils from .collections.checks import is_collection, is_empty def booleanize(truthy): ''' Smartly converts argument to true or false. Strings and variants of 'true' and 'false' convert to appropriate types, along with normal bool() like conversions. ''' if truthy is None: ret...
OpenGov/og-python-utils
ogutils/loggers/flask.py
build_flask_like_logger
python
def build_flask_like_logger( logger_name='logger', log_level=None, log_dir=None, console_enabled=True, max_log_size=5*1024*1024, max_backup_logs=5, host=None): ''' Generates a logger that outputs messages in the same format as default Flask applications. ''' old_lo...
Generates a logger that outputs messages in the same format as default Flask applications.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/flask.py#L100-L121
null
import sys import time import logging import logging.handlers from .default import DefaultLogger MONTH_NAMES = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] class OrderedFormatsFormatter(logging.Formatter): ''' Allows for multiple _fmt to be applied in order until ...
OpenGov/og-python-utils
ogutils/loggers/flask.py
OrderedFormatsFormatter.usesTime
python
def usesTime(self, fmt=None): ''' Check if the format uses the creation time of the record. ''' if fmt is None: fmt = self._fmt if not isinstance(fmt, basestring): fmt = fmt[0] return fmt.find('%(asctime)') >= 0
Check if the format uses the creation time of the record.
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/flask.py#L20-L28
null
class OrderedFormatsFormatter(logging.Formatter): ''' Allows for multiple _fmt to be applied in order until all their keys are accounted for and processed. OrderedFormatsFormatter(['%(host)s -- %(message)s', '%(message)s']) creates a formatter that will first try to format a host into the message ...
OpenGov/og-python-utils
ogutils/collections/operators.py
apply_dict_default
python
def apply_dict_default(dictionary, arg, default): ''' Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object apply_dict_default({}, 'test', list) # => {'test': []} apply_dict_default({'test': 'ok'}, 'test', list) # => {'test': 'ok'} ''' if ...
Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object apply_dict_default({}, 'test', list) # => {'test': []} apply_dict_default({'test': 'ok'}, 'test', list) # => {'test': 'ok'}
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/operators.py#L3-L18
[ "def restrict_args(func, *args, **kwargs):\n '''\n Restricts the possible arguements to a method to match the func argument.\n\n restrict_args(lambda a: a, 1, 2)\n # => 1\n '''\n callargs = getargspec(func)\n if not callargs.varargs:\n args = args[0:len(callargs.args)]\n return func(*...
from ..functions.operators import restrict_args def apply_dict_default(dictionary, arg, default): ''' Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object apply_dict_default({}, 'test', list) # => {'test': []} apply_dict_default({'test': 'ok'}, 'test', list) ...
OpenGov/og-python-utils
ogutils/text/regex.py
chain_sub_regexes
python
def chain_sub_regexes(phrase, *regex_sub_pairs): ''' Allow for a series of regex substitutions to occur chain_sub_regexes('test ok', (' ', '_'), ('k$', 'oo')) # => 'test_ooo' ''' for regex, substitution in regex_sub_pairs: if isinstance(regex, basestring): regex = r...
Allow for a series of regex substitutions to occur chain_sub_regexes('test ok', (' ', '_'), ('k$', 'oo')) # => 'test_ooo'
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/text/regex.py#L3-L14
null
import re def chain_sub_regexes(phrase, *regex_sub_pairs): ''' Allow for a series of regex substitutions to occur chain_sub_regexes('test ok', (' ', '_'), ('k$', 'oo')) # => 'test_ooo' ''' for regex, substitution in regex_sub_pairs: if isinstance(regex, basestring): regex =...
OpenGov/og-python-utils
ogutils/collections/transformations.py
recursive_iter
python
def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, (basestring, dict)): yield enumerables else: for...
Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/transformations.py#L5-L17
[ "def is_collection(elem):\n '''\n Truthy if the argument is a collection object\n '''\n return hasattr(elem, '__iter__') or hasattr(elem, '__getitem__')\n" ]
import inspect from checks import is_collection from itertools import islice def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, ...
OpenGov/og-python-utils
ogutils/collections/transformations.py
degenerate
python
def degenerate(enumerable): ''' Converts generators to lists degenerate(xrange(2)) # => [0, 1] ''' if (isinstance(enumerable, xrange) or inspect.isgeneratorfunction(enumerable) or inspect.isgenerator(enumerable)): return list(enumerable) return enumerable
Converts generators to lists degenerate(xrange(2)) # => [0, 1]
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/transformations.py#L28-L39
null
import inspect from checks import is_collection from itertools import islice def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, ...
OpenGov/og-python-utils
ogutils/collections/transformations.py
merge_dicts
python
def merge_dicts(*dicts, **copy_check): ''' Combines dictionaries into a single dictionary. If the 'copy' keyword is passed then the first dictionary is copied before update. merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1}) # => {'a': 2, 'b': 1, 'c': 1} ''' merged = {} if not dic...
Combines dictionaries into a single dictionary. If the 'copy' keyword is passed then the first dictionary is copied before update. merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1}) # => {'a': 2, 'b': 1, 'c': 1}
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/transformations.py#L41-L57
null
import inspect from checks import is_collection from itertools import islice def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, ...
OpenGov/og-python-utils
ogutils/collections/transformations.py
batch
python
def batch(enumerable, batch_size): ''' Breaks enumerable argument into batch size enumerable pieces. The last chunk can be of any length up to batch_size. batch(xrange(5), 3) # => [0, 1, 2], [3, 4] ''' batch_size = max(int(batch_size), 1) try: enumerable.__getitem__ ...
Breaks enumerable argument into batch size enumerable pieces. The last chunk can be of any length up to batch_size. batch(xrange(5), 3) # => [0, 1, 2], [3, 4]
train
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/transformations.py#L59-L82
null
import inspect from checks import is_collection from itertools import islice def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, ...
rohankapoorcom/zm-py
zoneminder/run_state.py
RunState.active
python
def active(self) -> bool: states = self._client.get_state(self._state_url)['states'] for state in states: state = state['State'] if int(state['Id']) == self._state_id: # yes, the ZM API uses the *string* "1" for this... return state['IsActive'] == ...
Indicate if this RunState is currently active.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/run_state.py#L26-L34
null
class RunState: """Represents a Run State from ZoneMinder.""" def __init__(self, client, raw_state): """Create a new RunState.""" self._client = client self._state_id = int(raw_state['Id']) self._state_url = 'api/states.json' self._name = raw_state['Name'] @property...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.login
python
def login(self): _LOGGER.debug("Attempting to login to ZoneMinder") login_post = {'view': 'console', 'action': 'login'} if self._username: login_post['username'] = self._username if self._password: login_post['password'] = self._password req = requests.p...
Login to the ZoneMinder API.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L35-L62
null
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder._zm_request
python
def _zm_request(self, method, api_url, data=None, timeout=DEFAULT_TIMEOUT) -> dict: try: # Since the API uses sessions that expire, sometimes we need to # re-auth if the call fails. for _ in range(ZoneMinder.LOGIN_RETRIES): req = requests.r...
Perform a request to the ZoneMinder API.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L72-L100
[ "def login(self):\n \"\"\"Login to the ZoneMinder API.\"\"\"\n _LOGGER.debug(\"Attempting to login to ZoneMinder\")\n\n login_post = {'view': 'console', 'action': 'login'}\n if self._username:\n login_post['username'] = self._username\n if self._password:\n login_post['password'] = self...
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.get_monitors
python
def get_monitors(self) -> List[Monitor]: raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL) if not raw_monitors: _LOGGER.warning("Could not fetch monitors from ZoneMinder") return [] monitors = [] for raw_result in raw_monitors['monitors']: ...
Get a list of Monitors from the ZoneMinder API.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L102-L115
[ "def _zm_request(self, method, api_url, data=None,\n timeout=DEFAULT_TIMEOUT) -> dict:\n \"\"\"Perform a request to the ZoneMinder API.\"\"\"\n try:\n # Since the API uses sessions that expire, sometimes we need to\n # re-auth if the call fails.\n for _ in range(ZoneMinder....
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.get_run_states
python
def get_run_states(self) -> List[RunState]: raw_states = self.get_state('api/states.json') if not raw_states: _LOGGER.warning("Could not fetch runstates from ZoneMinder") return [] run_states = [] for i in raw_states['states']: raw_state = i['State'] ...
Get a list of RunStates from the ZoneMinder API.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L117-L130
[ "def get_state(self, api_url) -> dict:\n \"\"\"Perform a GET request on the specified ZoneMinder API URL.\"\"\"\n return self._zm_request('get', api_url)\n" ]
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.get_active_state
python
def get_active_state(self) -> Optional[str]: for state in self.get_run_states(): if state.active: return state.name return None
Get the name of the active run state from the ZoneMinder API.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L132-L137
[ "def get_run_states(self) -> List[RunState]:\n \"\"\"Get a list of RunStates from the ZoneMinder API.\"\"\"\n raw_states = self.get_state('api/states.json')\n if not raw_states:\n _LOGGER.warning(\"Could not fetch runstates from ZoneMinder\")\n return []\n\n run_states = []\n for i in r...
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.set_active_state
python
def set_active_state(self, state_name): _LOGGER.info('Setting ZoneMinder run state to state %s', state_name) return self._zm_request('GET', 'api/states/change/{}.json'.format(state_name), timeout=120)
Set the ZoneMinder run state to the given state name, via ZM API. Note that this is a long-running API call; ZoneMinder changes the state of each camera in turn, and this GET does not receive a response until all cameras have been updated. Even on a reasonably powerful machine, this cal...
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L139-L152
[ "def _zm_request(self, method, api_url, data=None,\n timeout=DEFAULT_TIMEOUT) -> dict:\n \"\"\"Perform a request to the ZoneMinder API.\"\"\"\n try:\n # Since the API uses sessions that expire, sometimes we need to\n # re-auth if the call fails.\n for _ in range(ZoneMinder....
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.get_url_with_auth
python
def get_url_with_auth(self, url) -> str: if not self._username: return url url += '&user={:s}'.format(self._username) if not self._password: return url return url + '&pass={:s}'.format(self._password)
Add the auth credentials to a url (if needed).
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L158-L168
null
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder.is_available
python
def is_available(self) -> bool: status_response = self.get_state( 'api/host/daemonCheck.json' ) if not status_response: return False return status_response.get('result') == 1
Indicate if this ZoneMinder service is currently available.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L171-L180
[ "def get_state(self, api_url) -> dict:\n \"\"\"Perform a GET request on the specified ZoneMinder API URL.\"\"\"\n return self._zm_request('get', api_url)\n" ]
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/zm.py
ZoneMinder._build_server_url
python
def _build_server_url(server_host, server_path) -> str: server_url = urljoin(server_host, server_path) if server_url[-1] == '/': return server_url return '{}/'.format(server_url)
Build the server url making sure it ends in a trailing slash.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L193-L198
null
class ZoneMinder: """The ZoneMinder API client itself. Create one of these to begin.""" DEFAULT_SERVER_PATH = '/zm/' DEFAULT_ZMS_PATH = '/zm/cgi-bin/nph-zms' DEFAULT_TIMEOUT = 10 LOGIN_RETRIES = 2 MONITOR_URL = 'api/monitors.json' def __init__(self, server_host, username, password, ...
rohankapoorcom/zm-py
zoneminder/monitor.py
TimePeriod.get_time_period
python
def get_time_period(value): for time_period in TimePeriod: if time_period.period == value: return time_period raise ValueError('{} is not a valid TimePeriod'.format(value))
Get the corresponding TimePeriod from the value. Example values: 'all', 'hour', 'day', 'week', or 'month'.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L41-L49
null
class TimePeriod(Enum): """Represents a period of time to check for events.""" @property def period(self) -> str: """Get the period of time.""" # pylint: disable=unsubscriptable-object return self.value[0] @property def title(self) -> str: """Explains what is measur...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor.update_monitor
python
def update_monitor(self): result = self._client.get_state(self._monitor_url) self._raw_result = result['monitor']
Update the monitor and monitor status from the ZM server.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L86-L89
null
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor.function
python
def function(self, new_function): self._client.change_state( self._monitor_url, {'Monitor[Function]': new_function.value})
Set the MonitorState of this Monitor.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L99-L103
[ "def update_monitor(self):\n \"\"\"Update the monitor and monitor status from the ZM server.\"\"\"\n result = self._client.get_state(self._monitor_url)\n self._raw_result = result['monitor']\n" ]
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor.is_recording
python
def is_recording(self) -> Optional[bool]: status_response = self._client.get_state( 'api/monitors/alarm/id:{}/command:status.json'.format( self._monitor_id ) ) if not status_response: _LOGGER.warning('Could not get status for monitor {}'.forma...
Indicate if this Monitor is currently recording.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L121-L140
null
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor.is_available
python
def is_available(self) -> bool: status_response = self._client.get_state( 'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format( self._monitor_id ) ) if not status_response: _LOGGER.warning('Could not get availability for monitor {}'.format...
Indicate if this Monitor is currently available.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L143-L161
null
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor.get_events
python
def get_events(self, time_period, include_archived=False) -> Optional[int]: date_filter = '1%20{}'.format(time_period.period) if time_period == TimePeriod.ALL: # The consoleEvents API uses DATE_SUB, so give it # something large date_filter = '100%20year' arch...
Get the number of events that have occurred on this Monitor. Specifically only gets events that have occurred within the TimePeriod provided.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L163-L192
null
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
rohankapoorcom/zm-py
zoneminder/monitor.py
Monitor._build_image_url
python
def _build_image_url(self, monitor, mode) -> str: query = urlencode({ 'mode': mode, 'buffer': monitor['StreamReplayBuffer'], 'monitor': monitor['Id'], }) url = '{zms_url}?{query}'.format( zms_url=self._client.get_zms_url(), query=query) _LO...
Build and return a ZoneMinder camera image url.
train
https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L194-L205
null
class Monitor: """Represents a Monitor from ZoneMinder.""" def __init__(self, client, raw_result): """Create a new Monitor.""" self._client = client self._raw_result = raw_result raw_monitor = raw_result['Monitor'] self._monitor_id = int(raw_monitor['Id']) self._...
neithere/monk
monk/modeling.py
StructuredDictMixin._insert_defaults
python
def _insert_defaults(self): merged = merge_defaults(self.structure, self) self.update(merged)
Inserts default values from :attr:`StructuredDictMixin.structure` to `self` by merging the two structures (see :func:`monk.manipulation.merge_defaults`).
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/modeling.py#L127-L133
[ "def merge_defaults(spec, value):\n \"\"\"\n Returns a copy of `value` recursively updated to match the `spec`:\n\n * New values are added whenever possible (including nested ones).\n * Existing values are never changed or removed.\n\n * Exception: container values (lists, dictionaries) may be popu...
class StructuredDictMixin(object): """ A dictionary with structure specification and validation. .. attribute:: structure The document structure specification. For details see :func:`monk.shortcuts.validate`. """ structure = {} #defaults = {} #required = [] #validators = {...
neithere/monk
monk/shortcuts.py
opt_key
python
def opt_key(spec): if isinstance(spec, text_types): spec = Equals(spec) return optional(spec)
Returns a validator which allows the value to be missing. Similar to :func:`optional` but wraps a string in :class:`~monk.validators.Equals` instead of :class:`~monk.validators.IsA`. Intended for dictionary keys. :: >>> opt_key(str) == IsA(str) | ~Exists() True >>> opt_key('foo...
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/shortcuts.py#L61-L78
[ "def optional(spec):\n \"\"\"\n Returns a validator which allows the value to be missing.\n\n ::\n\n >>> optional(str) == IsA(str) | ~Exists()\n True\n >>> optional('foo') == IsA(str, default='foo') | ~Exists()\n True\n\n Note that you should normally :func:`opt_key` to mark ...
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/shortcuts.py
one_of
python
def one_of(choices, first_is_default=False, as_rules=False): assert choices if as_rules: None # for coverage else: choices = [Equals(x) for x in choices] return Any(choices, first_is_default=first_is_default)
A wrapper for :class:`Any`. :param as_rules: `bool`. If `False` (by default), each element of `choices` is wrapped in the :class:`Equals` validator so they are interpreted as literals. .. deprecated:: 0.13 Use :class:`Any` instead.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/shortcuts.py#L81-L102
null
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/shortcuts.py
in_range
python
def in_range(start, stop, first_is_default=False): if first_is_default: default_value = start else: default_value = None return InRange(start, stop, default=default_value)
A shortcut for a rule with :func:`~monk.validators.validate_range` validator. :: # these expressions are equal: in_range(0, 200) Rule(int, validators=[monk.validators.validate_range(0, 200)]) # default value can be taken from the first choice: in_range(0, 200, first_is_d...
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/shortcuts.py#L105-L133
null
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/helpers.py
walk_dict
python
def walk_dict(data): assert hasattr(data, '__getitem__') for key, value in data.items(): if isinstance(value, dict): yield (key,), None for keys, value in walk_dict(value): path = (key,) + keys yield path, value else: yield (key...
Generates pairs ``(keys, value)`` for each item in given dictionary, including nested dictionaries. Each pair contains: `keys` a tuple of 1..n keys, e.g. ``('foo',)`` for a key on root level or ``('foo', 'bar')`` for a key in a nested dictionary. `value` the value of given key or ``...
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/helpers.py#L70-L89
[ "def walk_dict(data):\n \"\"\" Generates pairs ``(keys, value)`` for each item in given dictionary,\n including nested dictionaries. Each pair contains:\n\n `keys`\n a tuple of 1..n keys, e.g. ``('foo',)`` for a key on root level or\n ``('foo', 'bar')`` for a key in a nested dictionary.\n ...
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/validators.py
translate
python
def translate(value): if isinstance(value, BaseValidator): return value if value is None: return Anything() if isinstance(value, type): return IsA(value) if type(value) in compat.func_types: real_value = value() return IsA(type(real_value), default=real_value) ...
Translates given schema from "pythonic" syntax to a validator. Usage:: >>> translate(str) IsA(str) >>> translate('hello') IsA(str, default='hello')
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/validators.py#L699-L753
[ "def translate(value):\n \"\"\"\n Translates given schema from \"pythonic\" syntax to a validator.\n\n Usage::\n\n >>> translate(str)\n IsA(str)\n\n >>> translate('hello')\n IsA(str, default='hello')\n\n \"\"\"\n if isinstance(value, BaseValidator):\n return value\n...
# coding: utf-8 # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
neithere/monk
monk/validators.py
BaseListOf._merge
python
def _merge(self, value): if not value: return [] if value is not None and not isinstance(value, list): # bogus value; will not pass validation but should be preserved return value item_spec = self._nested_validator return [x if x is None else item_sp...
Returns a list based on `value`: * missing required value is converted to an empty list; * missing required items are never created; * nested items are merged recursively.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/validators.py#L431-L447
null
class BaseListOf(BaseRequirement): """ The base class for validating lists. Supports different error toleration strategies which can be selected by subclasses. In many aspects this is similar to :class:`BaseCombinator`. """ implies = IsA(list) item_strategy = NotImplemented error_class...
neithere/monk
monk/validators.py
DictOf._merge
python
def _merge(self, value): if value is not None and not isinstance(value, dict): # bogus value; will not pass validation but should be preserved return value if not self._pairs: return {} collected = {} # collected.update(value) for k_validator...
Returns a dictionary based on `value` with each value recursively merged with `spec`.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/validators.py#L589-L622
null
class DictOf(BaseRequirement): """ Requires that the value is a `dict` which items match given patterns. Usage:: >>> v = DictOf([ ... # key "name" must exist; its value must be a `str` ... (Equals('name'), IsA(str)), ... # key "age" may not exist; its value must ...
neithere/monk
monk/manipulation.py
normalize_list_of_dicts
python
def normalize_list_of_dicts(value, default_key, default_value=UNDEFINED): if value is None: if default_value is UNDEFINED: return [] value = default_value if isinstance(value, dict): return [value] if isinstance(value, text_type): return [{default_key: value}] ...
Converts given value to a list of dictionaries as follows: * ``[{...}]`` → ``[{...}]`` * ``{...}`` → ``[{...}]`` * ``'xyz'`` → ``[{default_key: 'xyz'}]`` * ``None`` → ``[{default_key: default_value}]`` (if specified) * ``None`` → ``[]`` :param default_value: only Unicode, i....
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/manipulation.py#L108-L139
null
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/compat.py
safe_str
python
def safe_str(value): if sys.version_info < (3,0) and isinstance(value, unicode): return value.encode('utf-8') else: return str(value)
Returns: * a `str` instance (bytes) in Python 2.x, or * a `str` instance (Unicode) in Python 3.x.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/compat.py#L50-L60
null
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/compat.py
safe_unicode
python
def safe_unicode(value): if sys.version_info < (3,0): if isinstance(value, str): return value.decode('utf-8') else: return unicode(value) else: return str(value)
Returns: * a `unicode` instance in Python 2.x, or * a `str` instance in Python 3.x.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/compat.py#L63-L76
null
# -*- coding: utf-8 -*- # # Monk is an unobtrusive data modeling, manipulation and validation library. # Copyright © 2011—2015 Andrey Mikhaylenko # # This file is part of Monk. # # Monk is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.find
python
def find(cls, db, *args, **kwargs): cls._ensure_indexes(db) docs = db[cls.collection].find(*args, **kwargs) return MongoResultSet(docs, partial(cls.wrap_incoming, db=db))
Returns a :class:`MongoResultSet` object. Example:: items = Item.find(db, {'title': u'Hello'}) .. note:: The arguments are those of pymongo collection's `find` method. A frequent error is to pass query key/value pairs as keyword arguments. This is **wrong...
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L165-L183
null
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.get_one
python
def get_one(cls, db, *args, **kwargs): data = db[cls.collection].find_one(*args, **kwargs) if data: return cls.wrap_incoming(data, db) else: return None
Returns an object that corresponds to given query or ``None``. Example:: item = Item.get_one(db, {'title': u'Hello'})
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L186-L199
null
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.save
python
def save(self, db): assert self.collection self._ensure_indexes(db) # XXX self.structure belongs to StructuredDictMixin !! outgoing = dict(dict_to_db(self, self.structure)) object_id = db[self.collection].save(outgoing) if self.get('_id') is None: self['_i...
Saves the object to given database. Usage:: item = Item(title=u'Hello') item.save(db) Collection name is taken from :attr:`MongoBoundDictMixin.collection`.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L201-L224
[ "def dict_to_db(data, spec={}):\n return dict(_dict_to_db_pairs(spec, data))\n", "def _ensure_indexes(cls, db):\n for field, kwargs in cls.indexes.items():\n kwargs = kwargs or {}\n db[cls.collection].ensure_index(field, **kwargs)\n" ]
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.get_id
python
def get_id(self): import warnings warnings.warn('{0}.get_id() is deprecated, ' 'use {0}.id instead'.format(type(self).__name__), DeprecationWarning) return self.get('_id')
Returns object id or ``None``.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L232-L239
null
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.get_ref
python
def get_ref(self): _id = self.id if _id is None: return None else: return DBRef(self.collection, _id)
Returns a `DBRef` for this object or ``None``.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L241-L248
null
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
neithere/monk
monk/mongo.py
MongoBoundDictMixin.remove
python
def remove(self, db): assert self.collection assert self.id db[self.collection].remove(self.id)
Removes the object from given database. Usage:: item = Item.get_one(db) item.remove(db) Collection name is taken from :attr:`MongoBoundDictMixin.collection`.
train
https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L250-L262
null
class MongoBoundDictMixin(object): """ Adds MongoDB-specific features to the dictionary. .. attribute:: collection Collection name. .. attribute:: indexes (TODO) """ collection = None indexes = {} def __hash__(self): """ Collection name and id together make the ...
COALAIP/pycoalaip
coalaip/data_formats.py
_copy_context_into_mutable
python
def _copy_context_into_mutable(context): def make_mutable(val): if isinstance(val, Mapping): return dict(val) else: return val if not isinstance(context, (str, Mapping)): try: return [make_mutable(val) for val in context] except TypeError: ...
Copy a properly formatted context into a mutable data structure.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L17-L31
[ "def make_mutable(val):\n if isinstance(val, Mapping):\n return dict(val)\n else:\n return val\n" ]
"""Utilities for data formats supported by pycoalaip.""" from collections import namedtuple, Mapping from copy import copy from enum import Enum, unique from types import MappingProxyType @unique class DataFormat(Enum): """Enum of supported data formats.""" json = 'json' jsonld = 'jsonld' ipld = 'ipl...
COALAIP/pycoalaip
coalaip/data_formats.py
_make_context_immutable
python
def _make_context_immutable(context): def make_immutable(val): if isinstance(val, Mapping): return MappingProxyType(val) else: return val if not isinstance(context, (str, Mapping)): try: return tuple([make_immutable(val) for val in context]) e...
Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType. Otherwise, return as-is.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L34-L53
[ "def make_immutable(val):\n if isinstance(val, Mapping):\n return MappingProxyType(val)\n else:\n return val\n" ]
"""Utilities for data formats supported by pycoalaip.""" from collections import namedtuple, Mapping from copy import copy from enum import Enum, unique from types import MappingProxyType @unique class DataFormat(Enum): """Enum of supported data formats.""" json = 'json' jsonld = 'jsonld' ipld = 'ipl...
COALAIP/pycoalaip
coalaip/data_formats.py
_data_format_resolver
python
def _data_format_resolver(data_format, resolver_dict): try: data_format = DataFormat(data_format) except ValueError: supported_formats = ', '.join( ["'{}'".format(f.value) for f in DataFormat]) raise ValueError(("'data_format' must be one of {formats}. Given " ...
Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. resolver_dict (dict): the resolving dict. Can hold any value ...
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L56-L80
null
"""Utilities for data formats supported by pycoalaip.""" from collections import namedtuple, Mapping from copy import copy from enum import Enum, unique from types import MappingProxyType @unique class DataFormat(Enum): """Enum of supported data formats.""" json = 'json' jsonld = 'jsonld' ipld = 'ipl...
COALAIP/pycoalaip
coalaip/data_formats.py
_extract_ld_data
python
def _extract_ld_data(data, data_format=None, **kwargs): if not data_format: data_format = _get_format_from_data(data) extract_ld_data_fn = _data_format_resolver(data_format, { 'jsonld': _extract_ld_data_from_jsonld, 'json': _extract_ld_data_from_json, 'ipld': _extract_ld_data_fr...
Extract the given :attr:`data` into a :class:`~.ExtractedLinkedDataResult` with the resulting data stripped of any Linked Data specifics. Any missing Linked Data properties are returned as ``None`` in the resulting :class:`~.ExtractLinkedDataResult`. Does not modify the given :attr:`data`.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L91-L108
[ "def _data_format_resolver(data_format, resolver_dict):\n \"\"\"Resolve a value from :attr:`resolver_dict` based on the\n :attr:`data_format`.\n\n Args:\n data_format (:class:`~.DataFormat` or str): The data format;\n must be a member of :class:`~.DataFormat` or a string\n equi...
"""Utilities for data formats supported by pycoalaip.""" from collections import namedtuple, Mapping from copy import copy from enum import Enum, unique from types import MappingProxyType @unique class DataFormat(Enum): """Enum of supported data formats.""" json = 'json' jsonld = 'jsonld' ipld = 'ipl...
COALAIP/pycoalaip
coalaip/model_validators.py
is_callable
python
def is_callable(instance, attribute, value): if not callable(value): raise TypeError("'{}' must be callable".format(attribute.name))
Raises a :exc:`TypeError` if the value is not a callable.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L6-L10
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def use_model_attr(attr): """Use the validator set on a separate attribute on the class.""" def use_model_validator(instance, attribute, value): getattr(instance, attr)(instance, attribute, va...
COALAIP/pycoalaip
coalaip/model_validators.py
use_model_attr
python
def use_model_attr(attr): def use_model_validator(instance, attribute, value): getattr(instance, attr)(instance, attribute, value) return use_model_validator
Use the validator set on a separate attribute on the class.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L13-L18
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/model_validators.py
does_not_contain
python
def does_not_contain(*avoid_keys, error_cls=ValueError): def decorator(func): def not_contains(instance, attribute, value): instance_name = instance.__class__.__name__ num_matched_keys = len(set(avoid_keys) & value.keys()) if num_matched_keys > 0: avoid_...
Decorator: value must not contain any of the :attr:`avoid_keys`.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L21-L42
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/model_validators.py
is_creation_model
python
def is_creation_model(instance, attribute, value): creation_name = value.get('name') if not isinstance(creation_name, str): instance_name = instance.__class__.__name__ err_str = ("'name' must be given as a string in the '{attr}' " "parameter of a '{cls}'. Given " ...
Must include at least a ``name`` key.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L45-L56
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/model_validators.py
is_manifestation_model
python
def is_manifestation_model(instance, attribute, value): instance_name = instance.__class__.__name__ is_creation_model(instance, attribute, value) manifestation_of = value.get('manifestationOfWork') if not isinstance(manifestation_of, str): err_str = ("'manifestationOfWork' must be given as a s...
Must include a ``manifestationOfWork`` key.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L68-L81
[ "def is_creation_model(instance, attribute, value):\n \"\"\"Must include at least a ``name`` key.\"\"\"\n\n creation_name = value.get('name')\n if not isinstance(creation_name, str):\n instance_name = instance.__class__.__name__\n err_str = (\"'name' must be given as a string in the '{attr}' ...
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/model_validators.py
is_right_model
python
def is_right_model(instance, attribute, value): for key in ['source', 'license']: key_value = value.get(key) if not isinstance(key_value, str): instance_name = instance.__class__.__name__ raise ModelDataError(("'{key}' must be given as a string in " ...
Must include at least the ``source`` and ``license`` keys, but not a ``rightsOf`` key (``source`` indicates that the Right is derived from and allowed by a source Right; it cannot contain the full rights to a Creation).
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L85-L101
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/model_validators.py
is_copyright_model
python
def is_copyright_model(instance, attribute, value): rights_of = value.get('rightsOf') if not isinstance(rights_of, str): instance_name = instance.__class__.__name__ raise ModelDataError(("'rightsOf' must be given as a string in " "the '{attr}' parameter of a '{cls}...
Must include at least a ``rightsOf`` key, but not a ``source`` key (``rightsOf`` indicates that the Right contains full rights to an existing Manifestation or Work; i.e. is a Copyright).
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L105-L118
null
"""Validators for COALA IP models (:mod:`coalaip.models`)""" from coalaip.exceptions import ModelDataError def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.nam...
COALAIP/pycoalaip
coalaip/entities.py
TransferrableEntity.transfer
python
def transfer(self, transfer_payload=None, *, from_user, to_user): if self.persist_id is None: raise EntityNotYetPersistedError(('Entities cannot be transferred ' 'until they have been ' 'persisted')) ...
Transfer this entity to another owner on the backing persistence layer Args: transfer_payload (dict): Payload for the transfer from_user (any): A user based on the model specified by the persistence layer to_user (any): A user based on the model speci...
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L409-L442
null
class TransferrableEntity(Entity): """Base class for transferable COALA IP entity models. Provides functionality for transferrable entities through :meth:`transfer` """
COALAIP/pycoalaip
coalaip/entities.py
Right.transfer
python
def transfer(self, rights_assignment_data=None, *, from_user, to_user, rights_assignment_format='jsonld'): rights_assignment = RightsAssignment.from_data( rights_assignment_data or {}, plugin=self.plugin) transfer_payload = rights_assignment._to_format( ...
Transfer this Right to another owner on the backing persistence layer. Args: rights_assignment_data (dict): Model data for the resulting :class:`~.RightsAssignment` from_user (any, keyword): A user based on the model specified by the persistence l...
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L506-L542
[ "def from_data(cls, data, *, data_format=DataFormat.jsonld, plugin):\n \"\"\"Generic factory for instantiating :attr:`cls` entities\n from their model data. Entities instantiated from this factory\n have yet to be created on the backing persistence layer; see\n :meth:`create` on persisting an entity.\n\...
class Right(TransferrableEntity): """COALA IP's Right entity. Transferrable. A statement of entitlement (i.e. "right") to do something in relation to a :class:`~.Work` or :class:`~.Manifestation`. More specific rights, such as ``PlaybackRights``, ``StreamRights``, etc should be implemented as subc...
COALAIP/pycoalaip
coalaip/models.py
work_model_factory
python
def work_model_factory(*, validator=validators.is_work_model, **kwargs): kwargs['ld_type'] = 'AbstractWork' return _model_factory(validator=validator, **kwargs)
Generate a Work model. Expects ``data``, ``validator``, ``model_cls``, and ``ld_context`` as keyword arguments. Raises: :exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword argument is given.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L241-L252
[ "def _model_factory(*, data=None, model_cls=Model, **kwargs):\n return model_cls(data=data, **kwargs)\n" ]
"""Low level data models for COALA IP entities. Encapsulates the data modelling of COALA IP entities. Supports model validation and the loading of data from a backing persistence layer. .. note:: This module should not be used directly to generate models, unless you are extending the built-ins for your own ...
COALAIP/pycoalaip
coalaip/models.py
manifestation_model_factory
python
def manifestation_model_factory(*, validator=validators.is_manifestation_model, ld_type='CreativeWork', **kwargs): return _model_factory(validator=validator, ld_type=ld_type, **kwargs)
Generate a Manifestation model. Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and ``ld_context`` as keyword arguments.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L255-L262
[ "def _model_factory(*, data=None, model_cls=Model, **kwargs):\n return model_cls(data=data, **kwargs)\n" ]
"""Low level data models for COALA IP entities. Encapsulates the data modelling of COALA IP entities. Supports model validation and the loading of data from a backing persistence layer. .. note:: This module should not be used directly to generate models, unless you are extending the built-ins for your own ...
COALAIP/pycoalaip
coalaip/models.py
right_model_factory
python
def right_model_factory(*, validator=validators.is_right_model, ld_type='Right', **kwargs): return _model_factory(validator=validator, ld_type=ld_type, **kwargs)
Generate a Right model. Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and ``ld_context`` as keyword arguments.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L265-L272
[ "def _model_factory(*, data=None, model_cls=Model, **kwargs):\n return model_cls(data=data, **kwargs)\n" ]
"""Low level data models for COALA IP entities. Encapsulates the data modelling of COALA IP entities. Supports model validation and the loading of data from a backing persistence layer. .. note:: This module should not be used directly to generate models, unless you are extending the built-ins for your own ...
COALAIP/pycoalaip
coalaip/models.py
copyright_model_factory
python
def copyright_model_factory(*, validator=validators.is_copyright_model, **kwargs): kwargs['ld_type'] = 'Copyright' return _model_factory(validator=validator, **kwargs)
Generate a Copyright model. Expects ``data``, ``validator``, ``model_cls``, and ``ld_context`` as keyword arguments. Raises: :exc:`ModelError`: If a non-'Copyright' ``ld_type`` keyword argument is given.
train
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L276-L288
[ "def _model_factory(*, data=None, model_cls=Model, **kwargs):\n return model_cls(data=data, **kwargs)\n" ]
"""Low level data models for COALA IP entities. Encapsulates the data modelling of COALA IP entities. Supports model validation and the loading of data from a backing persistence layer. .. note:: This module should not be used directly to generate models, unless you are extending the built-ins for your own ...
hover2pi/svo_filters
svo_filters/svo.py
color_gen
python
def color_gen(colormap='viridis', key=None, n=15): if colormap in dir(bpal): palette = getattr(bpal, colormap) if isinstance(palette, dict): if key is None: key = list(palette.keys())[0] palette = palette[key] elif callable(palette): pale...
Color generator for Bokeh plots Parameters ---------- colormap: str, sequence The name of the color map Returns ------- generator A generator for the color palette
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L763-L796
null
#!/usr/bin/python # -*- coding: latin-1 -*- """ A Python wrapper for the SVO Filter Profile Service """ from glob import glob import inspect import os import pickle from pkg_resources import resource_filename import warnings import itertools import astropy.table as at import astropy.io.votable as vo import astropy.uni...
hover2pi/svo_filters
svo_filters/svo.py
filters
python
def filters(filter_directory=None, update=False, fmt='table', **kwargs): if filter_directory is None: filter_directory = resource_filename('svo_filters', 'data/filters/') # Get the pickle path and make sure file exists p_path = os.path.join(filter_directory, 'filter_list.p') updated = False ...
Get a list of the available filters Parameters ---------- filter_directory: str The directory containing the filter relative spectral response curves update: bool Check the filter directory for new filters and generate pickle of table fmt: str The format for the returned tab...
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L799-L886
[ "def info(self, fetch=False):\n \"\"\"\n Print a table of info about the current filter\n \"\"\"\n # Get the info from the class\n tp = (int, bytes, bool, str, float, tuple, list, np.ndarray)\n info = [[k, str(v)] for k, v in vars(self).items() if isinstance(v, tp)\n and k not in ['rsr'...
#!/usr/bin/python # -*- coding: latin-1 -*- """ A Python wrapper for the SVO Filter Profile Service """ from glob import glob import inspect import os import pickle from pkg_resources import resource_filename import warnings import itertools import astropy.table as at import astropy.io.votable as vo import astropy.uni...
hover2pi/svo_filters
svo_filters/svo.py
rebin_spec
python
def rebin_spec(spec, wavnew, oversamp=100, plot=False): wave, flux = spec nlam = len(wave) x0 = np.arange(nlam, dtype=float) x0int = np.arange((nlam-1.) * oversamp + 1., dtype=float)/oversamp w0int = np.interp(x0int, x0, wave) spec0int = np.interp(w0int, wave, flux)/oversamp # Set up the bi...
Rebin a spectrum to a new wavelength array while preserving the total flux Parameters ---------- spec: array-like The wavelength and flux to be binned wavenew: array-like The new wavelength array Returns ------- np.ndarray The rebinned flux
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L889-L931
null
#!/usr/bin/python # -*- coding: latin-1 -*- """ A Python wrapper for the SVO Filter Profile Service """ from glob import glob import inspect import os import pickle from pkg_resources import resource_filename import warnings import itertools import astropy.table as at import astropy.io.votable as vo import astropy.uni...
hover2pi/svo_filters
svo_filters/svo.py
Filter.apply
python
def apply(self, spectrum, plot=False): # Convert to filter units if possible f_units = 1. if hasattr(spectrum[0], 'unit'): spectrum[0] = spectrum[0].to(self.wave_units) if hasattr(spectrum[1], 'unit'): spectrum[1] = spectrum[1].to(self.flux_units) f_un...
Apply the filter to the given [W, F], or [W, F, E] spectrum Parameters ---------- spectrum: array-like The wavelength [um] and flux of the spectrum to apply the filter to plot: bool Plot the original and filtered spectrum Returns ----...
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L232-L324
[ "def color_gen(colormap='viridis', key=None, n=15):\n \"\"\"Color generator for Bokeh plots\n\n Parameters\n ----------\n colormap: str, sequence\n The name of the color map\n\n Returns\n -------\n generator\n A generator for the color palette\n \"\"\"\n if colormap in dir(b...
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.bin
python
def bin(self, n_bins=1, pixels_per_bin=None, wave_min=None, wave_max=None): # Get wavelength limits if wave_min is not None: self.wave_min = wave_min if wave_max is not None: self.wave_max = wave_max # Trim the wavelength by the given min and max raw_wave...
Break the filter up into bins and apply a throughput to each bin, useful for G141, G102, and other grisms Parameters ---------- n_bins: int The number of bins to dice the throughput curve into pixels_per_bin: int (optional) The number of channels per bin,...
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L326-L376
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.centers
python
def centers(self): # Get the bin centers w_cen = np.nanmean(self.wave.value, axis=1) f_cen = np.nanmean(self.throughput, axis=1) return np.asarray([w_cen, f_cen])
A getter for the wavelength bin centers and average fluxes
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L379-L385
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.flux_units
python
def flux_units(self, units): # Check that the units are valid dtypes = (q.core.PrefixUnit, q.quantity.Quantity, q.core.CompositeUnit) if not isinstance(units, dtypes): raise ValueError(units, "units not understood.") # Check that the units changed if units != self.fl...
A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L393-L415
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.info
python
def info(self, fetch=False): # Get the info from the class tp = (int, bytes, bool, str, float, tuple, list, np.ndarray) info = [[k, str(v)] for k, v in vars(self).items() if isinstance(v, tp) and k not in ['rsr', 'raw', 'centers'] and not k.startswith('_')] # Make the ta...
Print a table of info about the current filter
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L417-L436
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.load_TopHat
python
def load_TopHat(self, wave_min, wave_max, pixels_per_bin=100): # Get min, max, effective wavelengths and width self.pixels_per_bin = pixels_per_bin self.n_bins = 1 self._wave_units = q.AA wave_min = wave_min.to(self.wave_units) wave_max = wave_max.to(self.wave_units) ...
Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use n_pixels: int ...
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L438-L492
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.load_txt
python
def load_txt(self, filepath): self.raw = np.genfromtxt(filepath, unpack=True) # Convert to Angstroms if microns if self.raw[0][-1] < 100: self.raw[0] = self.raw[0] * 10000 self.WavelengthUnit = str(q.AA) self.ZeroPointUnit = str(q.erg/q.s/q.cm**2/q.AA) x, f ...
Load the filter from a txt file Parameters ---------- file: str The filepath
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L494-L546
[ "def rebin_spec(spec, wavnew, oversamp=100, plot=False):\n \"\"\"\n Rebin a spectrum to a new wavelength array while preserving\n the total flux\n\n Parameters\n ----------\n spec: array-like\n The wavelength and flux to be binned\n wavenew: array-like\n The new wavelength array\n...
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...