output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _find_combo_match(path):
"""
Calculate the key to check the MEDIASYNC['JOINED'] dict for, perform the
lookup, and return the matching key string if a match is found. If no
match is found, return None instead.
"""
key_str = _form_key_str(path)
if not key_str:
# _form_key_str() say... | Create a Python 3 function to
find the combo file key for a given path. | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to serve a media asset. | Here you have a function in Python 3, explain what it does
def static_serve(request, path, client):
if msettings['SERVE_REMOTE']:
# We're serving from S3, redirect there.
url = client.remote_media_url().strip('/') + '/%(path)s'
return redirect(url, permanent=True)
if not msettings[... | As a Python code composer, you craft elegant and concise scripts. |
def start_server(self, port_number, number_of_procs=0):
"""
Create a HTTP server and start it.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the ... | Write a Python 3 script for
creating a HTTP server and start it. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run(self, port_number, number_of_procs=0):
"""
Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the applic... | Can you create a Python 3 function that
creates the server and run the IOLoop. | As a python code expert, you are capable of creating scripts from specifications. |
Decorator to set the short_description attribute of a resource. | Explain what the following Python 3 code does
def short_description(description):
def decorator(func):
if isinstance(func, property):
func = func.fget
func.short_description = description
return func
return decorator | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds configuration parameters from a Python module. | Explain what the following Python 3 code does
def add_module(self, module):
'''
Adds configuration parameters from a Python module.
'''
for key, value in module.__dict__.iteritems():
if key[0:2] != '__':
self.__setattr__(attr=key, value=value) | As a python code expert, you are capable of creating scripts from specifications. |
Redirects the user to the login page passing the given next page | Can you tell what is the following Python 3 function doing
def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME):
resolved_url = reverse('IS:login')
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if object is authorized and if object is not found and if object is authorized redirect to login page. | How would you explain what the following Python 3 function does
def _check_permission(self, name, obj=None):
def redirect_or_exception(ex):
if not self.request.user or not self.request.user.is_authenticated:
if self.auto_login_redirect:
redirect_to_login(self.requ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
... | Write a Python 3 function that can
use when the plot method defined does not create a figure nor calls save_plot Then the plot method has to use self. fig | As a python code expert, you are capable of creating scripts from specifications. |
def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
"""Not functional -- TODO"""
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bit... | How would you code a function in Python 3 to
save an animation to a file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def guess_server_name():
"""We often use the same servers, which one are we running on now ?"""
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou':... | How would you code a function in Python 3 to
guess the server name based on environment variables. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a model instance in db. session. | How would you explain what the following Python 3 function does
def get_instance(cls, instance_or_pk):
if isinstance(instance_or_pk, cls):
if instance_or_pk in cls._flask_signalbus_sa.session:
return instance_or_pk
instance_or_pk = inspect(cls).primary_key_from_instance(... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a locked model instance in db. session. | Given the following Python 3 function, write the documentation
def lock_instance(cls, instance_or_pk, read=False):
mapper = inspect(cls)
pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key]
pk_values = cls.get_pk_values(instance_or_pk)
clause = and_(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_pk_values(cls, instance_or_pk):
"""Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
"""
if isinstance(instance_or_pk, cls):
cls._flask_si... | How would you code a function in Python 3 to
return a tuple of values for the current primary key. | You are a Python code generator, capable of creating scripts from specifications. |
Re - raise DBSerializationError if an IntegrityError occurs. | Explain what the following Python 3 code does
def retry_on_integrity_error(self):
session = self.session
assert session.info.get(_ATOMIC_FLAG_SESSION_INFO_KEY), \
'Calls to "retry_on_integrity_error" must be wrapped in atomic block.'
session.flush()
try:
yield
... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_fieldtranslations(instance, field=None, lang=None):
"""
Get all the translations for this object.
"""
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"]... | Write a Python 3 script for
getting all the translations for this object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Loads all translations as dynamic attributes | Explain what the following Python 3 code does
def _load_translations(instance, lang=None):
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for this language
field_lang = trans_attr(translation_i.field, t... | As a Python code composer, you craft elegant and concise scripts. |
This function sets the object s translatable fields to the values in the dict. | Explain what the following Python 3 code does
def _set_dict_translations(instance, dict_translations):
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one language there is no need of saving translations
if site_is_mono... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslat... | Create a Python 3 function for
adding the translations to the object. | As a Python code composer, you craft elegant and concise scripts. |
Encrypt a file inline with an optional passphrase. | Explain what the following Python 3 code does
def encrypt_file_inline(filename, passphrase):
key = key_generators.key_from_file(filename, passphrase)
inline_transform(filename, key)
return key | You are a Python code architect, reviewing and designing scalable and efficient code |
Encrypt a given file with the given key and replaces it directly with any extra extra
space requirement. | Here you have a function in Python 3, explain what it does
def inline_transform(filename, key):
pos = 0
for chunk, fp in iter_transform(filename, key):
fp.seek(pos)
fp.write(chunk)
fp.flush()
pos = fp.tell() | As a Python code analyst, you investigate and solve complex coding mysteries |
def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt ... | Implement a Python 3 function for
generating encrypted file with given key. This generator function reads the file in chunks and encrypts them using AES-CTR, with the specified key. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str :return... | You are a Python code analyst, evaluating scripts for potential improvements. |
def set(self, name, permission):
"""
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance
"""
assert isinstance(permission, BasePermission), 'On... | Can you write a function in Python 3 where it
adds a permission to the set. | As a Python code analyst, you investigate and solve complex coding mysteries |
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
wid... | Implement a function in Python 3 to
render the field using the passed widget. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a function which creates a schema class for all signal models. | Given the following Python 3 function, write the documentation
def _setup_schema(Base, session):
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
model = m
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
def get_signal_models(self):
"""Return all signal types in a list.
:rtype: list(`signal-model`)
"""
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
... | Implement a Python 3 function for
returning all signal types in a list. | You are a Python code analyst, evaluating scripts for potential improvements. |
def flush(self, models=None, wait=3.0):
"""Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after o... | Write a Python 3 script to
flush all pending signals over the message bus. | You are a Python code analyst, evaluating scripts for potential improvements. |
def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
s... | Write a Python 3 function that can
send a potentially huge number of pending signals over the message bus. | As a Python code analyst, you investigate and solve complex coding mysteries |
This method returns the requested status. | Explain what the following Python 3 code does
def get(self, status_code):
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_code}
if self.get_query_argument('reason', None):
kwargs['reason'] = self.get_query_argument('reason')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the absolute path of the path argument. | Can you generate a brief explanation for the following Python 3 code
def get_absolute_path(self, path):
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return ro... | Create a Python 3 function for
returning all absolute paths to the roles directories while considering the BASEDIR and ROLES config variables. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a key - value dict with a roles. | Here you have a function in Python 3, explain what it does
def get_roles(self):
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
... | You are a Python code generator, capable of creating scripts from specifications. |
def read_yaml(self, filename):
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | Write a Python 3 function for
reading and parses a YAML file and returns the content. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and... | How would you implement a function in Python 3 that
reads all YAML files inside the dir_path and returns a list of all the items in the order they were found. | As a Python code analyst, you investigate and solve complex coding mysteries |
Cleans string quoting in response. | Explain what the following Python 3 code does
def clean_response(response):
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | You are a Python code architect, reviewing and designing scalable and efficient code |
def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
"""Return function decorator that executes the function again in case of a deadlock."""
def decorator(action):
"""Function decorator that retries `action` in case of a deadlock."""
@wraps(action)
def f(*args, **kwa... | How would you code a function in Python 3 to
return decorator that retries the given function if the number of retries is greater than min_wait. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator for functions evaluated only once. | Can you tell what is the following Python 3 function doing
def cached(f):
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | You are a Python code generator, capable of creating scripts from specifications. |
Return a FormSet for the given form class. | Can you tell what is the following Python 3 function doing
def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
"""Return a FormSet for the given form class."""
if max_num is ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Contains formset save prepare obj for saving | Can you generate a brief explanation for the following Python 3 code
def save_form(self, form, **kwargs):
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | Write a Python 3 function for
getting the value of the method returning the specified field. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get object according to pk or get object from get_obj method. | Can you generate a brief explanation for the following Python 3 code
def _get_perm_obj_or_404(self, pk=None):
if pk:
obj = get_object_or_none(self.core.model, pk=pk)
else:
try:
obj = self.get_obj(False)
except Http404:
obj = get_object_... | As a python code expert, you are capable of creating scripts from specifications. |
def view_all(request, language, filter=None):
"""
View all translations that are in site.
"""
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language... | Can you write a function in Python 3 where it
views all translations that are in site. | As a Python code analyst, you investigate and solve complex coding mysteries |
def edit(request, translation):
"""
Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection.
"""
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel... | Write a Python 3 function for
editing a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection. | You are a Python code generator, capable of creating scripts from specifications. |
Export translations to a file. | Can you tell what is the following Python 3 function doing
def export_translations(request, language):
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_tra... | Write a Python 3 script to
update translations for new objects in database. | As a Python code composer, you craft elegant and concise scripts. |
Send GET request with given url. | Here you have a function in Python 3, explain what it does
def client_get(self, url, **kwargs):
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
sta... | You are a Python code analyst, evaluating scripts for potential improvements. |
def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Excep... | Implement a Python 3 function for
sending POST request with given url and keyword args. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def client_delete(self, url, **kwargs):
"""Send POST request with given url."""
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=r... | Can you create a Python 3 function that
sends POST request with given url. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of all followed projects. | Here you have a function in Python 3, explain what it does
def list_projects(self):
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | As a python code expert, you are capable of creating scripts from specifications. |
def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
... | Implement a Python 3 function for
triggering a new build and return a summary of the build. | You are a Python code generator, capable of creating scripts from specifications. |
Cancel the build and return its summary. | Here you have a function in Python 3, explain what it does
def cancel(self, username, project, build_num):
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=proje... | You are a Python code generator, capable of creating scripts from specifications. |
Return information about recent builds across all projects. | Explain what the following Python 3 code does
def recent_all_projects(self, limit=30, offset=0):
method = 'GET'
url = ('/recent-builds?circle-token={token}&limit={limit}&'
'offset={offset}'.format(token=self.client.api_token,
limit=limit,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns status of recent builds for given project and branch. | Given the following Python 3 function, write the documentation
def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""):
method = 'GET'
if branch is not None:
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}&limit={li... | As a Python code analyst, you investigate and solve complex coding mysteries |
Clear the cache for given project. | Here you have a function in Python 3, explain what it does
def clear(self, username, project):
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def post(self, request, format=None):
"""
Add a new Channel.
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
re... | How would you code a function in Python 3 to
add a new Channel. | As a Python code composer, you craft elegant and concise scripts. |
def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
... | Can you implement a function in Python 3 that
updates an existing Channel record | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sha256_file(path):
"""Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method
"""
h = hashlib.sha256()
with open(path, 'rb')... | Can you implement a function in Python 3 that
calculates sha256 hex digest of a file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculate a convergent encryption key for a file. | How would you explain what the following Python 3 function does
def key_from_file(filename, passphrase):
hexdigest = sha256_file(filename)
if passphrase is None:
passphrase = DEFAULT_HMAC_PASSPHRASE
return keyed_hash(hexdigest, passphrase) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def keyed_hash(digest, passphrase):
"""Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str
"""
encodedPassphrase = passphrase.e... | Create a Python 3 function to
calculate a HMAC / keyed hash. | As a Python code analyst, you investigate and solve complex coding mysteries |
Search for a tag among direct children of the s - expression. | How would you explain what the following Python 3 function does
def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | You are a Python code analyst, evaluating scripts for potential improvements. |
Helper function for building an attribute dictionary. | Can you generate a brief explanation for the following Python 3 code
def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | As a Python code analyst, you investigate and solve complex coding mysteries |
Return value - related substitutions. | Make a summary of the following Python 3 code
def get_template_substitution_values(self, value):
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns True or False according to number of objects in queryset. | How would you explain what the following Python 3 function does
def is_restricted(self):
return (
not hasattr(self.choices, 'queryset') or
self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES
) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a Three object that can be queried against. | How would you explain what the following Python 3 function does
def city(name=None):
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | You are a Python code architect, reviewing and designing scalable and efficient code |
def dev(endpoint, **kwargs):
"""
Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development.
"""
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kw... | How would you code a function in Python 3 to
use an endpoint and any additional keyword arguments rather than one . | As a Python code analyst, you investigate and solve complex coding mysteries |
def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('field... | Create a Python 3 function for
returning a list of field names from an admin fieldsets structure. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_vie... | How would you implement a function in Python 3 that
returns a list of field names from an admin fieldsets structure. | As a Python code composer, you craft elegant and concise scripts. |
def get_inline_views_opts_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif '... | Can you create a Python 3 function that
returns a list of field names from an admin fieldsets structure. | As a python code expert, you are capable of creating scripts from specifications. |
def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
"""
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: v... | Can you create a Python 3 function that
returns the readonly data for the given field or method. | You are a Python code generator, capable of creating scripts from specifications. |
Returns humanized value of object that can be rendered to HTML or returned as part of REST
| Can you generate the documentation for the following Python 3 function
def display_object_data(obj, field_name, request=None):
from is_core.forms.utils import ReadonlyValue
value, _, _ = get_readonly_field_data(field_name, obj)
return display_for_value(value.humanized_value if isinstance(value, ReadonlyVal... | You are a Python code generator, capable of creating scripts from specifications. |
Displays the value for the object in the order they are assigned. | How would you explain what the following Python 3 function does
def display_for_value(value, request=None):
from is_core.utils.compatibility import admin_display_for_value
if request and isinstance(value, Model):
return render_model_object_with_link(request, value)
else:
return (
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns object URL from model core. | How would you explain what the following Python 3 function does
def get_url_from_model_core(request, obj):
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
... | As a Python code composer, you craft elegant and concise scripts. |
Returns object URL if current logged user has permissions to see the object | How would you explain what the following Python 3 function does
def get_obj_url(request, obj):
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def protect_api(uuid=None, **kwargs):
"""Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory.
"""
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, v... | How would you implement a function in Python 3 that
retrieves object and check permissions. | As a python code expert, you are capable of creating scripts from specifications. |
def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | Write a Python 3 function that can
return a table as a dataframe. | As a python code expert, you are capable of creating scripts from specifications. |
Create a table and populate it with data from a dataframe. | Make a summary of the following Python 3 code
def insert_df(self, table_name, df):
df.to_sql(table_name, con=self.own_conn) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the number of rows in a table by counting them. | Make a summary of the following Python 3 code
def count_rows(self, table_name):
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | As a Python code composer, you craft elegant and concise scripts. |
Return the number of entries in all tables. | Can you generate the documentation for the following Python 3 function
def tables_with_counts(self):
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert the database to SQLite. | Explain what the following Python 3 code does
def convert_to_sqlite(self, destination=None, method="shell", progress=False):
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if destination is None: destination = self.r... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a text dump compatible with SQLite by using
shell commands. Place this script at script_path *. | Given the following Python 3 function, write the documentation
def sqlite_dump_shell(self, script_path):
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds things up when importing #
script_path.append("\n\n\nBEGIN... | As a Python code analyst, you investigate and solve complex coding mysteries |
def sqlite_dump_string(self, progress):
"""Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string."""
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transa... | Write a Python 3 script to
generate a text dump compatible with SQLite. | As a python code expert, you are capable of creating scripts from specifications. |
def import_table(self, source, table_name):
"""Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment."""
# Run commands #
wsl = sh.Command("wsl.exe")
table_sch... | Implement a function in Python 3 to
copy a table from another Access database to this one. | You are a Python code generator, capable of creating scripts from specifications. |
def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a
jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+
qKgIIHL8Znb39u72znWJiWP3+9l473fzm... | Create a Python 3 function for
creating a new empty MDB at destination. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | Write a Python 3 function that can
make a new connection. | As a python code expert, you are capable of creating scripts from specifications. |
Check that the file exists optionally downloads it. | Given the following Python 3 function, write the documentation
def prepare(self):
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
download_from_url(self.retrieve, self.path, progress=True)
else: raise Exception(... | As a Python code composer, you craft elegant and concise scripts. |
def create(self, columns=None, type_map=None, overwrite=False):
"""Create a new database with a certain schema."""
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we wan... | Create a Python 3 function for
creating a new database with a certain schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_table(self, name, columns, type_map=None, if_not_exists=False):
"""Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})"""
# Check types mapping #
if type_map is None and isinstance(col... | Write a Python 3 script to
add a new table to the database. | As a Python code composer, you craft elegant and concise scripts. |
Return the list of columns for a particular table by querying the SQL for the complete list of column names. | How would you explain what the following Python 3 function does
def get_columns_of_table(self, table=None):
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A PRAGMA statement will implicitly issue a commit, don't use #
... | As a python code expert, you are capable of creating scripts from specifications. |
Add entries to a table. | Explain what the following Python 3 code does
def add(self, entries, table=None, columns=None, ignore=False):
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
# Default columns #
question_ma... | You are a Python code generator, capable of creating scripts from specifications. |
Add entries to the main table. | Given the following Python 3 function, write the documentation
def add_by_steps(self, entries_by_step, table=None, columns=None):
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | As a Python code analyst, you investigate and solve complex coding mysteries |
Just the first entry. | Given the following Python 3 function, write the documentation
def get_first(self, table=None):
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | You are a Python code generator, capable of creating scripts from specifications. |
def get_number(self, num, table=None):
"""Get a specific entry by its number."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num))
return self.own_cursor.fetchone() | How would you implement a function in Python 3 that
gets a specific entry by its number. | As a Python code composer, you craft elegant and concise scripts. |
Get a specific entry. | Explain what the following Python 3 code does
def get_entry(self, key, column=None, table=None):
if table is None: table = self.main_table
if column is None: column = "id"
if isinstance(key, basestring): key = key.replace("'","''")
query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;'... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a table and populate it with data from a dataframe. | Given the following Python 3 function, write the documentation
def insert_df(self, table_name, df):
df.to_sql(table_name, con=self.own_connection) | As a Python code composer, you craft elegant and concise scripts. |
def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
... | Implement a function in Python 3 to
get specific entries and order them in the same way. | You are a Python code generator, capable of creating scripts from specifications. |
Copy a table from another SQLite database to this one. | Can you tell what is the following Python 3 function doing
def import_table(self, source, table_name):
query = "SELECT * FROM `%s`" % table_name.lower()
df = pandas.read_sql(query, source.connection)
df.to_sql(table_name, con=self.own_connection) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a jsonified version of the exception. | Make a summary of the following Python 3 code
def jsonify(self, status_code=None, message=None, headers=None):
if status_code is None:
status_code = self.status_code
if message is None:
message = self.message
if headers is None:
headers = self.headers
... | You are a Python code generator, capable of creating scripts from specifications. |
Builds a generic error handler that packages a flask_buzz exception
so that it can be handled nicely by flask s error handler. | Can you tell what is the following Python 3 function doing
def build_error_handler(*tasks):
def _handler(error, tasks=[]):
[t(error) for t in tasks]
return error.jsonify(), error.status_code, error.headers
return functools.partial(_handler, tasks=tasks) | You are a Python code analyst, evaluating scripts for potential improvements. |
Build a generic error handler that packages a flask_buzz exception
so that it can be handled by the Flask - restplus error handler. | Can you tell what is the following Python 3 function doing
def build_error_handler_for_flask_restplus(*tasks):
def _handler(error, tasks=[]):
[t(error) for t in tasks]
response = error.jsonify()
return flask.json.loads(response.get_data()), response.status_code
retur... | You are a Python code architect, reviewing and designing scalable and efficient code |
Registers an error handler for FlaskBuzz derived errors that are not currently imported. | Can you tell what is the following Python 3 function doing
def register_error_handler_with_flask_restplus(cls, api, *tasks):
for buzz_subclass in [cls] + cls.__subclasses__():
api.errorhandler(buzz_subclass)(
cls.build_error_handler_for_flask_restplus(*tasks)
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.