code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
'''Compute the bezout algorithm of a and b, i.e. it returns u, v, p such as:
p = GCD(a,b)
a * u + b * v = p
Copied from http://www.labri.fr/perso/betrema/deug/poly/euclide.html.
'''
u = 1
v = 0
s = 0
t = 1
while b > 0:
q = a // b
r = a % b
a = b
b = r
tmp = s
s = u - q * s
u = tmp
tmp = t
t = v - q * t
v = tmp
return u, v, a | def bezout(a, b) | Compute the bezout algorithm of a and b, i.e. it returns u, v, p such as:
p = GCD(a,b)
a * u + b * v = p
Copied from http://www.labri.fr/perso/betrema/deug/poly/euclide.html. | 4.042241 | 1.563457 | 2.58545 |
'''Converts the integer x to its big-endian representation of length
x_len.
'''
if x > 256**x_len:
raise exceptions.IntegerTooLarge
h = hex(x)[2:]
if h[-1] == 'L':
h = h[:-1]
if len(h) & 1 == 1:
h = '0%s' % h
x = binascii.unhexlify(h)
return b'\x00' * int(x_len-len(x)) + x | def i2osp(x, x_len) | Converts the integer x to its big-endian representation of length
x_len. | 3.273374 | 2.671055 | 1.225499 |
'''Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter.
'''
if sys.version_info[0] < 3:
return ''.join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)))
else:
return bytes(x ^ y for (x, y) in zip(a, b)) | def string_xor(a, b) | Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter. | 2.953648 | 1.88129 | 1.570012 |
'''
Accumulate random bit string and remove \0 bytes until the needed length
is obtained.
'''
result = []
i = 0
while i < length:
rnd = rnd.getrandbits(12*length)
s = i2osp(rnd, 3*length)
s = s.replace('\x00', '')
result.append(s)
i += len(s)
return (''.join(result))[:length] | def get_nonzero_random_bytes(length, rnd=default_crypto_random) | Accumulate random bit string and remove \0 bytes until the needed length
is obtained. | 6.155799 | 3.257735 | 1.889595 |
'''Compare two strings using constant time.'''
result = True
for x, y in zip(a, b):
result &= (x == y)
return result | def constant_time_cmp(a, b) | Compare two strings using constant time. | 3.894249 | 4.330297 | 0.899303 |
'''Encrypt a byte message using a RSA public key and the OAEP wrapping
algorithm,
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashlib interface
mgf1 - a mask generation function
seed - a seed to use instead of generating it using a random generator
rnd - a random generator class, respecting the random generator
interface from the random module, if seed is None, it is used to
generate it.
Return value:
the encrypted string of the same length as the public key
'''
hash = hash_class()
h_len = hash.digest_size
k = public_key.byte_size
max_message_length = k - 2 * h_len - 2
if len(message) > max_message_length:
raise exceptions.MessageTooLong
hash.update(label)
label_hash = hash.digest()
ps = b'\0' * int(max_message_length - len(message))
db = b''.join((label_hash, ps, b'\x01', message))
if not seed:
seed = primitives.i2osp(rnd.getrandbits(h_len*8), h_len)
db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class)
masked_db = primitives.string_xor(db, db_mask)
seed_mask = mgf(masked_db, h_len, hash_class=hash_class)
masked_seed = primitives.string_xor(seed, seed_mask)
em = b''.join((b'\x00', masked_seed, masked_db))
m = primitives.os2ip(em)
c = public_key.rsaep(m)
output = primitives.i2osp(c, k)
return output | def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1,
mgf=mgf.mgf1, seed=None, rnd=default_crypto_random) | Encrypt a byte message using a RSA public key and the OAEP wrapping
algorithm,
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashlib interface
mgf1 - a mask generation function
seed - a seed to use instead of generating it using a random generator
rnd - a random generator class, respecting the random generator
interface from the random module, if seed is None, it is used to
generate it.
Return value:
the encrypted string of the same length as the public key | 4.056631 | 2.143211 | 1.892782 |
'''Decrypt a byte message using a RSA private key and the OAEP wrapping
algorithm
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashlib interface
mgf1 - a mask generation function
Return value:
the string before encryption (decrypted)
'''
hash = hash_class()
h_len = hash.digest_size
k = private_key.byte_size
# 1. check length
if len(message) != k or k < 2 * h_len + 2:
raise ValueError('decryption error')
# 2. RSA decryption
c = primitives.os2ip(message)
m = private_key.rsadp(c)
em = primitives.i2osp(m, k)
# 4. EME-OAEP decoding
hash.update(label)
label_hash = hash.digest()
y, masked_seed, masked_db = em[0], em[1:h_len+1], em[1+h_len:]
if y != b'\x00' and y != 0:
raise ValueError('decryption error')
seed_mask = mgf(masked_db, h_len)
seed = primitives.string_xor(masked_seed, seed_mask)
db_mask = mgf(seed, k - h_len - 1)
db = primitives.string_xor(masked_db, db_mask)
label_hash_prime, rest = db[:h_len], db[h_len:]
i = rest.find(b'\x01')
if i == -1:
raise exceptions.DecryptionError
if rest[:i].strip(b'\x00') != b'':
print(rest[:i].strip(b'\x00'))
raise exceptions.DecryptionError
m = rest[i+1:]
if label_hash_prime != label_hash:
raise exceptions.DecryptionError
return m | def decrypt(private_key, message, label=b'', hash_class=hashlib.sha1,
mgf=mgf.mgf1) | Decrypt a byte message using a RSA private key and the OAEP wrapping
algorithm
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashlib interface
mgf1 - a mask generation function
Return value:
the string before encryption (decrypted) | 3.965205 | 2.61258 | 1.517736 |
'''Generates an RSA key pair.
size:
the bit size of the modulus, default to 512.
number:
the number of primes to use, default to 2.
rnd:
the random number generator to use, default to SystemRandom from the
random library.
k:
the number of iteration to use for the probabilistic primality
tests.
primality_algorithm:
the primality algorithm to use.
strict_size:
whether to use size as a lower bound or a strict goal.
e:
the public key exponent.
Returns the pair (public_key, private_key).
'''
primes = []
lbda = 1
bits = size // number + 1
n = 1
while len(primes) < number:
if number - len(primes) == 1:
bits = size - primitives.integer_bit_size(n) + 1
prime = get_prime(bits, rnd, k, algorithm=primality_algorithm)
if prime in primes:
continue
if e is not None and fractions.gcd(e, lbda) != 1:
continue
if (strict_size and number - len(primes) == 1 and
primitives.integer_bit_size(n*prime) != size):
continue
primes.append(prime)
n *= prime
lbda *= prime - 1
if e is None:
e = 0x10001
while e < lbda:
if fractions.gcd(e, lbda) == 1:
break
e += 2
assert 3 <= e <= n-1
public = RsaPublicKey(n, e)
private = MultiPrimeRsaPrivateKey(primes, e, blind=True, rnd=rnd)
return public, private | def generate_key_pair(size=512, number=2, rnd=default_crypto_random,
k=DEFAULT_ITERATION, primality_algorithm=None,
strict_size=True, e=0x10001) | Generates an RSA key pair.
size:
the bit size of the modulus, default to 512.
number:
the number of primes to use, default to 2.
rnd:
the random number generator to use, default to SystemRandom from the
random library.
k:
the number of iteration to use for the probabilistic primality
tests.
primality_algorithm:
the primality algorithm to use.
strict_size:
whether to use size as a lower bound or a strict goal.
e:
the public key exponent.
Returns the pair (public_key, private_key). | 3.37383 | 2.38761 | 1.413057 |
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
else:
incomplete = ''
def escape(s):
return s.replace('"', '""').replace("'", "''").replace('$', '\\$').replace('`', '\\`')
res = []
for item, help in get_choices(cli, prog_name, args, incomplete):
if help:
res.append(r'"%s"\:"%s"' % (escape(item), escape(help)))
else:
res.append('"%s"' % escape(item))
if res:
echo("_arguments '*: :((%s))'" % '\n'.join(res))
else:
echo("_files")
return True | def do_zsh_complete(cli, prog_name) | Do the zsh completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise | 4.265158 | 4.646258 | 0.917977 |
app.connect('html-page-context', add_html_link)
app.connect('build-finished', create_sitemap)
app.set_translator('html', HTMLTranslator)
app.sitemap_links = [] | def setup(app) | Setup conntects events to the sitemap builder | 3.457663 | 3.018216 | 1.145598 |
base_url = app.config['html_theme_options'].get('base_url', '')
if base_url:
app.sitemap_links.append(base_url + pagename + ".html") | def add_html_link(app, pagename, templatename, context, doctree) | As each page is built, collect page names for the sitemap | 3.616911 | 2.994476 | 1.207861 |
if (not app.config['html_theme_options'].get('base_url', '') or
exception is not None or
not app.sitemap_links):
return
filename = app.outdir + "/sitemap.xml"
print("Generating sitemap.xml in %s" % filename)
root = ET.Element("urlset")
root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for link in app.sitemap_links:
url = ET.SubElement(root, "url")
ET.SubElement(url, "loc").text = link
ET.ElementTree(root).write(filename) | def create_sitemap(app, exception) | Generates the sitemap.xml from the collected HTML page links | 2.554198 | 2.428091 | 1.051937 |
bits = token.split_contents()
if len(bits) == 2:
object_var = parser.compile_filter(bits[1])
language_var = None
elif len(bits) == 3:
object_var = parser.compile_filter(bits[1])
language_var = parser.compile_filter(bits[2])
else:
raise TemplateSyntaxError("'%s' takes one argument (object) and has one optional argument (language)" % bits[0])
nodelist = parser.parse(('endobjectlanguage',))
parser.delete_first_token()
return ObjectLanguageNode(nodelist, object_var, language_var) | def objectlanguage(parser, token) | Template tag to switch an object language
Example::
{% objectlanguage object "en" %}
{{ object.title }}
{% endobjectlanguage %}
A TranslatedObject is not affected by the ``{% language .. %}`` tag
as it maintains it's own state. This tag temporary switches the object state.
Note that using this tag is not thread-safe if the object is shared between threads.
It temporary changes the current language of the object. | 1.752206 | 1.939471 | 0.903445 |
# This is the same logic as the django-admin uses.
# The only difference is the origin of the request parameter.
if not is_multilingual_project():
# By default, the objects are stored in a single static language.
# This makes the transition to multilingual easier as well.
# The default language can operate as fallback language too.
return default or appsettings.PARLER_LANGUAGES.get_default_language()
else:
# In multilingual mode, take the provided language of the request.
code = request.GET.get(query_language_key)
if not code:
# forms: show first tab by default
code = default or appsettings.PARLER_LANGUAGES.get_first_language()
return normalize_language_code(code) | def get_language_parameter(request, query_language_key='language', object=None, default=None) | Get the language parameter from the current request. | 7.439471 | 7.267632 | 1.023644 |
tabs = TabsList(css_class=css_class)
get = request.GET.copy() # QueryDict object
tab_languages = []
site_id = getattr(settings, 'SITE_ID', None)
for lang_dict in appsettings.PARLER_LANGUAGES.get(site_id, ()):
code = lang_dict['code']
title = get_language_title(code)
get['language'] = code
url = '?{0}'.format(get.urlencode())
if code == current_language:
status = 'current'
elif code in available_languages:
status = 'available'
else:
status = 'empty'
tabs.append((url, title, code, status))
tab_languages.append(code)
# Additional stale translations in the database?
if appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS:
for code in available_languages:
if code not in tab_languages:
get['language'] = code
url = '?{0}'.format(get.urlencode())
if code == current_language:
status = 'current'
else:
status = 'available'
tabs.append((url, get_language_title(code), code, status))
tabs.current_is_translated = current_language in available_languages
tabs.allow_deletion = len(available_languages) > 1
return tabs | def get_language_tabs(request, current_language, available_languages, css_class=None) | Determine the language tabs to show. | 2.838737 | 2.860905 | 0.992252 |
if instance.pk is None or instance._state.adding:
return []
keys = []
tr_models = instance._parler_meta.get_all_models()
# TODO: performs a query to fetch the language codes. Store that in memcached too.
for language in instance.get_available_languages():
for tr_model in tr_models:
keys.append(get_translation_cache_key(tr_model, instance.pk, language))
return keys | def get_object_cache_keys(instance) | Return the cache keys associated with an object. | 4.967822 | 4.831306 | 1.028257 |
# Always cache the entire object, as this already produces
# a lot of queries. Don't go for caching individual fields.
return 'parler.{0}.{1}.{2}.{3}'.format(translated_model._meta.app_label, translated_model.__name__, master_id, language_code) | def get_translation_cache_key(translated_model, master_id, language_code) | The low-level function to get the cache key for a translation. | 6.896466 | 6.685486 | 1.031558 |
if language_code is None:
language_code = instance.get_current_language()
translated_model = instance._parler_meta.get_model_by_related_name(related_name)
values = _get_cached_values(instance, translated_model, language_code, use_fallback)
if not values:
return None
try:
translation = translated_model(**values)
except TypeError:
# Some model field was removed, cache entry is no longer working.
return None
translation._state.adding = False
return translation | def get_cached_translation(instance, language_code=None, related_name=None, use_fallback=False) | Fetch an cached translation.
.. versionadded 1.2 Added the ``related_name`` parameter. | 3.773689 | 3.915734 | 0.963725 |
if language_code is None:
language_code = instance.get_current_language()
# In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
# This serves as detection against backwards incompatibility issues.
if len(field_name) <= 5 and len(language_code) > 5:
raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")
translated_model = instance._parler_meta.get_model_by_field(field_name)
values = _get_cached_values(instance, translated_model, language_code, use_fallback)
if not values:
return None
# Allow older cached versions where the field didn't exist yet.
return values.get(field_name, None) | def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False) | Fetch an cached field. | 5.315305 | 5.201552 | 1.021869 |
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return None
key = get_translation_cache_key(translated_model, instance.pk, language_code)
values = cache.get(key)
if not values:
return None
# Check for a stored fallback marker
if values.get('__FALLBACK__', False):
# Internal trick, already set the fallback marker, so no query will be performed.
instance._translations_cache[translated_model][language_code] = MISSING
# Allow to return the fallback language instead.
if use_fallback:
lang_dict = get_language_settings(language_code)
# iterate over list of fallback languages, which should be already
# in proper order
for fallback_lang in lang_dict['fallbacks']:
if fallback_lang != language_code:
return _get_cached_values(
instance, translated_model, fallback_lang,
use_fallback=False
)
return None
values['master'] = instance
values['language_code'] = language_code
return values | def _get_cached_values(instance, translated_model, language_code, use_fallback=False) | Fetch an cached field. | 4.652738 | 4.564831 | 1.019257 |
if not appsettings.PARLER_ENABLE_CACHING:
return
if translation.master_id is None:
raise ValueError("Can't cache unsaved translation")
# Cache a translation object.
# For internal usage, object parameters are not suited for outside usage.
fields = translation.get_translated_fields()
values = {'id': translation.id}
for name in fields:
values[name] = getattr(translation, name)
key = get_translation_cache_key(translation.__class__, translation.master_id, translation.language_code)
cache.set(key, values, timeout=timeout) | def _cache_translation(translation, timeout=cache.default_timeout) | Store a new translation in the cache. | 4.502793 | 4.255074 | 1.058217 |
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return
tr_model = instance._parler_meta.get_model_by_related_name(related_name)
key = get_translation_cache_key(tr_model, instance.pk, language_code)
cache.set(key, {'__FALLBACK__': True}, timeout=timeout) | def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=cache.default_timeout) | Store the fact that a translation doesn't exist, and the fallback should be used. | 3.854444 | 3.692205 | 1.043941 |
if not isinstance(template_name_list, tuple):
template_name_list = tuple(template_name_list)
try:
return _cached_name_lookups[template_name_list]
except KeyError:
# Find which template of the template_names is selected by the Django loader.
for template_name in template_name_list:
try:
get_template(template_name, using=using)
except TemplateDoesNotExist:
continue
else:
template_name = six.text_type(template_name) # consistent value for lazy() function.
_cached_name_lookups[template_name_list] = template_name
return template_name
return None | def select_template_name(template_name_list, using=None) | Given a list of template names, find the first one that exists. | 3.442333 | 3.247493 | 1.059997 |
if not self.view_url_name:
# Sadly, class based views can't work with reverse(func_pointer) as that's unknown.
# Neither is it possible to use resolve(self.request.path).view_name in this function as auto-detection.
# This function can be called in the context of a different language.
# When i18n_patterns() is applied, that resolve() will fail.
#
# Hence, you need to provide a "view_url_name" as static configuration option.
raise ImproperlyConfigured("Missing `view_url_name` attribute on {0}".format(self.__class__.__name__))
return reverse(self.view_url_name, args=self.args, kwargs=self.kwargs) | def get_view_url(self) | This method is used by the ``get_translated_url`` template tag.
By default, it uses the :attr:`view_url_name` to generate an URL.
When the URL ``args`` and ``kwargs`` are translatable,
override this function instead to generate the proper URL. | 7.568701 | 7.289625 | 1.038284 |
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback = False
prev_choices = []
for lang_choice in choices:
try:
# Get the single item from the filtered queryset
# NOTE. Explicitly set language to the state the object was fetched in.
filters = self.get_translated_filters(slug=slug)
obj = queryset.translated(lang_choice, **filters).language(lang_choice).get()
except ObjectDoesNotExist:
# Translated object not found, next object is marked as fallback.
using_fallback = True
prev_choices.append(lang_choice)
else:
break
if obj is None:
tried_msg = ", tried languages: {0}".format(", ".join(choices))
error_message = translation.ugettext("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}
raise Http404(error_message + tried_msg)
# Object found!
if using_fallback:
# It could happen that objects are resolved using their fallback language,
# but the actual translation also exists. Either that means this URL should
# raise a 404, or a redirect could be made as service to the users.
# It's possible that the old URL was active before in the language domain/subpath
# when there was no translation yet.
for prev_choice in prev_choices:
if obj.has_translation(prev_choice):
# Only dispatch() and render_to_response() can return a valid response,
# By breaking out here, this functionality can't be broken by users overriding render_to_response()
raise FallbackLanguageResolved(obj, prev_choice)
return obj | def get_object(self, queryset=None) | Fetch the object using a translated slug. | 6.294689 | 6.024673 | 1.044818 |
object = super(LanguageChoiceMixin, self).get_object(queryset)
if isinstance(object, TranslatableModelMixin):
object.set_current_language(self.get_language(), initialize=True)
return object | def get_object(self, queryset=None) | Assign the language for the retrieved object. | 4.608684 | 3.748581 | 1.229448 |
return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object)) | def get_language(self) | Get the language parameter from the current request. | 9.296394 | 7.46139 | 1.245933 |
current_language = self.get_current_language()
if self.object:
available_languages = list(self.object.get_available_languages())
else:
available_languages = []
return get_language_tabs(self.request, current_language, available_languages) | def get_language_tabs(self) | Determine the language tabs to show. | 2.97198 | 2.812119 | 1.056847 |
super_method = super(TranslatableModelFormMixin, self).get_form_class
# no "__func__" on the class level function in python 3
default_method = getattr(ModelFormMixin.get_form_class, '__func__', ModelFormMixin.get_form_class)
if not (super_method.__func__ is default_method):
# Don't get in your way, if you've overwritten stuff.
return super_method()
else:
# Same logic as ModelFormMixin.get_form_class, but using the right form base class.
if self.form_class:
return self.form_class
else:
model = _get_view_model(self)
if self.fields:
fields = self.fields
return modelform_factory(model, form=TranslatableModelForm, fields=fields)
else:
return modelform_factory(model, form=TranslatableModelForm) | def get_form_class(self) | Return a ``TranslatableModelForm`` by default if no form_class is set. | 4.252863 | 3.897145 | 1.091277 |
kwargs = super(TranslatableModelFormMixin, self).get_form_kwargs()
# The TranslatableAdmin can set form.language_code, because the modeladmin always creates a fresh subclass.
# If that would be done here, the original globally defined form class would be updated.
kwargs['_current_language'] = self.get_form_language()
return kwargs | def get_form_kwargs(self) | Pass the current language to the form. | 11.017241 | 9.619438 | 1.14531 |
languages_list = LanguagesSetting(languages_list)
languages_list.setdefault('default', {})
defaults = languages_list['default']
defaults.setdefault('hide_untranslated', False) # Whether queries with .active_translations() may or may not return the fallback language.
if 'fallback' in defaults:
#warnings.warn("Please use 'fallbacks' instead of 'fallback' in the 'defaults' section of {0}".format(var_name), DeprecationWarning)
defaults['fallbacks'] = [defaults.pop('fallback')]
if 'fallback' in extra_defaults:
#warnings.warn("Please use 'fallbacks' instead of 'fallback' in parameters for {0} = add_default_language_settings(..)".format(var_name), DeprecationWarning)
extra_defaults['fallbacks'] = [extra_defaults.pop('fallback')]
defaults.update(extra_defaults) # Also allow to override code and fallback this way.
# This function previously existed in appsettings, where it could reference the defaults directly.
# However, this module is a more logical place for this function. To avoid circular import problems,
# the 'code' and 'fallback' parameters are always passed by the appsettings module.
# In case these are missing, default to the original behavior for backwards compatibility.
if 'code' not in defaults:
from parler import appsettings
defaults['code'] = appsettings.PARLER_DEFAULT_LANGUAGE_CODE
if 'fallbacks' not in defaults:
from parler import appsettings
defaults['fallbacks'] = [appsettings.PARLER_DEFAULT_LANGUAGE_CODE]
if not is_supported_django_language(defaults['code']):
raise ImproperlyConfigured("The value for {0}['defaults']['code'] ('{1}') does not exist in LANGUAGES".format(var_name, defaults['code']))
for site_id, lang_choices in six.iteritems(languages_list):
if site_id == 'default':
continue
if not isinstance(lang_choices, (list, tuple)):
raise ImproperlyConfigured("{0}[{1}] should be a tuple of language choices!".format(var_name, site_id))
for i, choice in enumerate(lang_choices):
if not is_supported_django_language(choice['code']):
raise ImproperlyConfigured("{0}[{1}][{2}]['code'] does not exist in LANGUAGES".format(var_name, site_id, i))
# Copy all items from the defaults, so you can provide new fields too.
for key, value in six.iteritems(defaults):
choice.setdefault(key, value)
return languages_list | def add_default_language_settings(languages_list, var_name='PARLER_LANGUAGES', **extra_defaults) | Apply extra defaults to the language settings.
This function can also be used by other packages to
create their own variation of ``PARLER_LANGUAGES`` with extra fields.
For example::
from django.conf import settings
from parler import appsettings as parler_appsettings
# Create local names, which are based on the global parler settings
MYAPP_DEFAULT_LANGUAGE_CODE = getattr(settings, 'MYAPP_DEFAULT_LANGUAGE_CODE', parler_appsettings.PARLER_DEFAULT_LANGUAGE_CODE)
MYAPP_LANGUAGES = getattr(settings, 'MYAPP_LANGUAGES', parler_appsettings.PARLER_LANGUAGES)
# Apply the defaults to the languages
MYAPP_LANGUAGES = parler_appsettings.add_default_language_settings(MYAPP_LANGUAGES, 'MYAPP_LANGUAGES',
code=MYAPP_DEFAULT_LANGUAGE_CODE,
fallback=MYAPP_DEFAULT_LANGUAGE_CODE,
hide_untranslated=False
)
The returned object will be an :class:`~parler.utils.conf.LanguagesSetting` object,
which adds additional methods to the :class:`dict` object.
:param languages_list: The settings, in :ref:`PARLER_LANGUAGES` format.
:param var_name: The name of your variable, for debugging output.
:param extra_defaults: Any defaults to override in the ``languages_list['default']`` section, e.g. ``code``, ``fallback``, ``hide_untranslated``.
:return: The updated ``languages_list`` with all defaults applied to all sections.
:rtype: LanguagesSetting | 3.350091 | 3.349164 | 1.000277 |
valid_keys = ['code', 'fallbacks', 'hide_untranslated',
'redirect_on_fallback']
if cms_languages:
if sys.version_info < (3, 0, 0):
int_types = (int, long)
else:
int_types = int
parler_languages = copy.deepcopy(cms_languages)
for site_id, site_config in cms_languages.items():
if site_id and (
not isinstance(site_id, int_types) and
site_id != 'default'
):
del parler_languages[site_id]
continue
if site_id == 'default':
for key, value in site_config.items():
if key not in valid_keys:
del parler_languages['default'][key]
else:
for i, lang_config in enumerate(site_config):
for key, value in lang_config.items():
if key not in valid_keys:
del parler_languages[site_id][i][key]
return parler_languages
return None | def get_parler_languages_from_django_cms(cms_languages=None) | Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since
CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of
cleansing to remove irrelevant items. | 2.250924 | 2.141803 | 1.050948 |
if language_code is None:
raise ValueError(get_null_language_error())
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
for lang_dict in self.get(site_id, ()):
if lang_dict['code'] == language_code:
return lang_dict
# no language match, search for variant: fr-ca falls back to fr
for lang_dict in self.get(site_id, ()):
if lang_dict['code'].split('-')[0] == language_code.split('-')[0]:
return lang_dict
return self['default'] | def get_language(self, language_code, site_id=None) | Return the language settings for the current site
This function can be used with other settings variables
to support modules which create their own variation of the ``PARLER_LANGUAGES`` setting.
For an example, see :func:`~parler.appsettings.add_default_language_settings`. | 3.15621 | 3.075123 | 1.026369 |
if language_code is None:
language_code = get_language()
lang_dict = self.get_language(language_code, site_id=site_id)
if not lang_dict['hide_untranslated']:
return [language_code] + [lang for lang in lang_dict['fallbacks'] if lang != language_code]
else:
return [language_code] | def get_active_choices(self, language_code=None, site_id=None) | Find out which translations should be visible in the site.
It returns a list with either a single choice (the current language),
or a list with the current language + fallback language. | 2.779804 | 2.462477 | 1.128865 |
choices = self.get_active_choices(language_code, site_id=site_id)
return choices[1:] | def get_fallback_languages(self, language_code=None, site_id=None) | Find out what the fallback language is for a given language choice.
.. versionadded 1.5 | 5.910148 | 7.167292 | 0.8246 |
choices = self.get_active_choices(language_code, site_id=site_id)
if choices and len(choices) > 1:
# Still take the last, like previous code.
# With multiple fallback languages that means taking the base language.
# Hence, upgrade the code to use get_fallback_languages() instead.
return choices[-1]
else:
return None | def get_fallback_language(self, language_code=None, site_id=None) | Find out what the fallback language is for a given language choice.
.. deprecated:: 1.5
Use :func:`get_fallback_languages` instead. | 8.910695 | 8.458101 | 1.05351 |
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
try:
return self[site_id][0]['code']
except (KeyError, IndexError):
# No configuration, always fallback to default language.
# This is essentially a non-multilingual configuration.
return self['default']['code'] | def get_first_language(self, site_id=None) | Return the first language for the current site.
This can be used for user interfaces, where the languages are displayed in tabs. | 4.578582 | 4.238543 | 1.080226 |
field = model._meta.get_field(name)
if not field.editable: # see fields_for_model() logic in Django.
return None
# Apply admin formfield_overrides
if formfield_callback is None:
formfield = field.formfield(**kwargs)
elif not callable(formfield_callback):
raise TypeError('formfield_callback must be a function or callable')
else:
formfield = formfield_callback(field, **kwargs)
return formfield | def _get_model_form_field(model, name, formfield_callback=None, **kwargs) | Utility to create the formfield from a model field.
When a field is not editable, a ``None`` will be returned. | 3.105025 | 3.118346 | 0.995728 |
fields = {}
# Collect all translated fields {'name': 'value'}
for field in self._translated_fields:
try:
value = self.cleaned_data[field]
except KeyError: # Field has a ValidationError
continue
fields[field] = value
# Set the field values on their relevant models
translations = self.instance._set_translated_fields(**fields)
# Perform full clean on models
non_translated_fields = set(('id', 'master_id', 'language_code'))
for translation in translations:
self._post_clean_translation(translation)
# Assign translated fields to the model (using the TranslatedAttribute descriptor)
for field in translation._get_field_names():
if field in non_translated_fields:
continue
setattr(self.instance, field, getattr(translation, field)) | def save_translated_fields(self) | Save all translated fields. | 4.991388 | 4.914801 | 1.015583 |
if not meta:
meta = {}
if shared_model._meta.abstract:
# This can't be done, because `master = ForeignKey(shared_model)` would fail.
raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__))
# Define inner Meta class
meta['app_label'] = shared_model._meta.app_label
meta['db_tablespace'] = shared_model._meta.db_tablespace
meta['managed'] = shared_model._meta.managed
meta['unique_together'] = list(meta.get('unique_together', [])) + [('language_code', 'master')]
meta.setdefault('db_table', '{0}_translation'.format(shared_model._meta.db_table))
meta.setdefault('verbose_name', _lazy_verbose_name(shared_model))
# Avoid creating permissions for the translated model, these are not used at all.
# This also avoids creating lengthy permission names above 50 chars.
meta.setdefault('default_permissions', ())
# Define attributes for translation table
name = str('{0}Translation'.format(shared_model.__name__)) # makes it bytes, for type()
attrs = {}
attrs.update(fields)
attrs['Meta'] = type(str('Meta'), (object,), meta)
attrs['__module__'] = shared_model.__module__
attrs['objects'] = models.Manager()
attrs['master'] = TranslationsForeignKey(shared_model, related_name=related_name, editable=False, null=True,
on_delete=models.CASCADE)
# Create and return the new model
translations_model = TranslatedFieldsModelBase(name, (TranslatedFieldsModel,), attrs)
# Register it as a global in the shared model's module.
# This is needed so that Translation model instances, and objects which refer to them, can be properly pickled and unpickled.
# The Django session and caching frameworks, in particular, depend on this behaviour.
mod = sys.modules[shared_model.__module__]
setattr(mod, name, translations_model)
return translations_model | def create_translations_model(shared_model, related_name, meta, **fields) | Dynamically create the translations model.
Create the translations model for the shared model 'model'.
:param related_name: The related name for the reverse FK from the translations model.
:param meta: A (optional) dictionary of attributes for the translations model's inner Meta class.
:param fields: A dictionary of fields to put on the translations model.
Two fields are enforced on the translations model:
language_code: A 15 char, db indexed field.
master: A ForeignKey back to the shared model.
Those two fields are unique together. | 3.976322 | 3.895781 | 1.020674 |
objects = [] # no generator, make sure objects are all filled first
for parler_meta, model_fields in self._parler_meta._split_fields(**fields):
translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta)
for field, value in six.iteritems(model_fields):
setattr(translation, field, value)
objects.append(translation)
return objects | def _set_translated_fields(self, language_code=None, **fields) | Assign fields to the translated models. | 5.994309 | 5.511597 | 1.087581 |
if language_code is None:
raise ValueError(get_null_language_error())
meta = self._parler_meta
if self._translations_cache[meta.root_model].get(language_code, None): # MISSING evaluates to False too
raise ValueError("Translation already exists: {0}".format(language_code))
# Save all fields in the proper translated model.
for translation in self._set_translated_fields(language_code, **fields):
self.save_translation(translation) | def create_translation(self, language_code, **fields) | Add a translation to the model.
The :func:`save_translations` function is called afterwards.
The object will be saved immediately, similar to
calling :func:`~django.db.models.manager.Manager.create`
or :func:`~django.db.models.fields.related.RelatedManager.create` on related fields. | 6.935459 | 7.077195 | 0.979973 |
if language_code is None:
raise ValueError(get_null_language_error())
if related_name is None:
metas = self._parler_meta
else:
metas = [self._parler_meta[related_name]]
num_deleted = 0
for meta in metas:
try:
translation = self._get_translated_model(language_code, meta=meta)
except meta.model.DoesNotExist:
continue
# By using the regular model delete, the cache is properly cleared
# (via _delete_cached_translation) and signals are emitted.
translation.delete()
num_deleted += 1
# Clear other local caches
try:
del self._translations_cache[meta.model][language_code]
except KeyError:
pass
try:
del self._prefetched_objects_cache[meta.rel_name]
except (AttributeError, KeyError):
pass
if not num_deleted:
raise ValueError("Translation does not exist: {0}".format(language_code))
return num_deleted | def delete_translation(self, language_code, related_name=None) | Delete a translation from a model.
:param language_code: The language to remove.
:param related_name: If given, only the model matching that related_name is removed. | 3.783389 | 3.885535 | 0.973711 |
self._current_language = normalize_language_code(language_code or get_language())
# Ensure the translation is present for __get__ queries.
if initialize:
self._get_translated_model(use_fallback=False, auto_create=True) | def set_current_language(self, language_code, initialize=False) | Switch the currently activate language of the object. | 8.292472 | 8.344862 | 0.993722 |
lang_dict = get_language_settings(self._current_language)
fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language]
return fallbacks or [] | def get_fallback_languages(self) | Return the fallback language codes,
which are used in case there is no translation for the currently active language. | 4.643499 | 4.048016 | 1.147105 |
if language_code is None:
language_code = self._current_language
if language_code is None:
raise ValueError(get_null_language_error())
meta = self._parler_meta._get_extension_by_related_name(related_name)
try:
# Check the local cache directly, and the answer is known.
# NOTE this may also return newly auto created translations which are not saved yet.
return not is_missing(self._translations_cache[meta.model][language_code])
except KeyError:
# If there is a prefetch, will be using that.
# However, don't assume the prefetch contains all possible languages.
# With Django 1.8, there are custom Prefetch objects.
# TODO: improve this, detect whether this is the case.
if language_code in self._read_prefetched_translations(meta=meta):
return True
# Try to fetch from the cache first.
# If the cache returns the fallback, it means the original does not exist.
object = get_cached_translation(self, language_code, related_name=related_name, use_fallback=True)
if object is not None:
return object.language_code == language_code
try:
# Fetch from DB, fill the cache.
self._get_translated_model(language_code, use_fallback=False, auto_create=False, meta=meta)
except meta.model.DoesNotExist:
return False
else:
return True | def has_translation(self, language_code=None, related_name=None) | Return whether a translation for the given language exists.
Defaults to the current language code.
.. versionadded 1.2 Added the ``related_name`` parameter. | 6.481234 | 6.32505 | 1.024693 |
meta = self._parler_meta._get_extension_by_related_name(related_name)
prefetch = self._get_prefetched_translations(meta=meta)
if prefetch is not None:
# TODO: this will break when using custom Django 1.8 Prefetch objects?
db_languages = sorted(obj.language_code for obj in prefetch)
else:
qs = self._get_translated_queryset(meta=meta)
db_languages = qs.values_list('language_code', flat=True).order_by('language_code')
if include_unsaved:
local_languages = (k for k, v in six.iteritems(self._translations_cache[meta.model]) if not is_missing(v))
return list(set(db_languages) | set(local_languages))
else:
return db_languages | def get_available_languages(self, related_name=None, include_unsaved=False) | Return the language codes of all translated variations.
.. versionadded 1.2 Added the ``include_unsaved`` and ``related_name`` parameters. | 4.375392 | 4.545208 | 0.962639 |
meta = self._parler_meta._get_extension_by_related_name(related_name)
return self._get_translated_model(language_code, meta=meta) | def get_translation(self, language_code, related_name=None) | Fetch the translated model | 7.710735 | 6.991367 | 1.102894 |
if meta is None:
meta = self._parler_meta.root
tr_model = meta.model
local_cache = self._translations_cache[tr_model]
if local_cache:
# There is already a language available in the case. No need for queries.
# Give consistent answers if they exist.
check_languages = [self._current_language] + self.get_fallback_languages()
try:
for fallback_lang in check_languages:
trans = local_cache.get(fallback_lang, None)
if trans and not is_missing(trans):
return trans
return next(t for t in six.itervalues(local_cache) if not is_missing(t))
except StopIteration:
pass
try:
# Use prefetch if available, otherwise perform separate query.
prefetch = self._get_prefetched_translations(meta=meta)
if prefetch is not None:
translation = prefetch[0] # Already a list
else:
translation = self._get_translated_queryset(meta=meta)[0]
except IndexError:
return None
else:
local_cache[translation.language_code] = translation
_cache_translation(translation)
return translation | def _get_any_translated_model(self, meta=None) | Return any available translation.
Returns None if there are no translations at all. | 4.723749 | 4.491239 | 1.05177 |
# Get via self.TRANSLATIONS_FIELD.get(..) so it also uses the prefetch/select_related cache.
if meta is None:
meta = self._parler_meta.root
accessor = getattr(self, meta.rel_name) # RelatedManager
return accessor.get_queryset() | def _get_translated_queryset(self, meta=None) | Return the queryset that points to the translated model.
If there is a prefetch, it can be read from this queryset. | 15.941734 | 14.248675 | 1.118822 |
if meta is None:
meta = self._parler_meta.root
related_name = meta.rel_name
try:
# Read the list directly, avoid QuerySet construction.
# Accessing self._get_translated_queryset(parler_meta)._prefetch_done is more expensive.
return self._prefetched_objects_cache[related_name]
except (AttributeError, KeyError):
return None | def _get_prefetched_translations(self, meta=None) | Return the queryset with prefetch results. | 9.318112 | 8.198388 | 1.136579 |
# This is called from ModelForm._post_clean() or Model.full_clean()
errors = {}
try:
super(TranslatableModelMixin, self).validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.message_dict
for local_cache in six.itervalues(self._translations_cache):
for translation in six.itervalues(local_cache):
if is_missing(translation): # Skip fallback markers
continue
try:
translation.validate_unique(exclude=exclude)
except ValidationError as e:
errors.update(e.message_dict)
if errors:
raise ValidationError(errors) | def validate_unique(self, exclude=None) | Also validate the unique_together of the translated model. | 3.763054 | 3.445884 | 1.092043 |
# Copy cache, new objects (e.g. fallbacks) might be fetched if users override save_translation()
# Not looping over the cache, but using _parler_meta so the translations are processed in the order of inheritance.
local_caches = self._translations_cache.copy()
for meta in self._parler_meta:
local_cache = local_caches[meta.model]
translations = list(local_cache.values())
# Save all translated objects which were fetched.
# This also supports switching languages several times, and save everything in the end.
for translation in translations:
if is_missing(translation): # Skip fallback markers
continue
self.save_translation(translation, *args, **kwargs) | def save_translations(self, *args, **kwargs) | The method to save all translations.
This can be overwritten to implement any custom additions.
This method calls :func:`save_translation` for every fetched language.
:param args: Any custom arguments to pass to :func:`save`.
:param kwargs: Any custom arguments to pass to :func:`save`. | 10.616898 | 10.425309 | 1.018377 |
if self.pk is None or self._state.adding:
raise RuntimeError("Can't save translations when the master object is not yet saved.")
# Translation models without any fields are also supported.
# This is useful for parent objects that have inlines;
# the parent object defines how many translations there are.
if translation.pk is None or translation.is_modified:
if not translation.master_id: # Might not exist during first construction
translation._state.db = self._state.db
translation.master = self
translation.save(*args, **kwargs) | def save_translation(self, translation, *args, **kwargs) | Save the translation when it's modified, or unsaved.
.. note::
When a derived model provides additional translated fields,
this method receives both the original and extended translation.
To distinguish between both objects, check for ``translation.related_name``.
:param translation: The translation
:type translation: TranslatedFieldsModel
:param args: Any custom arguments to pass to :func:`save`.
:param kwargs: Any custom arguments to pass to :func:`save`. | 7.970369 | 7.984086 | 0.998282 |
meta = self._parler_meta._get_extension_by_field(field)
# Extra feature: query a single field from a other translation.
if language_code and language_code != self._current_language:
try:
tr_model = self._get_translated_model(language_code, meta=meta, use_fallback=True)
return getattr(tr_model, field)
except TranslationDoesNotExist:
pass
else:
# By default, query via descriptor (TranslatedFieldDescriptor)
# which also attempts the fallback language if configured to do so.
try:
return getattr(self, field)
except TranslationDoesNotExist:
pass
if any_language:
translation = self._get_any_translated_model(meta=meta)
if translation is not None:
try:
return getattr(translation, field)
except KeyError:
pass
if callable(default):
return default()
else:
return default | def safe_translation_getter(self, field, default=None, language_code=None, any_language=False) | Fetch a translated property, and return a default value
when both the translation and fallback language are missing.
When ``any_language=True`` is used, the function also looks
into other languages to find a suitable value. This feature can be useful
for "title" attributes for example, to make sure there is at least something being displayed.
Also consider using ``field = TranslatedField(any_language=True)`` in the model itself,
to make this behavior the default for the given field.
.. versionchanged 1.5:: The *default* parameter may also be a callable. | 4.724833 | 5.132078 | 0.920647 |
try:
return self._fields_to_model[name]
except KeyError:
raise FieldError("Translated field does not exist: '{0}'".format(name)) | def get_model_by_field(self, name) | Find the :class:`TranslatedFieldsModel` that contains the given field. | 5.200353 | 4.031229 | 1.290017 |
if name is None:
raise TypeError("Expected field name")
# Reuse existing lookups.
tr_model = self.get_model_by_field(name)
for meta in self._extensions:
if meta.model == tr_model:
return meta | def _get_extension_by_field(self, name) | Find the ParlerOptions object that corresponds with the given translated field. | 7.365159 | 6.231816 | 1.181864 |
if related_name is None:
return self._extensions[0]
for meta in self._extensions:
if meta.rel_name == related_name:
return meta
raise ValueError("No translated model of '{0}' has a reverse name of '{1}'".format(
self.root.shared_model.__name__, related_name
)) | def _get_extension_by_related_name(self, related_name) | Find which model is connected to a given related name.
If the related name is ``None``, the :attr:`root_model` will be returned. | 5.623057 | 5.139959 | 1.093989 |
if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor):
raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__))
remote_field = new_class.master.field.remote_field
shared_model = remote_field.model
meta = shared_model._parler_meta
if meta is not None:
if meta._has_translations_model(new_class):
raise ImproperlyConfigured("The model '{0}' already has an associated translation table!".format(shared_model.__name__))
if meta._has_translations_field(remote_field.related_name):
raise ImproperlyConfigured("The model '{0}' already has an associated translation field named '{1}'!".format(shared_model.__name__, remote_field.related_name))
return shared_model | def _validate_master(new_class) | Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. | 3.129448 | 2.897059 | 1.080215 |
translations_model = self.field.meta.model
if translations_model is None:
# This only happens with abstract models. The code is accessing the descriptor at the base model directly,
# not the upgraded descriptor version that contribute_translations() installed.
# Fallback to what the admin label_for_field() would have done otherwise.
return pretty_name(self.field.name)
field = translations_model._meta.get_field(self.field.name)
return field.verbose_name | def short_description(self) | Ensure that the admin ``list_display`` renders the correct verbose name for translated fields.
The :func:`~django.contrib.admin.utils.label_for_field` function
uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``.
However, for translated fields, this option does not exist,
hence it falls back to reading the attribute and trying ``short_description``.
Ideally, translated fields should also appear in this list, to be treated like regular fields. | 11.322444 | 9.508699 | 1.190746 |
if obj is not None:
return obj.get_current_language()
else:
return self._language(request) | def get_form_language(self, request, obj=None) | Return the current language for the currently displayed object fields. | 4.798983 | 3.872871 | 1.239128 |
qs = super(BaseTranslatableAdmin, self).get_queryset(request)
if self._has_translatable_model():
if not isinstance(qs, TranslatableQuerySet):
raise ImproperlyConfigured("{0} class does not inherit from TranslatableQuerySet".format(qs.__class__.__name__))
# Apply a consistent language to all objects.
qs_language = self.get_queryset_language(request)
if qs_language:
qs = qs.language(qs_language)
return qs | def get_queryset(self, request) | Make sure the current language is selected. | 3.511046 | 3.170254 | 1.107497 |
current_language = self.get_form_language(request, obj)
return get_language_tabs(request, current_language, available_languages, css_class=css_class) | def get_language_tabs(self, request, obj, available_languages, css_class=None) | Determine the language tabs to show. | 2.922226 | 2.696316 | 1.083785 |
all_languages = [code for code, __ in settings.LANGUAGES]
return mark_safe(
self._languages_column(
object, all_languages, span_classes='all-languages'
)
) | def all_languages_column(self, object) | The language column which can be included in the ``list_display``.
It also shows untranslated languages | 5.908676 | 6.60718 | 0.894281 |
if obj:
return obj.get_available_languages()
else:
return self.model._parler_meta.root_model.objects.none() | def get_available_languages(self, obj) | Fetching the available languages as queryset. | 5.07732 | 4.103711 | 1.237251 |
obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs)
if obj is not None and self._has_translatable_model(): # Allow fallback to regular models.
obj.set_current_language(self._language(request, obj), initialize=True)
return obj | def get_object(self, request, object_id, *args, **kwargs) | Make sure the object is fetched in the correct language. | 5.373897 | 4.774461 | 1.12555 |
form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs)
if self._has_translatable_model():
form_class.language_code = self.get_form_language(request, obj)
return form_class | def get_form(self, request, obj=None, **kwargs) | Pass the current language to the form. | 3.425081 | 2.780797 | 1.231691 |
urlpatterns = super(TranslatableAdmin, self).get_urls()
if not self._has_translatable_model():
return urlpatterns
else:
opts = self.model._meta
info = opts.app_label, opts.model_name
return [url(
r'^(.+)/change/delete-translation/(.+)/$',
self.admin_site.admin_view(self.delete_translation),
name='{0}_{1}_delete_translation'.format(*info)
)] + urlpatterns | def get_urls(self) | Add a delete-translation view. | 2.663945 | 2.310055 | 1.153195 |
if self._has_translatable_model():
lang_code = self.get_form_language(request, obj)
lang = get_language_title(lang_code)
available_languages = self.get_available_languages(obj)
language_tabs = self.get_language_tabs(request, obj, available_languages)
context['language_tabs'] = language_tabs
if language_tabs:
context['title'] = '%s (%s)' % (context['title'], lang)
if not language_tabs.current_is_translated:
add = True # lets prepopulated_fields_js work.
# Patch form_url to contain the "language" GET parameter.
# Otherwise AdminModel.render_change_form will clean the URL
# and remove the "language" when coming from a filtered object
# list causing the wrong translation to be changed.
params = request.GET.dict()
params['language'] = lang_code
form_url = add_preserved_filters({
'preserved_filters': urlencode(params),
'opts': self.model._meta
}, form_url)
# django-fluent-pages uses the same technique
if 'default_change_form_template' not in context:
context['default_change_form_template'] = self.default_change_form_template
#context['base_template'] = self.get_change_form_base_template()
return super(TranslatableAdmin, self).render_change_form(request, context, add, change, form_url, obj) | def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None) | Insert the language tabs. | 4.39567 | 4.223982 | 1.040646 |
opts = self.model._meta
root_model = self.model._parler_meta.root_model
# Get object and translation
shared_obj = self.get_object(request, unquote(object_id))
if shared_obj is None:
raise Http404
shared_obj.set_current_language(language_code)
try:
translation = root_model.objects.get(master=shared_obj, language_code=language_code)
except root_model.DoesNotExist:
raise Http404
if not self.has_delete_permission(request, translation):
raise PermissionDenied
if len(self.get_available_languages(shared_obj)) <= 1:
return self.deletion_not_allowed(request, translation, language_code)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
using = router.db_for_write(root_model) # NOTE: all same DB for now.
lang = get_language_title(language_code)
# There are potentially multiple objects to delete;
# the translation object at the base level,
# and additional objects that can be added by inherited models.
deleted_objects = []
perms_needed = False
protected = []
# Extend deleted objects with the inlines.
for qs in self.get_translation_objects(request, translation.language_code, obj=shared_obj, inlines=self.delete_inline_translations):
if isinstance(qs, (list, tuple)):
qs_opts = qs[0]._meta
else:
qs_opts = qs.model._meta
if django.VERSION >= (2, 1):
deleted_result = get_deleted_objects(qs, request, self.admin_site)
else:
deleted_result = get_deleted_objects(qs, qs_opts, request.user, self.admin_site, using)
(del2, model_counts, perms2, protected2) = deleted_result
deleted_objects += del2
perms_needed = perms_needed or perms2
protected += protected2
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = _('{0} translation of {1}').format(lang, force_text(translation)) # in hvad: (translation.master)
self.log_deletion(request, translation, obj_display)
self.delete_model_translation(request, translation)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % dict(
name=force_text(opts.verbose_name), obj=force_text(obj_display)
))
if self.has_change_permission(request, None):
info = opts.app_label, opts.model_name
return HttpResponseRedirect(reverse('admin:{0}_{1}_change'.format(*info), args=(object_id,), current_app=self.admin_site.name))
else:
return HttpResponseRedirect(reverse('admin:index', current_app=self.admin_site.name))
object_name = _('{0} Translation').format(force_text(opts.verbose_name))
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": translation,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"app_label": opts.app_label,
}
# Small hack for django-polymorphic-tree.
# This makes sure the breadcrumb renders correctly,
# and avoids errors when the child model is not registered in the admin.
if hasattr(self, 'base_model'):
context.update({
'base_opts': self.base_model._meta,
})
return render(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (opts.app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % opts.app_label,
"admin/delete_confirmation.html"
], context) | def delete_translation(self, request, object_id, language_code) | The 'delete translation' admin view for this model. | 2.734712 | 2.7403 | 0.997961 |
opts = self.model._meta
context = {
'object': obj.master,
'language_code': language_code,
'opts': opts,
'app_label': opts.app_label,
'language_name': get_language_title(language_code),
'object_name': force_text(opts.verbose_name)
}
return render(request, self.deletion_not_allowed_template, context) | def deletion_not_allowed(self, request, obj, language_code) | Deletion-not-allowed view. | 2.412692 | 2.442776 | 0.987685 |
master = translation.master
for qs in self.get_translation_objects(request, translation.language_code, obj=master, inlines=self.delete_inline_translations):
if isinstance(qs, (tuple, list)):
# The objects are deleted one by one.
# This triggers the post_delete signals and such.
for obj in qs:
obj.delete()
else:
# Also delete translations of inlines which the user has access to.
# This doesn't trigger signals, just like the regular
qs.delete() | def delete_model_translation(self, request, translation) | Hook for deleting a translation.
This calls :func:`get_translation_objects` to collect all related objects for the translation.
By default, that includes the translations for inline objects. | 8.206914 | 6.776331 | 1.211115 |
if obj is not None:
# A single model can hold multiple TranslatedFieldsModel objects.
# Return them all.
for translations_model in obj._parler_meta.get_all_models():
try:
translation = translations_model.objects.get(master=obj, language_code=language_code)
except translations_model.DoesNotExist:
continue
yield [translation]
if inlines:
for inline, qs in self._get_inline_translations(request, language_code, obj=obj):
yield qs | def get_translation_objects(self, request, language_code, obj=None, inlines=True) | Return all objects that should be deleted when a translation is deleted.
This method can yield all QuerySet objects or lists for the objects. | 4.038181 | 3.78742 | 1.066209 |
inline_instances = self.get_inline_instances(request, obj=obj)
for inline in inline_instances:
if issubclass(inline.model, TranslatableModelMixin):
# leverage inlineformset_factory() to find the ForeignKey.
# This also resolves the fk_name if it's set.
fk = inline.get_formset(request, obj).fk
rel_name = 'master__{0}'.format(fk.name)
filters = {
'language_code': language_code,
rel_name: obj
}
for translations_model in inline.model._parler_meta.get_all_models():
qs = translations_model.objects.filter(**filters)
if obj is not None:
qs = qs.using(obj._state.db)
yield inline, qs | def _get_inline_translations(self, request, language_code, obj=None) | Fetch the inline translations | 4.320292 | 4.32068 | 0.99991 |
opts = self.model._meta
app_label = opts.app_label
return select_template_name((
"admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.lower()),
"admin/{0}/change_form.html".format(app_label),
"admin/change_form.html"
)) | def default_change_form_template(self) | Determine what the actual `change_form_template` should be. | 2.112308 | 1.966025 | 1.074405 |
FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)
# Existing objects already got the language code from the queryset().language() method.
# For new objects, the language code should be set here.
FormSet.language_code = self.get_form_language(request, obj)
if self.inline_tabs:
# Need to pass information to the template, this can only happen via the FormSet object.
available_languages = self.get_available_languages(obj, FormSet)
FormSet.language_tabs = self.get_language_tabs(request, obj, available_languages, css_class='parler-inline-language-tabs')
FormSet.language_tabs.allow_deletion = self._has_translatable_parent_model() # Views not available otherwise.
return FormSet | def get_formset(self, request, obj=None, **kwargs) | Return the formset, and provide the language information to the formset. | 6.338969 | 6.132802 | 1.033617 |
if self._has_translatable_parent_model():
return super(TranslatableInlineModelAdmin, self).get_form_language(request, obj=obj)
else:
# Follow the ?language parameter
return self._language(request) | def get_form_language(self, request, obj=None) | Return the current language for the currently displayed object fields. | 6.26509 | 5.836434 | 1.073445 |
if obj:
# Inlines dictate language code, not the parent model.
# Hence, not looking at obj.get_available_languages(), but see what languages
# are used by the inline objects that point to it.
filter = {
'master__{0}'.format(formset.fk.name): obj
}
return self.model._parler_meta.root_model.objects.using(obj._state.db).filter(**filter) \
.values_list('language_code', flat=True).distinct().order_by('language_code')
else:
return self.model._parler_meta.root_model.objects.none() | def get_available_languages(self, obj, formset) | Fetching the available inline languages as queryset. | 5.36115 | 5.166878 | 1.0376 |
if language_code is None:
language_code = appsettings.PARLER_LANGUAGES.get_default_language()
self._language = language_code
return self | def language(self, language_code=None) | Set the language code to assign to objects retrieved using this QuerySet. | 4.249174 | 3.283159 | 1.294234 |
relname = self.model._parler_meta.root_rel_name
if not language_codes:
language_codes = (get_language(),)
filters = {}
for field_name, val in six.iteritems(translated_fields):
if field_name.startswith('master__'):
filters[field_name[8:]] = val # avoid translations__master__ back and forth
else:
filters["{0}__{1}".format(relname, field_name)] = val
if len(language_codes) == 1:
filters[relname + '__language_code'] = language_codes[0]
return self.filter(**filters)
else:
filters[relname + '__language_code__in'] = language_codes
return self.filter(**filters).distinct() | def translated(self, *language_codes, **translated_fields) | Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
.. note::
Due to Django `ORM limitations <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships>`_,
this method can't be combined with other filters that access the translated fields. As such, query the fields in one filter:
.. code-block:: python
qs.translated('en', name="Cheese Omelette")
This will query the translated model for the ``name`` field. | 3.085871 | 3.262099 | 0.945977 |
# Default: (language, fallback) when hide_translated == False
# Alternative: (language,) when hide_untranslated == True
language_codes = get_active_language_choices(language_code)
return self.translated(*language_codes, **translated_fields) | def active_translations(self, language_code=None, **translated_fields) | Only return objects which are translated, or have a fallback that should be displayed.
Typically that's the currently active language and fallback language.
This should be combined with ``.distinct()``.
When ``hide_untranslated = True``, only the currently active language will be returned. | 9.49901 | 7.712478 | 1.231642 |
from parler import appsettings
# Avoid weird lookup errors.
if not language_code:
raise ValueError("Missing language_code in get_language_title()")
if appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS:
# this allows to edit languages that are not enabled in current project but are already
# in database
languages = ALL_LANGUAGES_DICT
else:
languages = LANGUAGES_DICT
try:
return _(languages[language_code])
except KeyError:
language_code = language_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
language_title = languages.get(language_code, None)
if language_title is not None:
return _(language_title)
else:
return language_code | def get_language_title(language_code) | Return the verbose_name for a language code.
Fallback to language_code if language is not found in settings. | 4.898557 | 4.964063 | 0.986804 |
# This method mainly exists for ease-of-use.
# the body is part of the settings, to allow third party packages
# to have their own variation of the settings with this method functionality included.
from parler import appsettings
return appsettings.PARLER_LANGUAGES.get_language(language_code, site_id) | def get_language_settings(language_code, site_id=None) | Return the language settings for the current site | 13.095664 | 12.936721 | 1.012286 |
from parler import appsettings
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES | def is_multilingual_project(site_id=None) | Whether the current Django project is configured for multilingual support. | 3.501145 | 3.18428 | 1.099509 |
from parler import appsettings
language = dj_get_language()
if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:
return appsettings.PARLER_DEFAULT_LANGUAGE_CODE
else:
return language | def get_language() | Wrapper around Django's `get_language` utility.
For Django >= 1.8, `get_language` returns None in case no translation is activate.
Here we patch this behavior e.g. for back-end functionality requiring access to translated fields | 6.038131 | 5.130661 | 1.176872 |
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | def __timestamp() | Generate timestamp data for pyc header. | 8.449503 | 6.628356 | 1.274751 |
res = None
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.name and entry.name.string == b"PYTHONSCRIPT":
res = entry.directory.entries[0].directory.entries[0]
break
return res | def _get_scripts_resource(pe) | Return the PYTHONSCRIPT resource entry. | 3.066594 | 2.314395 | 1.325009 |
rva = res.data.struct.OffsetToData
size = res.data.struct.Size
dump = pe.get_data(rva, size)
return dump | def _resource_dump(pe, res) | Return the dump of the given resource. | 3.664925 | 3.471171 | 1.055818 |
# Read py2exe header
current = struct.calcsize(b'iiii')
metadata = struct.unpack(b'iiii', data[:current])
# check py2exe magic number
# assert(metadata[0] == 0x78563412)
logging.info("Magic value: %x", metadata[0])
logging.info("Code bytes length: %d", metadata[3])
arcname = ''
while six.indexbytes(data, current) != 0:
arcname += chr(six.indexbytes(data, current))
current += 1
logging.info("Archive name: %s", arcname or '-')
code_bytes = data[current + 1:]
# verify code bytes count and metadata info
# assert(len(code_bytes) == metadata[3])
code_objects = marshal.loads(code_bytes)
return code_objects | def _get_co_from_dump(data) | Return the code objects from the dump. | 4.498719 | 4.263217 | 1.05524 |
py2exe_resource = _get_scripts_resource(pe)
if py2exe_resource is None:
logging.info('This is not a py2exe executable.')
if pe.__data__.find(b'pyi-windows-manifest-filename'):
logging.info('This seems a pyinstaller executable (unsupported).')
return bool(py2exe_resource) | def check_py2exe_file(pe) | Check file is a py2exe executable. | 8.814937 | 8.065891 | 1.092866 |
script_res = _get_scripts_resource(pe)
dump = _resource_dump(pe, script_res)
return _get_co_from_dump(dump) | def extract_code_objects(pe) | Extract Python code objects from a py2exe executable. | 9.434376 | 8.804336 | 1.07156 |
# assume Windows path information from the .exe
pyc_basename = ntpath.basename(co.co_filename)
pyc_name = pyc_basename + '.pyc'
if pyc_name not in IGNORE:
logging.info("Extracting %s", pyc_name)
pyc_header = _generate_pyc_header(python_version, len(co.co_code))
destination = os.path.join(output_dir, pyc_name)
pyc = open(destination, 'wb')
pyc.write(pyc_header)
marshaled_code = marshal.dumps(co)
pyc.write(marshaled_code)
pyc.close()
else:
logging.info("Skipping %s", pyc_name) | def dump_to_pyc(co, python_version, output_dir) | Save given code_object as a .pyc file. | 3.089808 | 3.109445 | 0.993685 |
if output_dir is None:
output_dir = '.'
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
pe = pefile.PE(filename)
is_py2exe = check_py2exe_file(pe)
if not is_py2exe:
raise ValueError('Not a py2exe executable.')
code_objects = extract_code_objects(pe)
for co in code_objects:
dump_to_pyc(co, python_version, output_dir) | def unpy2exe(filename, python_version=None, output_dir=None) | Process input params and produce output pyc files. | 2.792971 | 2.705377 | 1.032378 |
it = iter(iterable)
count = start
try:
last = next(it)
except StopIteration:
return
for val in it:
yield count, False, last
last = val
count += 1
yield count, True, last | def enum_mark_last(iterable, start=0) | Returns a generator over iterable that tells whether the current item is the last one.
Usage:
>>> iterable = range(10)
>>> for index, is_last, item in enum_mark_last(iterable):
>>> print(index, item, end='\n' if is_last else ', ') | 2.43397 | 3.025334 | 0.804529 |
self._check_alive()
request = IPCCommandLineExecutionRequest(command, timeout)
try:
self._tx_queue.put(request, timeout=timeout)
except queue.Full:
raise TxQueueFullError()
# The command could be modified by the IPCCommandLineExecutionRequest
self._cli_command_requests.append((request.command, callback)) | def execute_cli_command(self, command, callback, timeout=None) | Executes an arbitrary CLI command on the SLCAN adapter, assuming that the adapter supports CLI commands.
The callback will be invoked from the method receive() using same thread.
If the command times out, the callback will be invoked anyway, with 'expired' flag set.
Args:
command: Command as unicode string or bytes
callback: A callable that accepts one argument.
The argument is an instance of IPCCommandLineExecutionResponse
timeout: Timeout in seconds. None to use default timeout. | 7.639911 | 5.378465 | 1.420463 |
self._update_callbacks.append(callback)
return self.UpdateHandlerRemover(lambda: self._update_callbacks.remove(callback)) | def add_update_handler(self, callback) | Args:
callback: The specified callback will be invoked when:
- A new node appears
- Node info for an existing node gets updated
- Node goes offline
Returns: Call remove() or try_remove() on the returned object to unregister the handler. | 5.166883 | 5.483422 | 0.942273 |
if (self._registry[node_id].monotonic_timestamp + self.TIMEOUT) < time.monotonic():
self._call_event_handlers(self.UpdateEvent(self._registry[node_id],
self.UpdateEvent.EVENT_ID_OFFLINE))
del self._registry[node_id]
return self._registry[node_id] | def get(self, node_id) | Args:
node_id: Returns an Entry instance for the given node ID.
If the requested node ID does not exist, throws KeyError. | 5.512635 | 5.425115 | 1.016132 |
for _nid, entry in self._registry.items():
if predicate(entry):
yield entry | def find_all(self, predicate) | Returns a generator that produces a sequence of Entry objects for which the predicate returned True.
Args:
predicate: A callable that returns a value coercible to bool. | 8.94867 | 8.256754 | 1.0838 |
undiscovered = self.find_all(lambda e: not e.discovered)
return len(list(undiscovered)) == 0 | def are_all_nodes_discovered(self) | Reports whether there are nodes whose node info is still unknown. | 6.10467 | 5.247704 | 1.163303 |
def proxy(*args):
hook(*args)
self._io_hooks.append(proxy)
return self.HookRemover(lambda: self._io_hooks.remove(proxy)) | def add_io_hook(self, hook) | Args:
hook: This hook will be invoked for every incoming and outgoing CAN frame.
Hook arguments: (direction, frame)
See FRAME_DIRECTION_*, CANFrame. | 5.24297 | 7.026059 | 0.746218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.