signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def transmit_agnocomplete_context(self):
user = super(AgnocompleteContextQuerysetMixin, self).transmit_agnocomplete_context()<EOL>if user:<EOL><INDENT>self.queryset = self.agnocomplete.get_queryset()<EOL><DEDENT>return user<EOL>
We'll reset the current queryset only if the user is set.
f2527:c1:m0
@property<EOL><INDENT>def empty_value(self):<DEDENT>
return []<EOL>
Default empty value for this field.
f2527:c4:m1
def clear_list_value(self, value):
<EOL>if not value:<EOL><INDENT>return self.empty_value<EOL><DEDENT>if self.clean_empty:<EOL><INDENT>value = [v for v in value if v]<EOL><DEDENT>return value or self.empty_value<EOL>
Clean the argument value to eliminate None or Falsy values if needed.
f2527:c4:m3
@property<EOL><INDENT>def empty_value(self):<DEDENT>
return self.queryset.model.objects.none()<EOL>
Return default empty value as a Queryset. This value can be added via the `|` operator, so we surely need a queryset and not a list.
f2527:c6:m0
def create_item(self, **kwargs):
item, created = self.queryset.model.objects.get_or_create(**kwargs)<EOL>return item<EOL>
Return a model instance created from kwargs.
f2527:c6:m1
def extra_create_kwargs(self):
return {}<EOL>
Return extra arguments to create the new model instance. You can pass context-related arguments in the dictionary, or default values.
f2527:c6:m2
def create_new_values(self):
model = self.queryset.model<EOL>pks = []<EOL>extra_create_kwargs = self.extra_create_kwargs()<EOL>for value in self._new_values:<EOL><INDENT>create_kwargs = {self.create_field: value}<EOL>create_kwargs.update(extra_create_kwargs)<EOL>new_item = self.create_item(**create_kwargs)<EOL>pks.append(new_item.pk)<EOL><DEDENT>return model.objects.filter(pk__in=pks)<EOL>
Create values created by the user input. Return the model instances QS.
f2527:c6:m3
def clean(self, value):
if not self.create:<EOL><INDENT>return super(AgnocompleteModelMultipleField, self).clean(value)<EOL><DEDENT>value = self.clear_list_value(value)<EOL>pks = [v for v in value if v.isdigit()]<EOL>self._new_values = [v for v in value if not v.isdigit()]<EOL>qs = super(AgnocompleteModelMultipleField, self).clean(pks)<EOL>return qs<EOL>
Clean the field values.
f2527:c6:m4
def get_namespace():
return getattr(settings, '<STR_LIT>', '<STR_LIT>')<EOL>
Return the agnocomplete view namespace. Default value is "agnocomplete", but it can be overridden using the ``AGNOCOMPLETE_NAMESPACE`` settings variable.
f2528:m0
def autodiscover():
autodiscover_modules('<STR_LIT>')<EOL>
Auto-discover INSTALLED_APPS agnocomplete modules.
f2528:m1
def register(klass):
logger.info("<STR_LIT>".format(klass.__name__))<EOL>AGNOCOMPLETE_REGISTRY[klass.slug] = klass<EOL>
Register a class into the agnocomplete registry.
f2530:m0
def get_agnocomplete_registry():
return AGNOCOMPLETE_REGISTRY<EOL>
Get the registered agnostic autocompletes.
f2530:m1
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):<EOL><INDENT>func = classmethod(func)<EOL><DEDENT>return ClassPropertyDescriptor(func)<EOL>
Decorator: the given function will become a class property. e.g:: class SafeClass(object): @classproperty def safe(cls): return True class UnsafeClass(object): @classproperty def safe(cls): return False
f2531:m0
def load_settings_sizes():
page_size = AGNOCOMPLETE_DEFAULT_PAGESIZE<EOL>settings_page_size = getattr(<EOL>settings, '<STR_LIT>', None)<EOL>page_size = settings_page_size or page_size<EOL>page_size_min = AGNOCOMPLETE_MIN_PAGESIZE<EOL>settings_page_size_min = getattr(<EOL>settings, '<STR_LIT>', None)<EOL>page_size_min = settings_page_size_min or page_size_min<EOL>page_size_max = AGNOCOMPLETE_MAX_PAGESIZE<EOL>settings_page_size_max = getattr(<EOL>settings, '<STR_LIT>', None)<EOL>page_size_max = settings_page_size_max or page_size_max<EOL>query_size = AGNOCOMPLETE_DEFAULT_QUERYSIZE<EOL>settings_query_size = getattr(<EOL>settings, '<STR_LIT>', None)<EOL>query_size = settings_query_size or query_size<EOL>query_size_min = AGNOCOMPLETE_MIN_QUERYSIZE<EOL>settings_query_size_min = getattr(<EOL>settings, '<STR_LIT>', None)<EOL>query_size_min = settings_query_size_min or query_size_min<EOL>return (<EOL>page_size, page_size_min, page_size_max,<EOL>query_size, query_size_min,<EOL>)<EOL>
Load sizes from settings or fallback to the module constants
f2531:m1
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):<EOL><INDENT>func = classmethod(func)<EOL><DEDENT>self.fset = func<EOL>return self<EOL>
Setter: the decorated method will become a class property.
f2531:c0:m3
@classproperty<EOL><INDENT>def slug(cls):<DEDENT>
return cls.__name__<EOL>
Return the key used in the register, used as a slug for the URL. You can override this by adding a class property.
f2531:c1:m2
def get_page_size(self):
return self._page_size<EOL>
Return the computed page_size It takes into account: * class variables * constructor arguments, * settings * fallback to the module constants if needed.
f2531:c1:m4
def get_query_size(self):
return self._query_size<EOL>
Return the computed default query size It takes into account: * class variables * settings, * fallback to the module constants
f2531:c1:m5
def get_query_size_min(self):
return self._query_size_min<EOL>
Return the computed minimum query size It takes into account: * class variables * settings, * fallback to the module constants
f2531:c1:m6
@abstractmethod<EOL><INDENT>def selected(self, ids):<DEDENT>
pass<EOL>
Return the values (as a tuple of pairs) for the ids provided
f2531:c1:m9
def is_valid_query(self, query):
<EOL>if not query:<EOL><INDENT>return False<EOL><DEDENT>if len(query) < self.get_query_size_min():<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
Return True if the search query is valid. e.g.: * not empty, * not too short,
f2531:c1:m10
def selected(self, ids):
result = copy(self.choices)<EOL>result = filter(lambda x: x[<NUM_LIT:0>] in ids, result)<EOL>return list(result)<EOL>
Return the selected options as a list of tuples
f2531:c2:m3
def get_model(self):
if hasattr(self, '<STR_LIT>') and self.model:<EOL><INDENT>return self.model<EOL><DEDENT>try:<EOL><INDENT>none = self.get_queryset().none()<EOL>return none.model<EOL><DEDENT>except Exception:<EOL><INDENT>raise ImproperlyConfigured(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>
Return the class Model used by this Agnocomplete
f2531:c3:m2
def get_model_queryset(self):
return self.get_model().objects.all()<EOL>
Return an unfiltered complete model queryset. To be used for the select Input initialization
f2531:c3:m3
def get_field_name(self):
if hasattr(self, '<STR_LIT>') andhasattr(self.agnocomplete_field, '<STR_LIT>'):<EOL><INDENT>return self.agnocomplete_field.to_field_name or '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'<EOL>
Return the model field name to be used as a value, or 'pk' if unset
f2531:c3:m4
def _construct_qs_filter(self, field_name):
if field_name.startswith('<STR_LIT>'):<EOL><INDENT>return "<STR_LIT>" % field_name[<NUM_LIT:1>:]<EOL><DEDENT>elif field_name.startswith('<STR_LIT:=>'):<EOL><INDENT>return "<STR_LIT>" % field_name[<NUM_LIT:1>:]<EOL><DEDENT>elif field_name.startswith('<STR_LIT:@>'):<EOL><INDENT>return "<STR_LIT>" % field_name[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % field_name<EOL><DEDENT>
Using a field name optionnaly prefixed by `^`, `=`, `@`, return a case-insensitive filter condition name usable as a queryset `filter()` keyword argument.
f2531:c4:m1
def get_queryset_filters(self, query):
conditions = Q()<EOL>for field_name in self.fields:<EOL><INDENT>conditions |= Q(**{<EOL>self._construct_qs_filter(field_name): query<EOL>})<EOL><DEDENT>return conditions<EOL>
Return the filtered queryset
f2531:c4:m3
def paginate(self, qs):
return qs[:self.get_page_size()]<EOL>
Paginate a given Queryset
f2531:c4:m4
@property<EOL><INDENT>def _final_queryset(self):<DEDENT>
if self.__final_queryset is None:<EOL><INDENT>return None<EOL><DEDENT>return self.paginate(self.__final_queryset)<EOL>
Paginated final queryset
f2531:c4:m5
def item(self, current_item):
return {<EOL>'<STR_LIT:value>': text(getattr(current_item, self.get_field_name())),<EOL>'<STR_LIT:label>': self.label(current_item)<EOL>}<EOL>
Return the current item. @param current_item: Current item @type param: django.models @return: Value and label of the current item @rtype : dict
f2531:c4:m8
def label(self, current_item):
return text(current_item)<EOL>
Return a label for the current item. @param current_item: Current item @type param: django.models @return: Label of the current item @rtype : text
f2531:c4:m9
def build_extra_filtered_queryset(self, queryset, **kwargs):
<EOL>return queryset<EOL>
Apply eventual queryset filters, based on the optional extra arguments passed to the query. By default, this method returns the queryset "verbatim". You can override or overwrite this to perform custom filter on this QS. * `queryset`: it's the final queryset build using the search terms. * `kwargs`: this dictionary contains the extra arguments passed to the agnocomplete class.
f2531:c4:m10
def build_filtered_queryset(self, query, **kwargs):
<EOL>qs = self.get_queryset()<EOL>qs = qs.filter(self.get_queryset_filters(query))<EOL>return self.build_extra_filtered_queryset(qs, **kwargs)<EOL>
Build and return the fully-filtered queryset
f2531:c4:m11
def items(self, query=None, **kwargs):
<EOL>if not query:<EOL><INDENT>self.__final_queryset = self.get_model().objects.none()<EOL>return self.serialize(self.__final_queryset)<EOL><DEDENT>if len(query) < self.get_query_size_min():<EOL><INDENT>self.__final_queryset = self.get_model().objects.none()<EOL>return self.serialize(self.__final_queryset)<EOL><DEDENT>if self.requires_authentication:<EOL><INDENT>if not self.user:<EOL><INDENT>raise AuthenticationRequiredAgnocompleteException(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if not self.user.is_authenticated:<EOL><INDENT>raise AuthenticationRequiredAgnocompleteException(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>qs = self.build_filtered_queryset(query, **kwargs)<EOL>self.__final_queryset = qs<EOL>return self.serialize(qs)<EOL>
Return the items to be sent to the client
f2531:c4:m12
def selected(self, ids):
<EOL>if self.get_field_name() == '<STR_LIT>':<EOL><INDENT>ids = filter(lambda x: "<STR_LIT:{}>".format(x).isdigit(), copy(ids))<EOL><DEDENT>else:<EOL><INDENT>ids = filter(lambda x: len("<STR_LIT:{}>".format(x)) > <NUM_LIT:0>, copy(ids))<EOL><DEDENT>qs = self.get_model_queryset().filter(<EOL>**{'<STR_LIT>'.format(self.get_field_name()): ids})<EOL>result = []<EOL>for item in qs:<EOL><INDENT>item_repr = self.item(item)<EOL>result.append(<EOL>(item_repr['<STR_LIT:value>'], item_repr['<STR_LIT:label>'])<EOL>)<EOL><DEDENT>return result<EOL>
Return the selected options as a list of tuples
f2531:c4:m13
def get_http_method_arg_name(self):
if self.method == '<STR_LIT>':<EOL><INDENT>arg_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>arg_name = '<STR_LIT:data>'<EOL><DEDENT>return getattr(requests, self.method), arg_name<EOL>
Return the HTTP function to call and the params/data argument name
f2531:c5:m4
def http_call(self, url=None, **kwargs):
if not url:<EOL><INDENT>url = self.search_url<EOL><DEDENT>http_func, arg_name = self.get_http_method_arg_name()<EOL>_kwargs = {<EOL>arg_name: kwargs,<EOL>}<EOL>response = http_func(<EOL>url=url.format(**kwargs),<EOL>headers=self.get_http_headers(),<EOL>**_kwargs<EOL>)<EOL>if response.status_code != <NUM_LIT:200>:<EOL><INDENT>logger.warning('<STR_LIT>', response.url)<EOL>response.raise_for_status()<EOL><DEDENT>return response.json()<EOL>
Call the target URL via HTTP and return the JSON result
f2531:c5:m5
def get_http_headers(self):
return {}<EOL>
Return a dictionary that will be added to the HTTP request to the API You can overwrite this method, that return an empty dict by default.
f2531:c5:m7
def get_http_result(self, http_result):
return http_result.get(self.data_key, [])<EOL>
Return an iterable with all the result items in. You can override/overwrite this method to adapt it to the payload returned by the 3rd party API.
f2531:c5:m8
def get_http_call_kwargs(self, query, **kwargs):
return {'<STR_LIT:q>': query}<EOL>
Return the HTTP query arguments. You can override this method to pass further arguments corresponding to your search_url.
f2531:c5:m9
def validate(self, value):
url = self.get_item_url(value)<EOL>try:<EOL><INDENT>data = self.http_call(url=url)<EOL><DEDENT>except requests.HTTPError:<EOL><INDENT>raise ItemNotFound()<EOL><DEDENT>data = self.get_http_result(data)<EOL>try:<EOL><INDENT>self.item(data)<EOL><DEDENT>except SkipItem:<EOL><INDENT>raise ItemNotFound()<EOL><DEDENT>return value<EOL>
From a value available on the remote server, the method returns the complete item matching the value. If case the value is not available on the server side or filtered through :meth:`item`, the class:`agnocomplete.exceptions.ItemNotFound` is raised.
f2531:c5:m12
def allow_create(function):
@wraps(function)<EOL>def _wrapped_func(*args, **kwargs):<EOL><INDENT>form = args[<NUM_LIT:0>]<EOL>if isinstance(form, (Form, ModelForm)):<EOL><INDENT>if not form.is_valid():<EOL><INDENT>return function(*args, **kwargs)<EOL><DEDENT>for k, field in form.fields.items():<EOL><INDENT>if getattr(field, '<STR_LIT>', False)and getattr(field, '<STR_LIT>', None):<EOL><INDENT>new_values = field.create_new_values()<EOL>form.cleaned_data[k] = form.cleaned_data[k] | new_values<EOL><DEDENT><DEDENT><DEDENT>return function(*args, **kwargs)<EOL><DEDENT>return _wrapped_func<EOL>
Decorate the `form_valid` method in a Create/Update class to create new values if necessary. .. warning:: Make sure that this decorator **only** decorates the ``form_valid()`` method and **only** this one.
f2533:m0
def ready(self):
from . import autodiscover<EOL>autodiscover()<EOL>
Initialize the autodiscover when ready
f2535:c0:m0
@require_GET<EOL>def convert_schema_list(request, *args, **kwargs):
search_term = request.GET.get('<STR_LIT:q>', None)<EOL>result = _search(search_term, convert_data)<EOL>response = json.dumps(result.get('<STR_LIT:data>', []))<EOL>logger.debug(<EOL>'<STR_LIT>', search_term)<EOL>logger.debug('<STR_LIT>', response)<EOL>return HttpResponse(response)<EOL>
Return a list of items not embedded in a dict.
f2536:m7
@require_GET<EOL>def errors(request, *args, **kwargs):
search_term = request.GET.get('<STR_LIT:q>', None)<EOL>if '<STR_LIT>' in search_term:<EOL><INDENT>return HttpResponseBadRequest(MESSAGE_400)<EOL><DEDENT>elif '<STR_LIT>' in search_term:<EOL><INDENT>return HttpResponseForbidden(MESSAGE_403)<EOL><DEDENT>elif '<STR_LIT>' in search_term:<EOL><INDENT>return HttpResponseNotFound(MESSAGE_404)<EOL><DEDENT>elif '<STR_LIT>' in search_term:<EOL><INDENT>return HttpResponseNotAllowed(['<STR_LIT>'], MESSAGE_405)<EOL><DEDENT>return HttpResponseServerError(MESSAGE_500)<EOL>
A dummy view that will throw errors. It'll throw any HTTP error that is contained in the search query.
f2536:m11
@require_GET<EOL>def atomic_item(request, pk):
data = None<EOL>for item in DATABASE:<EOL><INDENT>if text(item['<STR_LIT>']) == text(pk):<EOL><INDENT>data = convert_data(item)<EOL>break<EOL><DEDENT><DEDENT>if not data:<EOL><INDENT>raise Http404("<STR_LIT>".format(pk))<EOL><DEDENT>logger.debug('<STR_LIT>', pk)<EOL>result = {'<STR_LIT:data>': data}<EOL>response = json.dumps(result)<EOL>logger.debug('<STR_LIT>', response)<EOL>return HttpResponse(response)<EOL>
Similar to `item` but does not return a list
f2536:m13
def extra_create_kwargs(self):
user = self.get_agnocomplete_context()<EOL>if user:<EOL><INDENT>_, domain = user.email.split('<STR_LIT:@>')<EOL>return {<EOL>'<STR_LIT>': domain<EOL>}<EOL><DEDENT>return {}<EOL>
Inject the domain of the current user in the new model instances.
f2552:c0:m0
def create_item(self, **kwargs):
return self.queryset.model.objects.create(**kwargs)<EOL>
Return the created model instance.
f2552:c1:m0
def grep(rootdir, searched):
to_inspect = []<EOL>for root, dirs, files in os.walk(rootdir):<EOL><INDENT>for _file in files:<EOL><INDENT>if _file.endswith('<STR_LIT>'):<EOL><INDENT>to_inspect.append(join(root, _file))<EOL><DEDENT><DEDENT><DEDENT>to_check = ((_file, open(_file, '<STR_LIT:r>').read()) for _file in to_inspect)<EOL>to_check = filter(lambda item: searched in item[<NUM_LIT:1>], to_check)<EOL>to_check = map(lambda item: item[<NUM_LIT:0>], to_check)<EOL>return to_check<EOL>
grep -l <searched>
f2562:m0
def __call__(self, var, default=NOTSET, cast=None, force=True):
return self._get(var, default=default, cast=cast, force=force)<EOL>
Function interface Once the environment has been initialised, it can be called as a function. This is necessary to provide custom casting, or it can sometimes be preferred for consistency. Examples: Casting an environment variable: >>> env = Environment({'MY_VAR': '1'}) >>> env('MY_VAR', cast=int) 1 Providing a default: >>> env = Environment({}) >>> env('ANOTHER_VAR', default='value') "value" Args: var (`str`): The name of the environment variable default: The value to return if the environment variable does not exist cast: type or function for casting environment variable. See casting force (`bool`): Whether to force casting of the default value Returns: The environment variable if it exists, otherwise default Raises: ImproperlyConfigured
f2565:c0:m1
def __contains__(self, var):
return var in self.environ<EOL>
Test if an environment variable exists Allows using the ``in`` operator to test if an environment variable exists. Examples: >>> env = Environment({'MY_VAR': '1'}) >>> 'MY_VAR' in env True >>> 'ANOTHER_VAR' in env False
f2565:c0:m2
def bool(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=bool, force=force)<EOL>
Convenience method for casting to a bool
f2565:c0:m3
def float(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=float, force=force)<EOL>
Convenience method for casting to a float
f2565:c0:m4
def int(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=int, force=force)<EOL>
Convenience method for casting to an int
f2565:c0:m5
def str(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=text_type, force=force)<EOL>
Convenience method for casting to a str
f2565:c0:m6
def tuple(self, var, default=NOTSET, cast=None, force=True):
return self._get(var, default=default, cast=(cast,), force=force)<EOL>
Convenience method for casting to a tuple Note: Casting
f2565:c0:m7
def list(self, var, default=NOTSET, cast=None, force=True):
return self._get(var, default=default, cast=[cast], force=force)<EOL>
Convenience method for casting to a list Note: Casting
f2565:c0:m8
def set(self, var, default=NOTSET, cast=None, force=True):
return self._get(var, default=default, cast={cast}, force=force)<EOL>
Convenience method for casting to a set Note: Casting
f2565:c0:m9
def dict(self, var, default=NOTSET, cast=None, force=True):
return self._get(var, default=default, cast={str: cast}, force=force)<EOL>
Convenience method for casting to a dict Note: Casting
f2565:c0:m10
def decimal(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=Decimal, force=force)<EOL>
Convenience method for casting to a decimal.Decimal Note: Casting
f2565:c0:m11
def json(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=json.loads, force=force)<EOL>
Get environment variable, parsed as a json string
f2565:c0:m12
def url(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=urlparse.urlparse,<EOL>force=force)<EOL>
Get environment variable, parsed with urlparse/urllib.parse
f2565:c0:m13
def setUp(self):
self.blog = Blog.objects.first()<EOL>self.apples = Section.objects.create(name="<STR_LIT>", slug="<STR_LIT>")<EOL>self.oranges = Section.objects.create(name="<STR_LIT>", slug="<STR_LIT>")<EOL>self.user = self.make_user("<STR_LIT>")<EOL>self.markup = "<STR_LIT>"<EOL>self.orange_title = "<STR_LIT>"<EOL>self.orange_slug = slugify(self.orange_title)<EOL>self.orange_post = Post.objects.create(blog=self.blog,<EOL>section=self.oranges,<EOL>title=self.orange_title,<EOL>slug=self.orange_slug,<EOL>author=self.user,<EOL>markup=self.markup,<EOL>state=Post.STATE_CHOICES[-<NUM_LIT:1>][<NUM_LIT:0>])<EOL>self.apple_title = "<STR_LIT>"<EOL>self.apple_slug = slugify(self.apple_title)<EOL>self.apple_post = Post.objects.create(blog=self.blog,<EOL>section=self.apples,<EOL>title=self.apple_title,<EOL>slug=self.apple_slug,<EOL>author=self.user,<EOL>markup=self.markup,<EOL>state=Post.STATE_CHOICES[-<NUM_LIT:1>][<NUM_LIT:0>])<EOL>
Create default Sections and Posts.
f2573:c0:m0
@require_POST<EOL>def ajax_preview(request, **kwargs):
data = {<EOL>"<STR_LIT:html>": render_to_string("<STR_LIT>", {<EOL>"<STR_LIT:content>": parse(request.POST.get("<STR_LIT>"))<EOL>})<EOL>}<EOL>return JsonResponse(data)<EOL>
Currently only supports markdown
f2595:m2
def get_blog(self, **kwargs):
from .models import Blog<EOL>return Blog.objects.first()<EOL>
By default there is a single Blog. In the event that there are multiple and/or those blogs are scoped by an external model, override this method to return the right blog given the `kwargs`. These `kwargs` are the kwargs that come from the URL definition for the view.
f2597:c0:m0
def response_cannot_manage(self, request, *args, **kwargs):
raise Http404()<EOL>
The response to return when `can_manage` returns `False` for all of the manage views. You may want to return a `redirect` or raise some HTTP error.
f2597:c0:m4
def get_text(self, node):
try:<EOL><INDENT>return node.children[<NUM_LIT:0>].content or "<STR_LIT>"<EOL><DEDENT>except (AttributeError, IndexError):<EOL><INDENT>return node.content or "<STR_LIT>"<EOL><DEDENT>
Try to emit whatever text is in the node.
f2605:c1:m1
def default_emit(self, node):
raise TypeError<EOL>
Fallback function for emitting unknown nodes.
f2605:c1:m24
def emit_children(self, node):
return "<STR_LIT>".join([self.emit_node(child) for child in node.children])<EOL>
Emit all the children of a node.
f2605:c1:m25
def emit_node(self, node):
emit = getattr(self, "<STR_LIT>" % node.kind, self.default_emit)<EOL>return emit(node)<EOL>
Emit a single node.
f2605:c1:m26
def emit(self):
return self.emit_node(self.root)<EOL>
Emit the document represented by self.root DOM tree.
f2605:c1:m27
def current(self):
return self.revisions.exclude(published=None).order_by("<STR_LIT>")[<NUM_LIT:0>]<EOL>
the currently visible (latest published) revision
f2607:c2:m7
@property<EOL><INDENT>def sharable_url(self):<DEDENT>
if not self.is_published or self.is_future_published:<EOL><INDENT>if self.secret_key:<EOL><INDENT>kwargs = self.blog.scoping_url_kwargs<EOL>kwargs.update({"<STR_LIT>": self.secret_key})<EOL>return reverse("<STR_LIT>", kwargs=kwargs)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self.get_absolute_url()<EOL><DEDENT>
An url to reach this post (there is a secret url for sharing unpublished posts to outside users).
f2607:c2:m11
def generate_synonym(self, input_word):
results = []<EOL>results.append(input_word)<EOL>synset = wordnet.synsets(input_word)<EOL>for i in synset:<EOL><INDENT>index = <NUM_LIT:0><EOL>syn = i.name.split('<STR_LIT:.>')<EOL>if syn[index]!= input_word:<EOL><INDENT>name = syn[<NUM_LIT:0>]<EOL>results.append(PataLib().strip_underscore(name))<EOL><DEDENT>else:<EOL><INDENT>index = index + <NUM_LIT:1><EOL><DEDENT><DEDENT>results = {'<STR_LIT:input>' : input_word, '<STR_LIT>' : results, '<STR_LIT>' : '<STR_LIT>'} <EOL>return results<EOL>
Generate Synonym using a WordNet synset.
f2631:c0:m0
def generate_clinamen(self, input_word, list_of_dict_words, swerve):
results = []<EOL>selected_list = []<EOL>for i in list_of_dict_words: <EOL><INDENT>if len(i) < len(input_word)+<NUM_LIT:1> and len(i) > len(input_word)/<NUM_LIT:2>:<EOL><INDENT>if '<STR_LIT:_>' not in i:<EOL><INDENT>selected_list.append(i)<EOL><DEDENT><DEDENT><DEDENT>for i in selected_list:<EOL><INDENT>match = self.damerau_levenshtein_distance(input_word,i)<EOL>if match == swerve:<EOL><INDENT>results.append(i)<EOL><DEDENT><DEDENT>results = {'<STR_LIT:input>' : input_word, '<STR_LIT>' : results, '<STR_LIT>' : '<STR_LIT>'} <EOL>return results<EOL>
Generate a clinamen. Here we looks for words via the damerau levenshtein distance with a distance of 2.
f2632:c0:m0
def damerau_levenshtein_distance(self, s1, s2):
d = {}<EOL>lenstr1 = len(s1)<EOL>lenstr2 = len(s2)<EOL>for i in xrange(-<NUM_LIT:1>,lenstr1+<NUM_LIT:1>):<EOL><INDENT>d[(i,-<NUM_LIT:1>)] = i+<NUM_LIT:1><EOL><DEDENT>for j in xrange(-<NUM_LIT:1>,lenstr2+<NUM_LIT:1>):<EOL><INDENT>d[(-<NUM_LIT:1>,j)] = j+<NUM_LIT:1><EOL><DEDENT>for i in xrange(lenstr1):<EOL><INDENT>for j in xrange(lenstr2):<EOL><INDENT>if s1[i] == s2[j]:<EOL><INDENT>cost = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>cost = <NUM_LIT:1><EOL><DEDENT>d[(i,j)] = min(<EOL>d[(i-<NUM_LIT:1>,j)] + <NUM_LIT:1>, <EOL>d[(i,j-<NUM_LIT:1>)] + <NUM_LIT:1>, <EOL>d[(i-<NUM_LIT:1>,j-<NUM_LIT:1>)] + cost, <EOL>)<EOL>if i and j and s1[i]==s2[j-<NUM_LIT:1>] and s1[i-<NUM_LIT:1>] == s2[j]:<EOL><INDENT>d[(i,j)] = min (d[(i,j)], d[i-<NUM_LIT:2>,j-<NUM_LIT:2>] + cost) <EOL><DEDENT><DEDENT><DEDENT>return d[lenstr1-<NUM_LIT:1>,lenstr2-<NUM_LIT:1>]<EOL>
Dervied algorithm from the following website: https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/ Gives us the distance between two words.
f2632:c0:m1
def generate_syzygy(self, input_word):
results = []<EOL>synset = wordnet.synsets(input_word)<EOL>for i in synset:<EOL><INDENT>if i.hypernyms():<EOL><INDENT>hyp = i.hypernyms()[<NUM_LIT:0>].name.split('<STR_LIT:.>')<EOL>if '<STR_LIT:_>' in hyp[<NUM_LIT:0>]:<EOL><INDENT>hyp[<NUM_LIT:0>] = PataLib().strip_underscore(hyp[<NUM_LIT:0>])<EOL><DEDENT>syns = wordnet.synsets(hyp[<NUM_LIT:0>])<EOL>if len(syns) > <NUM_LIT:0>:<EOL><INDENT>name = syns[<NUM_LIT:0>].name.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>results.append(PataLib().strip_underscore(name))<EOL><DEDENT><DEDENT><DEDENT>results = {'<STR_LIT:input>' : input_word, '<STR_LIT>' : results, '<STR_LIT>' : '<STR_LIT>'} <EOL>return results<EOL>
Generate a syzygy. Here we generate a list of hypernyms associated with an input word. Using the hypernym we then generate another synonym. For example: The input word 'weed' will result in a syzgy of 'band' as in rock band.
f2633:c0:m0
def strip_underscore(self, input_word):
if '<STR_LIT:_>' in input_word:<EOL><INDENT>return input_word.replace('<STR_LIT:_>','<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>return input_word<EOL><DEDENT>
Remove underscore from word
f2634:c0:m0
def palindrome(self, input_word):
return str(input_word) == str(input_word)[::-<NUM_LIT:1>]<EOL>
Check if string is a plaindrome
f2634:c0:m1
def generate_anomaly(self, input_word, list_of_dict_words, num):
results = []<EOL>for i in range(<NUM_LIT:0>,num):<EOL><INDENT>index = randint(<NUM_LIT:0>,len(list_of_dict_words)-<NUM_LIT:1>)<EOL>name = list_of_dict_words[index]<EOL>if name != input_word and name not in results:<EOL><INDENT>results.append(PataLib().strip_underscore(name))<EOL><DEDENT>else:<EOL><INDENT>i = i +<NUM_LIT:1><EOL><DEDENT><DEDENT>results = {'<STR_LIT:input>' : input_word, '<STR_LIT>' : results, '<STR_LIT>' : '<STR_LIT>'} <EOL>return results<EOL>
Generate an anomaly. This is done via a Psuedo-random number generator.
f2635:c0:m0
def generate_antonym(self, input_word):
results = []<EOL>synset = wordnet.synsets(input_word)<EOL>for i in synset:<EOL><INDENT>if i.pos in ['<STR_LIT:n>','<STR_LIT:v>']:<EOL><INDENT>for j in i.lemmas:<EOL><INDENT>if j.antonyms():<EOL><INDENT>name = j.antonyms()[<NUM_LIT:0>].name<EOL>results.append(PataLib().strip_underscore(name))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>results = {'<STR_LIT:input>' : input_word, '<STR_LIT>' : results, '<STR_LIT>' : '<STR_LIT>'} <EOL>return results<EOL>
Generate an antonym using a Synset and its lemmas.
f2637:c0:m0
def root(self, _):
return JsonResponse(<EOL>{<EOL>"<STR_LIT:name>": getattr(settings,<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"),<EOL>"<STR_LIT:version>": annotator.__version__<EOL>})<EOL>
Implements the `root <http://docs.annotatorjs.org/en/v1.2.x/storage.html#root>`_ endpoint. :param _: :class:`rest_framework.request.Request` object—ignored here. :return: API information :class:`rest_framework.response.Response`.
f2644:c0:m0
def search(self, _):
queryset = super(AnnotationViewSet, self).filter_queryset(<EOL>self.get_queryset())<EOL>serializer = self.get_serializer(queryset, many=True)<EOL>return Response({<EOL>"<STR_LIT>": len(serializer.data),<EOL>"<STR_LIT>": serializer.data<EOL>})<EOL>
Implements the `search <http://docs.annotatorjs.org/en/v1.2.x/storage.html#search>`_ endpoint. We rely on the behaviour of the ``filter_backends`` to manage the actual filtering of search results. :param _: :class:`rest_framework.request.Request` object—ignored here as we rely on the ``filter_backends``. :return: filtered :class:`rest_framework.response.Response`.
f2644:c0:m1
def get_success_headers(self, data):
headers = super(AnnotationViewSet, self).get_success_headers(data)<EOL>url = urlresolvers.reverse("<STR_LIT>",<EOL>kwargs={"<STR_LIT>": data["<STR_LIT:id>"]})<EOL>headers.update({"<STR_LIT>": self.request.build_absolute_uri(url)})<EOL>return headers<EOL>
As per the *Annotator* documentation regarding the `create <http://docs.annotatorjs.org/en/v1.2.x/storage.html#create>`_ and `update <http://docs.annotatorjs.org/en/v1.2.x/storage.html#update>`_ endpoints, we must return an absolute URL in the ``Location`` header. :param data: serialized object. :return: :class:`dict` of HTTP headers.
f2644:c0:m2
def create(self, request, *args, **kwargs):
response = super(AnnotationViewSet, self).create(request,<EOL>*args,<EOL>**kwargs)<EOL>response.data = None<EOL>response.status_code = status.HTTP_303_SEE_OTHER<EOL>return response<EOL>
See the *Annotator* documentation regarding the `create <http://docs.annotatorjs.org/en/v1.2.x/storage.html#create>`_ endpoint. :param request: incoming :class:`rest_framework.request.Request`. :return: 303 :class:`rest_framework.response.Response`.
f2644:c0:m3
def update(self, request, *args, **kwargs):
response = super(AnnotationViewSet, self).update(request,<EOL>*args,<EOL>**kwargs)<EOL>for h, v in self.get_success_headers(response.data).items():<EOL><INDENT>response[h] = v<EOL><DEDENT>response.data = None<EOL>response.status_code = status.HTTP_303_SEE_OTHER<EOL>return response<EOL>
See the *Annotator* documentation regarding the `update <http://docs.annotatorjs.org/en/v1.2.x/storage.html#update>`_ endpoint. :param request: incoming :class:`rest_framework.request.Request`. :return: 303 :class:`rest_framework.response.Response`.
f2644:c0:m4
def is_ipv4(entry):
try:<EOL><INDENT>if socket.inet_aton(entry):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except socket.error:<EOL><INDENT>return False<EOL><DEDENT>
Check if the string provided is a valid ipv4 address :param entry: A string representation of an IP address :return: True if valid, False if invalid
f2655:m0
def is_ipv6(entry):
try:<EOL><INDENT>if socket.inet_pton(socket.AF_INET6, entry):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except socket.error:<EOL><INDENT>return False<EOL><DEDENT>
Check if the string provided is a valid ipv6 address :param entry: A string representation of an IP address :return: True if valid, False if invalid
f2655:m1
def valid_hostnames(hostname_list):
for entry in hostname_list:<EOL><INDENT>if len(entry) > <NUM_LIT:255>:<EOL><INDENT>return False<EOL><DEDENT>allowed = re.compile('<STR_LIT>', re.IGNORECASE)<EOL>if not all(allowed.match(x) for x in entry.split("<STR_LIT:.>")):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Check if the supplied list of strings are valid hostnames :param hostname_list: A list of strings :return: True if the strings are valid hostnames, False if not
f2655:m2
def is_readable(path=None):
if os.path.isfile(path) and os.access(path, os.R_OK):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
Test if the supplied filesystem path can be read :param path: A filesystem path :return: True if the path is a file that can be read. Otherwise, False
f2655:m3
def dedupe_list(seq):
seen = set()<EOL>return [x for x in seq if not (x in seen or seen.add(x))]<EOL>
Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed
f2655:m4
def __init__(self,<EOL>entry_type=None,<EOL>address=None,<EOL>comment=None,<EOL>names=None):
if not entry_type or entry_type not in ('<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT:blank>'):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if entry_type == '<STR_LIT>' and not comment:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if entry_type == '<STR_LIT>':<EOL><INDENT>if not all((address, names)):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if not is_ipv4(address):<EOL><INDENT>raise InvalidIPv4Address()<EOL><DEDENT><DEDENT>if entry_type == '<STR_LIT>':<EOL><INDENT>if not all((address, names)):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if not is_ipv6(address):<EOL><INDENT>raise InvalidIPv6Address()<EOL><DEDENT><DEDENT>self.entry_type = entry_type<EOL>self.address = address<EOL>self.comment = comment<EOL>self.names = names<EOL>
Initialise an instance of a Hosts file entry :param entry_type: ipv4 | ipv6 | comment | blank :param address: The ipv4 or ipv6 address belonging to the instance :param comment: The comment belonging to the instance :param names: The names that resolve to the specified address :return: None
f2656:c0:m0
@staticmethod<EOL><INDENT>def get_entry_type(hosts_entry=None):<DEDENT>
if hosts_entry and isinstance(hosts_entry, str):<EOL><INDENT>entry = hosts_entry.strip()<EOL>if not entry or not entry[<NUM_LIT:0>] or entry[<NUM_LIT:0>] == "<STR_LIT:\n>":<EOL><INDENT>return '<STR_LIT:blank>'<EOL><DEDENT>if entry[<NUM_LIT:0>] == "<STR_LIT:#>":<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>entry_chunks = entry.split()<EOL>if is_ipv6(entry_chunks[<NUM_LIT:0>]):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if is_ipv4(entry_chunks[<NUM_LIT:0>]):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>
Return the type of entry for the line of hosts file passed :param hosts_entry: A line from the hosts file :return: 'comment' | 'blank' | 'ipv4' | 'ipv6'
f2656:c0:m4
@staticmethod<EOL><INDENT>def str_to_hostentry(entry):<DEDENT>
line_parts = entry.strip().split()<EOL>if is_ipv4(line_parts[<NUM_LIT:0>]) and valid_hostnames(line_parts[<NUM_LIT:1>:]):<EOL><INDENT>return HostsEntry(entry_type='<STR_LIT>',<EOL>address=line_parts[<NUM_LIT:0>],<EOL>names=line_parts[<NUM_LIT:1>:])<EOL><DEDENT>elif is_ipv6(line_parts[<NUM_LIT:0>]) and valid_hostnames(line_parts[<NUM_LIT:1>:]):<EOL><INDENT>return HostsEntry(entry_type='<STR_LIT>',<EOL>address=line_parts[<NUM_LIT:0>],<EOL>names=line_parts[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
Transform a line from a hosts file into an instance of HostsEntry :param entry: A line from the hosts file :return: An instance of HostsEntry
f2656:c0:m5
def __init__(self, path=None):
self.entries = []<EOL>if path:<EOL><INDENT>self.hosts_path = path<EOL><DEDENT>else:<EOL><INDENT>self.hosts_path = self.determine_hosts_path()<EOL><DEDENT>self.populate_entries()<EOL>
Initialise an instance of a hosts file :param path: The filesystem path of the hosts file to manage :return: None
f2656:c1:m0
def count(self):
return len(self.entries)<EOL>
Get a count of the number of host entries :return: The number of host entries
f2656:c1:m3
@staticmethod<EOL><INDENT>def determine_hosts_path(platform=None):<DEDENT>
if not platform:<EOL><INDENT>platform = sys.platform<EOL><DEDENT>if platform.startswith('<STR_LIT>'):<EOL><INDENT>result = r"<STR_LIT>"<EOL>return result<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Return the hosts file path based on the supplied or detected platform. :param platform: a string used to identify the platform :return: detected filesystem path of the hosts file
f2656:c1:m4
def write(self, path=None):
written_count = <NUM_LIT:0><EOL>comments_written = <NUM_LIT:0><EOL>blanks_written = <NUM_LIT:0><EOL>ipv4_entries_written = <NUM_LIT:0><EOL>ipv6_entries_written = <NUM_LIT:0><EOL>if path:<EOL><INDENT>output_file_path = path<EOL><DEDENT>else:<EOL><INDENT>output_file_path = self.hosts_path<EOL><DEDENT>try:<EOL><INDENT>with open(output_file_path, '<STR_LIT:w>') as hosts_file:<EOL><INDENT>for written_count, line in enumerate(self.entries):<EOL><INDENT>if line.entry_type == '<STR_LIT>':<EOL><INDENT>hosts_file.write(line.comment + "<STR_LIT:\n>")<EOL>comments_written += <NUM_LIT:1><EOL><DEDENT>if line.entry_type == '<STR_LIT:blank>':<EOL><INDENT>hosts_file.write("<STR_LIT:\n>")<EOL>blanks_written += <NUM_LIT:1><EOL><DEDENT>if line.entry_type == '<STR_LIT>':<EOL><INDENT>hosts_file.write(<EOL>"<STR_LIT>".format(<EOL>line.address,<EOL>'<STR_LIT:U+0020>'.join(line.names),<EOL>)<EOL>)<EOL>ipv4_entries_written += <NUM_LIT:1><EOL><DEDENT>if line.entry_type == '<STR_LIT>':<EOL><INDENT>hosts_file.write(<EOL>"<STR_LIT>".format(<EOL>line.address,<EOL>'<STR_LIT:U+0020>'.join(line.names), ))<EOL>ipv6_entries_written += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>raise UnableToWriteHosts()<EOL><DEDENT>return {'<STR_LIT>': written_count + <NUM_LIT:1>,<EOL>'<STR_LIT>': comments_written,<EOL>'<STR_LIT>': blanks_written,<EOL>'<STR_LIT>': ipv4_entries_written,<EOL>'<STR_LIT>': ipv6_entries_written}<EOL>
Write all of the HostsEntry instances back to the hosts file :param path: override the write path :return: Dictionary containing counts
f2656:c1:m5
@staticmethod<EOL><INDENT>def get_hosts_by_url(url=None):<DEDENT>
response = urlopen(url)<EOL>return response.read()<EOL>
Request the content of a URL and return the response :param url: The URL of the hosts file to download :return: The content of the passed URL
f2656:c1:m6
def exists(self, address=None, names=None, comment=None):
for entry in self.entries:<EOL><INDENT>if entry.entry_type in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if address and address == entry.address:<EOL><INDENT>return True<EOL><DEDENT>if names:<EOL><INDENT>for name in names:<EOL><INDENT>if name in entry.names:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif entry.entry_type == '<STR_LIT>' and entry.comment == comment:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
Determine if the supplied address and/or names, or comment, exists in a HostsEntry within Hosts :param address: An ipv4 or ipv6 address to search for :param names: A list of names to search for :param comment: A comment to search for :return: True if a supplied address, name, or comment is found. Otherwise, False.
f2656:c1:m7