text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_reviewable_topics(self, lang): """Return the topics learned but not golden by a user in a language."""
return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned'] and topic['strength'] < 1.0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_vocabulary(self, language_abbr=None): """Get overview of user's vocabulary in a language."""
if not self.password: raise Exception("You must provide a password for this function") if language_abbr and not self._is_current_language(language_abbr): self._switch_language(language_abbr) overview_url = "https://www.duolingo.com/vocabulary/overview" overview_request = self._make_req(overview_url) overview = overview_request.json() return overview
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire_update_event(self, *args, **kwargs): """Trigger the method tied to _on_update"""
for _handler in self._on_update: _handler(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_configuration(self) -> str: """downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode """
return self._restCall( "home/getCurrentState", json.dumps(self._connection.clientCharacteristics) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_security_zones_activation(self) -> (bool, bool): """ returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed """
internal_active = False external_active = False for g in self.groups: if isinstance(g, SecurityZoneGroup): if g.label == "EXTERNAL": external_active = g.active elif g.label == "INTERNAL": internal_active = g.active return internal_active, external_active
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def enable_events(self) -> asyncio.Task: """Connects to the websocket. Returns a listening task."""
return await self._connection.ws_connect( on_message=self._ws_on_message, on_error=self._ws_on_error )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_functionalChannels(self, groups: Iterable[Group]): """ this function will load the functionalChannels into the device """
self.functionalChannels = [] for channel in self._rawJSONData["functionalChannels"].values(): fc = self._parse_functionalChannel(channel, groups) self.functionalChannels.append(fc) self.functionalChannelCount = Counter( x.functionalChannelType for x in self.functionalChannels )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_shutter_level(self, level=0.0): """ sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall """
data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} return self._restCall("device/control/setShutterLevel", body=json.dumps(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_slats_level(self, slatsLevel=0.0, shutterLevel=None): """ sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value Returns: the result of the _restCall """
if shutterLevel is None: shutterLevel = self.shutterLevel data = { "channelIndex": 1, "deviceId": self.id, "slatsLevel": slatsLevel, "shutterLevel": shutterLevel, } return self._restCall("device/control/setSlatsLevel", json.dumps(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_label(self, label): """ sets the label of the rule """
data = {"ruleId": self.id, "label": label} return self._restCall("rule/setRuleLabel", json.dumps(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def api_call(self, path, body=None, full_url=False): """Make the actual call to the HMIP server. Throws `HmipWrongHttpStatusError` or `HmipConnectionError` if connection has failed or response is not correct."""
result = None if not full_url: path = self.full_url(path) for i in range(self._restCallRequestCounter): try: with async_timeout.timeout(self._restCallTimout, loop=self._loop): result = await self._websession.post( path, data=body, headers=self.headers ) if result.status == 200: if result.content_type == "application/json": ret = await result.json() else: ret = True return ret else: raise HmipWrongHttpStatusError except (asyncio.TimeoutError, aiohttp.ClientConnectionError): # Both exceptions occur when connecting to the server does # somehow not work. logger.debug("Connection timed out or another error occurred %s" % path) except JSONDecodeError as err: logger.exception(err) finally: if result is not None: await result.release() raise HmipConnectionError("Failed to connect to HomeMaticIp server")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_master_login(email, password, android_id, service='ac2dm', device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Perform a master login, which is what Android does when you first add a Google account. Return a dict, eg:: { 'Email': 'email@gmail.com', 'GooglePlusUpgrade': '1', 'PicasaUser': 'My Name', 'RopRevision': '1', 'RopText': ' ', 'firstName': 'My', 'lastName': 'Name', } """
data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'add_account': 1, 'EncryptedPasswd': google.signature(email, password, android_key_7_3_29), 'service': service, 'source': 'android', 'androidId': android_id, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version, } return _perform_auth_request(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_oauth(email, master_token, android_id, service, app, client_sig, device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Use a master token from master_login to perform OAuth to a specific Google service. Return a dict, eg:: { 'SID': '..', 'issueAdvice': 'auto', } To authenticate requests to this service, include a header ``Authorization: GoogleLogin auth=res['Auth']``. """
data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'EncryptedPasswd': master_token, 'service': service, 'source': 'android', 'androidId': android_id, 'app': app, 'client_sig': client_sig, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version } return _perform_auth_request(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION, algorithm=None): '''Test if n is a prime number m - the integer to test rnd - the random number generator to use for the probalistic primality algorithms, k - the number of iterations to use for the probabilistic primality algorithms, algorithm - the primality algorithm to use, default is Miller-Rabin. The gmpy implementation is used if gmpy is installed. Return value: True is n seems prime, False otherwise. ''' if algorithm is None: algorithm = PRIME_ALGO if algorithm == 'gmpy-miller-rabin': if not gmpy: raise NotImplementedError return gmpy.is_prime(n, k) elif algorithm == 'miller-rabin': # miller rabin probability of primality is 1/4**k return miller_rabin(n, k, rnd=rnd) elif algorithm == 'solovay-strassen': # for jacobi it's 1/2**k return randomized_primality_testing(n, rnd=rnd, k=k*2) else: raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def jacobi_witness(x, n): '''Returns False if n is an Euler pseudo-prime with base x, and True otherwise. ''' j = jacobi(x, n) % n f = pow(x, n >> 1, n) return j != f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def miller_rabin(n, k, rnd=default_pseudo_random): ''' Pure python implementation of the Miller-Rabin algorithm. n - the integer number to test, k - the number of iteration, the probability of n being prime if the algorithm returns True is 1/2**k, rnd - a random generator ''' s = 0 d = n-1 # Find nearest power of 2 s = primitives.integer_bit_size(n) # Find greatest factor which is a power of 2 s = fractions.gcd(2**s, n-1) d = (n-1) // s s = primitives.integer_bit_size(s) - 1 while k: k = k - 1 a = rnd.randint(2, n-2) x = pow(a, d, n) if x == 1 or x == n - 1: continue for r in range(1, s-1): x = pow(x, 2, n) if x == 1: return False if x == n - 1: break else: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_closest_match(target_track, tracks): """ Return closest match to target track """
track = None # Get a list of (track, artist match ratio, name match ratio) tracks_with_match_ratio = [( track, get_similarity(target_track.artist, track.artist), get_similarity(target_track.name, track.name), ) for track in tracks] # Sort by artist then by title sorted_tracks = sorted( tracks_with_match_ratio, key=lambda t: (t[1], t[2]), reverse=True # Descending, highest match ratio first ) if sorted_tracks: track = sorted_tracks[0][0] # Closest match to query return track
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def integer_ceil(a, b): '''Return the ceil integer of a div b.''' quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def integer_byte_size(n): '''Returns the number of bytes necessary to store the integer n.''' quanta, mod = divmod(integer_bit_size(n), 8) if mod or n == 0: quanta += 1 return quanta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def i2osp(x, x_len): '''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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_nonzero_random_bytes(length, rnd=default_crypto_random): ''' 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def constant_time_cmp(a, b): '''Compare two strings using constant time.''' result = True for x, y in zip(a, b): result &= (x == y) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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). ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(app): """Setup conntects events to the sitemap builder"""
app.connect('html-page-context', add_html_link) app.connect('build-finished', create_sitemap) app.set_translator('html', HTMLTranslator) app.sitemap_links = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_translated_url(context, lang_code, object=None): """ Get the proper URL for this page in a different language. Note that this algorithm performs a "best effect" approach to give a proper URL. To make sure the proper view URL is returned, add the :class:`~parler.views.ViewUrlMixin` to your view. Example, to build a language menu:: <ul> {% for lang_code, title in LANGUAGES %} {% get_language_info for lang_code as lang %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<li{% if lang_code == LANGUAGE_CODE %} class="is-selected"{% endif %}><a href="{{ tr_url }}" hreflang="{{ lang_code }}">{{ lang.name_local|capfirst }}</a></li>{% endif %} {% endfor %} </ul> Or to inform search engines about the translated pages:: {% for lang_code, title in LANGUAGES %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<link rel="alternate" hreflang="{{ lang_code }}" href="{{ tr_url }}" />{% endif %} {% endfor %} Note that using this tag is not thread-safe if the object is shared between threads. It temporary changes the current language of the view object. The query string of the current page is preserved in the translated URL. When the ``object`` variable is explicitly provided however, the query string will not be added. In such situation, *django-parler* assumes that the object may point to a completely different page, hence to query string is added. """
view = context.get('view', None) request = context['request'] if object is not None: # Cannot reliable determine whether the current page is being translated, # or the template code provides a custom object to translate. # Hence, not passing the querystring of the current page qs = '' else: # Try a few common object variables, the SingleObjectMixin object, # The Django CMS "current_page" variable, or the "page" from django-fluent-pages and Mezzanine. # This makes this tag work with most CMSes out of the box. object = context.get('object', None) \ or context.get('current_page', None) \ or context.get('page', None) # Assuming current page, preserve query string filters. qs = request.META.get('QUERY_STRING', '') try: if view is not None: # Allow a view to specify what the URL should be. # This handles situations where the slug might be translated, # and gives you complete control over the results of this template tag. get_view_url = getattr(view, 'get_view_url', None) if get_view_url: with smart_override(lang_code): return _url_qs(view.get_view_url(), qs) # Now, the "best effort" part starts. # See if it's a DetailView that exposes the object. if object is None: object = getattr(view, 'object', None) if object is not None and hasattr(object, 'get_absolute_url'): # There is an object, get the URL in the different language. # NOTE: this *assumes* that there is a detail view, not some edit view. # In such case, a language menu would redirect a user from the edit page # to a detail page; which is still way better a 404 or homepage. if isinstance(object, TranslatableModel): # Need to handle object URL translations. # Just using smart_override() should be enough, as a translated object # should use `switch_language(self)` internally before returning an URL. # However, it doesn't hurt to help a bit here. with switch_language(object, lang_code): return _url_qs(object.get_absolute_url(), qs) else: # Always switch the language before resolving, so i18n_patterns() are supported. with smart_override(lang_code): return _url_qs(object.get_absolute_url(), qs) except TranslationDoesNotExist: # Typically projects have a fallback language, so even unknown languages will return something. # This either means fallbacks are disabled, or the fallback language is not found! return '' # Just reverse the current URL again in a new language, and see where we end up. # This doesn't handle translated slugs, but will resolve to the proper view name. resolver_match = request.resolver_match if resolver_match is None: # Can't resolve the page itself, the page is apparently a 404. # This can also happen for the homepage in an i18n_patterns situation. return '' with smart_override(lang_code): clean_kwargs = _cleanup_urlpattern_kwargs(resolver_match.kwargs) return _url_qs(reverse(resolver_match.view_name, args=resolver_match.args, kwargs=clean_kwargs, current_app=resolver_match.app_name), qs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_translation_cache_key(translated_model, master_id, language_code): """ The low-level function to get the cache key for a translation. """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cache_translation(translation, timeout=cache.default_timeout): """ Store a new translation in the cache. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_template_name(template_name_list, using=None): """ Given a list of template names, find the first one that exists. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_object(self, queryset=None): """ Fetch the object using a translated slug. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_object(self, queryset=None): """ Assign the language for the retrieved object. """
object = super(LanguageChoiceMixin, self).get_object(queryset) if isinstance(object, TranslatableModelMixin): object.set_current_language(self.get_language(), initialize=True) return object
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_form_class(self): """ Return a ``TranslatableModelForm`` by default if no form_class is set. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_translated_fields(self): """ Save all translated fields. """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_translated_fields(self, language_code=None, **fields): """ Assign fields to the translated models. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_current_language(self, language_code, initialize=False): """ Switch the currently activate language of the object. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fallback_languages(self): """ Return the fallback language codes, which are used in case there is no translation for the currently active language. """
lang_dict = get_language_settings(self._current_language) fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language] return fallbacks or []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_translation(self, language_code, related_name=None): """ Fetch the translated model """
meta = self._parler_meta._get_extension_by_related_name(related_name) return self._get_translated_model(language_code, meta=meta)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None): """ Fetch the translated fields model. """
if self._parler_meta is None: raise ImproperlyConfigured("No translation is assigned to the current model!") if self._translations_cache is None: raise RuntimeError("Accessing translated fields before super.__init__() is not possible.") if not language_code: language_code = self._current_language if language_code is None: raise ValueError(get_null_language_error()) if meta is None: meta = self._parler_meta.root # work on base model by default local_cache = self._translations_cache[meta.model] # 1. fetch the object from the local cache try: object = local_cache[language_code] # If cached object indicates the language doesn't exist, need to query the fallback. if not is_missing(object): return object except KeyError: # 2. No cache, need to query # Check that this object already exists, would be pointless otherwise to check for a translation. if not self._state.adding and self.pk is not None: prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: # 2.1, use prefetched data # If the object is not found in the prefetched data (which contains all translations), # it's pointless to check for memcached (2.2) or perform a single query (2.3) for object in prefetch: if object.language_code == language_code: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object else: # 2.2, fetch from memcached object = get_cached_translation(self, language_code, related_name=meta.rel_name, use_fallback=use_fallback) if object is not None: # Track in local cache if object.language_code != language_code: local_cache[language_code] = MISSING # Set fallback marker local_cache[object.language_code] = object return object elif is_missing(local_cache.get(language_code, None)): # If get_cached_translation() explicitly set the "does not exist" marker, # there is no need to try a database query. pass else: # 2.3, fetch from database try: object = self._get_translated_queryset(meta).get(language_code=language_code) except meta.model.DoesNotExist: pass else: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object # Not in cache, or default. # Not fetched from DB # 3. Auto create? if auto_create: # Auto create policy first (e.g. a __set__ call) kwargs = { 'language_code': language_code, } if self.pk: # ID might be None at this point, and Django does not allow that. kwargs['master'] = self object = meta.model(**kwargs) local_cache[language_code] = object # Not stored in memcached here yet, first fill + save it. return object # 4. Fallback? fallback_msg = None lang_dict = get_language_settings(language_code) if language_code not in local_cache: # Explicitly set a marker for the fact that this translation uses the fallback instead. # Avoid making that query again. local_cache[language_code] = MISSING # None value is the marker. if not self._state.adding or self.pk is not None: _cache_translation_needs_fallback(self, language_code, related_name=meta.rel_name) fallback_choices = [lang_dict['code']] + list(lang_dict['fallbacks']) if use_fallback and fallback_choices: # Jump to fallback language, return directly. # Don't cache under this language_code for fallback_lang in fallback_choices: if fallback_lang == language_code: # Skip the current language, could also be fallback 1 of 2 choices continue try: return self._get_translated_model(fallback_lang, use_fallback=False, auto_create=auto_create, meta=meta) except meta.model.DoesNotExist: pass fallback_msg = " (tried fallbacks {0})".format(', '.join(lang_dict['fallbacks'])) # None of the above, bail out! raise meta.model.DoesNotExist( "{0} does not have a translation for the current language!\n" "{0} ID #{1}, language={2}{3}".format(self._meta.verbose_name, self.pk, language_code, fallback_msg or '' ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_any_translated_model(self, meta=None): """ Return any available translation. Returns None if there are no translations at all. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_prefetched_translations(self, meta=None): """ Return the queryset with prefetch results. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_unique(self, exclude=None): """ Also validate the unique_together of the translated model. """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_extension_by_field(self, name): """ Find the ParlerOptions object that corresponds with the given translated field. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_master(new_class): """ Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_queryset(self, request): """ Make sure the current language is selected. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_languages_column(self, object): """ The language column which can be included in the ``list_display``. It also shows untranslated languages """
all_languages = [code for code, __ in settings.LANGUAGES] return mark_safe( self._languages_column( object, all_languages, span_classes='all-languages' ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_available_languages(self, obj): """ Fetching the available languages as queryset. """
if obj: return obj.get_available_languages() else: return self.model._parler_meta.root_model.objects.none()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_object(self, request, object_id, *args, **kwargs): """ Make sure the object is fetched in the correct language. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_urls(self): """ Add a delete-translation view. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): """ Insert the language tabs. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deletion_not_allowed(self, request, obj, language_code): """ Deletion-not-allowed view. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_inline_translations(self, request, language_code, obj=None): """ Fetch the inline translations """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_change_form_template(self): """ Determine what the actual `change_form_template` should be. """
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" ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_formset(self, request, obj=None, **kwargs): """ Return the formset, and provide the language information to the formset. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_available_languages(self, obj, formset): """ Fetching the available inline languages as queryset. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def language(self, language_code=None): """ Set the language code to assign to objects retrieved using this QuerySet. """
if language_code is None: language_code = appsettings.PARLER_LANGUAGES.get_default_language() self._language = language_code return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_multilingual_project(site_id=None): """ Whether the current Django project is configured for multilingual support. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __timestamp(): """Generate timestamp data for pyc header."""
today = time.time() ret = struct.pack(b'=L', int(today)) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_scripts_resource(pe): """Return the PYTHONSCRIPT resource entry."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resource_dump(pe, res): """Return the dump of the given resource."""
rva = res.data.struct.OffsetToData size = res.data.struct.Size dump = pe.get_data(rva, size) return dump
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_co_from_dump(data): """Return the code objects from the dump."""
# 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_py2exe_file(pe): """Check file is a py2exe executable."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_code_objects(pe): """Extract Python code objects from a py2exe executable."""
script_res = _get_scripts_resource(pe) dump = _resource_dump(pe, script_res) return _get_co_from_dump(dump)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_to_pyc(co, python_version, output_dir): """Save given code_object as a .pyc file."""
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpy2exe(filename, python_version=None, output_dir=None): """Process input params and produce output pyc files."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def are_all_nodes_discovered(self): """Reports whether there are nodes whose node info is still unknown."""
undiscovered = self.find_all(lambda e: not e.discovered) return len(list(undiscovered)) == 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _path(self, attrpath): """Returns the namespace object at the given .-separated path, creating any namespaces in the path that don't already exist."""
attr, _, subpath = attrpath.partition(".") if attr not in self.__dict__: self.__dict__[attr] = Namespace() self.__namespaces.add(attr) if subpath: return self.__dict__[attr]._path(subpath) else: return self.__dict__[attr]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add(self, data_bytes): '''Feed ASCII string or bytes to the signature function''' try: if isinstance(data_bytes, basestring): # Python 2.7 compatibility data_bytes = map(ord, data_bytes) except NameError: if isinstance(data_bytes, str): # This branch will be taken on Python 3 data_bytes = map(ord, data_bytes) for b in data_bytes: self._crc ^= (b << 56) & Signature.MASK64 for _ in range(8): if self._crc & (1 << 63): self._crc = ((self._crc << 1) & Signature.MASK64) ^ Signature.POLY else: self._crc <<= 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_max_bitlen(self): """Returns total maximum bit length of the array, including length field if applicable."""
payload_max_bitlen = self.max_size * self.value_type.get_max_bitlen() return { self.MODE_DYNAMIC: payload_max_bitlen + self.max_size.bit_length(), self.MODE_STATIC: payload_max_bitlen }[self.mode]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dsdl_signature_source_definition(self): """ Returns normalized DSDL definition text. Please refer to the specification for details about normalized DSDL definitions. """
txt = StringIO() txt.write(self.full_name + '\n') def adjoin(attrs): return txt.write('\n'.join(x.get_normalized_definition() for x in attrs) + '\n') if self.kind == CompoundType.KIND_SERVICE: if self.request_union: txt.write('\n@union\n') adjoin(self.request_fields) txt.write('\n---\n') if self.response_union: txt.write('\n@union\n') adjoin(self.response_fields) elif self.kind == CompoundType.KIND_MESSAGE: if self.union: txt.write('\n@union\n') adjoin(self.fields) else: error('Compound type of unknown kind [%s]', self.kind) return txt.getvalue().strip().replace('\n\n\n', '\n').replace('\n\n', '\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data_type_signature(self): """ Computes data type signature of this type. The data type signature is guaranteed to match only if all nested data structures are compatible. Please refer to the specification for details about signatures. """
if self._data_type_signature is None: sig = Signature(self.get_dsdl_signature()) fields = self.request_fields + self.response_fields if self.kind == CompoundType.KIND_SERVICE else self.fields for field in fields: field_sig = field.type.get_data_type_signature() if field_sig is not None: sig_value = sig.get_value() sig.add(bytes_from_crc64(field_sig)) sig.add(bytes_from_crc64(sig_value)) self._data_type_signature = sig.get_value() return self._data_type_signature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Stops the instance and closes the allocation table storage. """
self._handle.remove() self._node_monitor_event_handle.remove() self._allocation_table.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pretty_filename(filename): '''Returns a nice human readable path to 'filename'.''' try: a = os.path.abspath(filename) r = os.path.relpath(filename) except ValueError: # Catch relpath exception. Happens, because it can not produce relative path # if wroking directory is on different drive. a = r = filename return a if '..' in r else r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_event(self, event): """Appends event to the file."""
# Check if event is of type event_pb2.Event proto. if not isinstance(event, event_pb2.Event): raise TypeError("expected an event_pb2.Event proto, " " but got %s" % type(event)) return self._write_serialized_event(event.SerializeToString())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Flushes the event file to disk."""
if self._num_outstanding_events == 0 or self._recordio_writer is None: return self._recordio_writer.flush() if self._logger is not None: self._logger.info('wrote %d %s to disk', self._num_outstanding_events, 'event' if self._num_outstanding_events == 1 else 'events') self._num_outstanding_events = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Flushes the pending events and closes the writer after it is done."""
self.flush() if self._recordio_writer is not None: self._recordio_writer.close() self._recordio_writer = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Flushes the event file to disk and close the file. Call this method when you do not need the summary writer anymore. """
if not self._closed: self.add_event(self._sentinel_event) self.flush() self._worker.join() self._ev_writer.close() self._closed = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_record(self, event_str): """Writes a serialized event to file."""
header = struct.pack('Q', len(event_str)) header += struct.pack('I', masked_crc32c(header)) footer = struct.pack('I', masked_crc32c(event_str)) self._writer.write(header + event_str + footer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Closes the record writer."""
if self._writer is not None: self.flush() self._writer.close() self._writer = None