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_... |
<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_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... |
<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.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 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 resul... |
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 = op... |
if shutterLevel is None:
shutterLevel = self.shutterLevel
data = {
"channelIndex": 1,
"deviceId": self.id,
"slatsLevel": slatsLevel,
"shutterLevel": shutterLevel,
}
return self._restCall("device/control/setSlatsLevel", json.dum... |
<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 `HmipConnectionEr... |
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(
... |
<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 maste... |
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': andro... |
<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 mas... |
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_co... |
<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 probabilist... |
<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
'''
... |
<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_t... |
<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)
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 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 ^ ... |
<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.rep... |
<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
... |
<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 st... |
<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:
... |
<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 na... |
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('$', '\\$').repla... |
<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 ... |
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
... |
<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 `... |
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:
t... |
<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... |
<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,... |
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_nam... |
<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. Whe... |
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... |
<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 ... |
<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):
... |
<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 stri... |
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... |
<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 dis... |
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.
... |
<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, ... |
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('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 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
... |
<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 s... |
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_l... |
<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.iter... |
<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 objec... |
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_cod... |
<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 relat... |
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:
tran... |
<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 languag... |
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 directl... |
<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 Adde... |
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 ... |
<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:
... |
<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.
... |
<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 quer... |
# 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._prefetch... |
<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._transla... |
<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 additi... |
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 ho... |
<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 ... |
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=Tr... |
<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 = ... |
<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.... |
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.
# Fall... |
<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__))
# Appl... |
<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/(... |
<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)
... |
<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)
... |
<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. T... |
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_co... |
<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.
... |
<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... |
<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
... |
<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, on... |
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 ... |
<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... |
# 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... |
<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 = ''
wh... |
<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... |
<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)
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 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... |
<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 ... |
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')
... |
<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 structur... |
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... |
<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... |
<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_... |
<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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.