output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def find_collections(
self,
search_pattern="",
identifier="",
fetched=0,
page=1,
page_size=30,
sort_by=None,
):
"""
Fetches a list of all resource IDs for every resource in the database.
:param string search_pattern: A search pattern t... | Write a Python 3 function for
fetching a list of all resource IDs for every resource in the database. | You are a Python code generator, capable of creating scripts from specifications. |
def augment_resource_ids(self, resource_ids):
"""
Given a list of resource IDs, returns a list of dicts containing detailed information about the specified resources and their children.
This function recurses to a maximum of two levels when fetching children from the specified resources.
... | Write a Python 3 script to
give a list of resource IDs, returns a list of dicts containing detailed information about the specified resources and their children. This function recurses to a maximum of two levels when fetching children from the specified resources. Consult the documentation of ArchivistsToolkitClient.ge... | You are a Python code generator, capable of creating scripts from specifications. |
def add_digital_object(
self,
information_object_slug,
identifier=None,
title=None,
uri=None,
location_of_originals=None,
object_type=None,
xlink_show="embed",
xlink_actuate="onLoad",
restricted=False,
use_statement="",
use_... | Can you implement a function in Python 3 that
adds a digital object to the current object. | You are a Python code generator, capable of creating scripts from specifications. |
Adds a new child record to the current record. | Given the following Python 3 function, write the documentation
def add_child(
self,
parent_slug=None,
title="",
level="",
start_date=None,
end_date=None,
date_expression=None,
notes=[],
):
"""
Adds a new resource component parented with... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete_record(self, record_id):
"""
Delete a record with record_id.
"""
self._delete(
urljoin(self.base_url, "informationobjects/{}".format(record_id)),
expected_response=204,
)
return {"status": "Deleted"} | Write a Python 3 function for
deleting a record with record_id. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_string_dict(self, plugin_info):
"""
Convert a section with information of priorities to a string dict.
To avoid typos we make all letters lower case when comparing
Arguments:
plugin_info (dict): A dictionary with plugin information
R... | Write a Python 3 function for
converting a section with information of priorities to a string dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if the version entry is in the proper format. | Can you generate the documentation for the following Python 3 function
def version_check(self):
try:
version_info = self['Version']
except KeyError:
raise ValidateError('Config file has to have a Version section')
try:
float(version_info['version'])
ex... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if the section is in the proper format. | Make a summary of the following Python 3 code
def check_plugin(self, plugin):
vcf_section = self[plugin]
try:
vcf_field = vcf_section['field']
if not vcf_field in self.vcf_columns:
raise ValidateError(
"field has to be in... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a nx. DiGraph equivalent of given dict. | Here you have a function in Python 3, explain what it does
def dict_to_nx(graph, oriented=False):
nxg = nx.DiGraph() if oriented else nx.Graph()
for node, succs in graph.items():
for succ in succs:
nxg.add_edge(node, succ)
return nxg | You are a Python code generator, capable of creating scripts from specifications. |
Get the full current set of B3 values. | Can you generate the documentation for the following Python 3 function
def values():
result = {}
try:
# Check if there's a sub-span in progress, otherwise use the main span:
span = g.get("subspan") if "subspan" in g else g
for header in b3_headers:
result[header] = span.get(h... | As a python code expert, you are capable of creating scripts from specifications. |
Starts a new Zipkin Trace ID and span ID. | Here you have a function in Python 3, explain what it does
def start_span(request_headers=None):
global debug
try:
headers = request_headers if request_headers else request.headers
except RuntimeError:
# We're probably working outside the Application Context at this point, likely on startup:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Start a new sub - span for a downstream service call. | Can you generate a brief explanation for the following Python 3 code
def _start_subspan(headers=None):
b3 = values()
g.subspan = {
# Propagate the trace ID
b3_trace_id: b3[b3_trace_id],
# Start a new span for the outgoing request
b3_span_id: _generate_identifier(),
# S... | You are a Python code generator, capable of creating scripts from specifications. |
Generates a new 64 - bit random identifier in B3 format. | Can you tell what is the following Python 3 function doing
def _generate_identifier():
bit_length = 64
byte_length = int(bit_length / 8)
identifier = os.urandom(byte_length)
return hexlify(identifier).decode('ascii') | As a Python code composer, you craft elegant and concise scripts. |
The initial view of the pub document | Can you generate the documentation for the following Python 3 function
def pub_view(request, docid, configuration):
if 'autodeclare' in settings.CONFIGURATIONS[configuration]:
for annotationtype, set in settings.CONFIGURATIONS['configuration']['autodeclare']:
try:
r = flat.comm.q... | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks the foliadocserve version returns 1 if the document is newer than the library 0 if it is older | Here you have a function in Python 3, explain what it does
def checkversion(version):
try:
for refversion, responseversion in zip([int(x) for x in REQUIREFOLIADOCSERVE.split('.')], [int(x) for x in version.split('.')]):
if responseversion > refversion:
return 1 #response is newer... | You are a Python code generator, capable of creating scripts from specifications. |
def initdoc(request, namespace, docid, mode, template, context=None, configuration=None):
"""Initialise a document (not invoked directly)"""
perspective = request.GET.get('perspective','document')
if context is None: context = {}
if 'configuration' in request.session:
configuration = request.ses... | Can you create a Python 3 function that
initialises a document (not invoked directly) | As a python code expert, you are capable of creating scripts from specifications. |
This function is used to make the actual query | Make a summary of the following Python 3 code
def query_helper(request,namespace, docid, configuration=None):
flatargs = {
'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search results
}
#stupid compatibil... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the content of a single document | Can you tell what is the following Python 3 function doing
def pub_poll(request, docid):
try:
r = flat.comm.get(request, '/poll/pub/' + docid + '/', False)
except URLError:
return HttpResponseForbidden("Unable to connect to the document server [viewer/poll]")
return HttpResponse(r, content_t... | You are a Python code analyst, evaluating scripts for potential improvements. |
def prepare(_next, self):
"""Hook after prepare and set 'id' disabled.
"""
_next(self)
if not self.autoincrement_support:
return
id_field = self.form['id']
del id_field.attrs['required']
id_field.attrs['disabled'] = 'disabled'
id_field.getter =... | Can you create a Python 3 function that
hooks after prepare and set id disabled. | As a python code expert, you are capable of creating scripts from specifications. |
Delete user from database. | Can you tell what is the following Python 3 function doing
def delete_user_action(model, request):
try:
users = model.parent.backend
uid = model.model.name
del users[uid]
users()
model.parent.invalidate()
localizer = get_localizer(request)
message = localizer.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add user to group. | Can you tell what is the following Python 3 function doing
def user_add_to_group_action(model, request):
group_id = request.params.get('id')
if not group_id:
group_ids = request.params.getall('id[]')
else:
group_ids = [group_id]
try:
user = model.model
validate_add_users_... | You are a Python code generator, capable of creating scripts from specifications. |
def delete_group_action(model, request):
"""Delete group from database.
"""
try:
groups = model.parent.backend
uid = model.model.name
del groups[uid]
groups()
model.parent.invalidate()
except Exception as e:
return {
'success': False,
... | Can you implement a function in Python 3 that
deletes group from database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add user to group. | Given the following Python 3 function, write the documentation
def group_add_user_action(model, request):
user_id = request.params.get('id')
if not user_id:
user_ids = request.params.getall('id[]')
else:
user_ids = [user_id]
try:
group = model.model
validate_add_users_to_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Hook after prepare and set principal_roles as selection to
form. | Can you generate the documentation for the following Python 3 function
def prepare(_next, self):
_next(self)
if not self.roles_support:
return
if not self.request.has_permission('manage', self.model.parent):
# XXX: yafowil selection display renderer
return
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def expiration_extractor(widget, data):
"""Extract expiration information.
- If active flag not set, Account is disabled (value 0).
- If active flag set and value is UNSET, account never expires.
- If active flag set and datetime choosen, account expires at given
datetime.
- Timestamp in seco... | Implement a Python 3 function for
extracting expiration information from widget. | You are a Python code generator, capable of creating scripts from specifications. |
Hook after prepare and set expiration widget to
self. form. | Explain what the following Python 3 code does
def prepare(_next, self):
_next(self)
cfg = ugm_general(self.model)
if cfg.attrs['users_account_expiration'] != 'True':
return
mode = 'edit'
if not self.request.has_permission(
'manage_expiration', self.mod... | You are a Python code analyst, evaluating scripts for potential improvements. |
XXX: needs polishing. Return configured default portrait if not set
on user. | Explain what the following Python 3 code does
def portrait_image(model, request):
response = Response()
cfg = ugm_general(model)
response.body = model.attrs[cfg.attrs['users_portrait_attr']]
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Cache-Control'] = 'max-age=0'
return re... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Hook after prepare and set portrait as image widget to
self. form. | Here you have a function in Python 3, explain what it does
def prepare(_next, self):
_next(self)
if not self.portrait_support:
return
model = self.model
request = self.request
if request.has_permission('edit_user', model.parent):
mode = 'edit'
else... | As a Python code analyst, you investigate and solve complex coding mysteries |
def local_manager_consider_for_user(self):
"""Flag whether local manager ACL should be considered for current
authenticated user.
"""
if not self.local_management_enabled:
return False
request = get_current_request()
if authenticated_userid(request) == securit... | Write a Python 3 function that can
flag whether local manager ACL should be considered for current authenticated user. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the local manager group id of current authenticated member. | Can you generate the documentation for the following Python 3 function
def local_manager_gid(self):
config = self.root['settings']['ugm_localmanager'].attrs
user = security.authenticated_user(get_current_request())
if not user:
return None
gids = user.group_ids
adm_gi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return rule for local manager. | Can you generate the documentation for the following Python 3 function
def local_manager_rule(self):
adm_gid = self.local_manager_gid
if not adm_gid:
return None
config = self.root['settings']['ugm_localmanager'].attrs
return config[adm_gid] | You are a Python code analyst, evaluating scripts for potential improvements. |
def local_manager_target_uids(self):
"""Target uid's for local manager.
"""
groups = self.root['groups'].backend
managed_uids = set()
for gid in self.local_manager_target_gids:
group = groups.get(gid)
if group:
managed_uids.update(group.mem... | Write a Python 3 function for
targeting uid s for local manager. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check whether the local manager group is default group. | Can you generate a brief explanation for the following Python 3 code
def local_manager_is_default(self, adm_gid, gid):
config = self.root['settings']['ugm_localmanager'].attrs
rule = config[adm_gid]
if gid not in rule['target']:
raise Exception(u"group '%s' not managed by '%s'" % (gi... | As a Python code analyst, you investigate and solve complex coding mysteries |
def form_field_definitions(self):
"""Hook optional_login extractor if necessary for form defaults.
"""
schema = copy.deepcopy(form_field_definitions.user)
uid, login = self._get_auth_attrs()
if uid != login:
field = schema.get(login, schema['default'])
if ... | Create a Python 3 function to
hook optional_login extractor if necessary for form defaults. | You are a Python code architect, reviewing and designing scalable and efficient code |
def remote_add_user(model, request):
"""Add user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
New user id.
... | Can you write a function in Python 3 where it
adds user via remote service. | You are a Python code analyst, evaluating scripts for potential improvements. |
def remote_delete_user(model, request):
"""Remove user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
Id of use... | Can you implement a function in Python 3 that
removes user via remote service. | As a Python code composer, you craft elegant and concise scripts. |
Load Synchronizer schema to display specific fields in administered by the user. | Given the following Python 3 function, write the documentation
def get_formset(self, request, obj=None, **kwargs):
if obj is not None:
try:
# this is enough to load the new schema
obj.external
except LayerExternal.DoesNotExist:
pass
... | You are a Python code generator, capable of creating scripts from specifications. |
A thread which checks for new messages in the public pipe and broadcasts them to all connected clients. | Can you generate a brief explanation for the following Python 3 code
def public_broadcaster():
while __websocket_server_running__:
pipein = open(PUBLIC_PIPE, 'r')
line = pipein.readline().replace('\n', '').replace('\r', '')
if line != '':
WebSocketHandler.broadcast(line)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def private_messenger():
"""
Thread which runs in parallel and constantly checks for new messages
in the private pipe and sends them to the specific client.
If client is not connected the message is discarded.
"""
while __websocket_server_running__:
pipein = open(PRIVATE_PIPE, 'r')
... | Implement a function in Python 3 to
thread which checks for new messages in the private pipe and sends them to the specific client. | You are a Python code architect, reviewing and designing scalable and efficient code |
Save the antenna record. | Given the following Python 3 function, write the documentation
def save(self, *args, **kwargs):
if not self.pk and self.model.polarization:
self.polarization = self.model.polarization
super(Antenna, self).save(*args, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get(self, request, *args, **kwargs):
""" return list of open 311 services """
# init django rest framework specific stuff
serializer_class = self.get_serializer_class()
context = self.get_serializer_context()
# init empty list
services = []
# loop over each... | Can you create a Python 3 function that
returns list of open 311 services | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the serializer instance that should be used for validating and
deserializing input and serializing output. | Can you generate the documentation for the following Python 3 function
def get_serializer(self, instance=None, data=None,
many=False, partial=False):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
... | As a Python code composer, you craft elegant and concise scripts. |
def get(self, request, *args, **kwargs):
""" Retrieve list of service requests """
if 'service_code' not in request.GET.keys():
return Response({ 'detail': _('A service code must be inserted') }, status=404)
service_code = request.GET['service_code']
if service_code not in ... | Can you create a Python 3 function that
retrieves list of service requests | As a Python code analyst, you investigate and solve complex coding mysteries |
def post(self, request, *args, **kwargs):
""" Post a service request (requires authentication) """
service_code = request.data['service_code']
if service_code not in SERVICES.keys():
return Response({ 'detail': _('Service not found') }, status=404)
serializers = {
... | Create a Python 3 function to
post a new object in a service | As a python code expert, you are capable of creating scripts from specifications. |
def ready(self):
""" Add user info to ExtensibleNodeSerializer """
from nodeshot.core.nodes.base import ExtensibleNodeSerializer
from .models import Vote
from .serializers import (CommentRelationSerializer,
ParticipationSerializer)
ExtensibleNod... | Implement a function in Python 3 to
add user info to ExtensibleNodeSerializer | As a Python code composer, you craft elegant and concise scripts. |
send notification when a new node is created according to users s settings | Can you generate a brief explanation for the following Python 3 code
def node_created_handler(sender, **kwargs):
if kwargs['created']:
obj = kwargs['instance']
queryset = exclude_owner_of_node(obj)
create_notifications.delay(**{
"users": queryset,
"notification_model"... | As a python code expert, you are capable of creating scripts from specifications. |
def node_status_changed_handler(**kwargs):
""" send notification when the status of a node changes according to users's settings """
obj = kwargs['instance']
obj.old_status = kwargs['old_status'].name
obj.new_status = kwargs['new_status'].name
queryset = exclude_owner_of_node(obj)
create_notific... | Write a Python 3 script to
send notification when the status of a node changes according to users s settings | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns the diff of the current and latest entries | Can you generate a brief explanation for the following Python 3 code
def diff(self):
latest = self.latest
current = NetJsonParser(self.json())
return diff(current, latest) | You are a Python code generator, capable of creating scripts from specifications. |
returns a dict that represents a NetJSON NetworkGraph object | Make a summary of the following Python 3 code
def json(self):
nodes = []
links = []
for link in self.link_set.all():
if self.is_layer2:
source = link.interface_a.mac
destination = link.interface_b.mac
else:
source = str(lin... | You are a Python code architect, reviewing and designing scalable and efficient code |
def update(self):
"""
Updates topology
Links are not deleted straightaway but set as "disconnected"
"""
from .link import Link # avoid circular dependency
diff = self.diff()
status = {
'added': 'active',
'removed': 'disconnected',
... | Create a Python 3 function for
updating the topology with the current state of the entries in the diff table. | You are a Python code generator, capable of creating scripts from specifications. |
Call self. synchronizer. clean method | Make a summary of the following Python 3 code
def clean(self, *args, **kwargs):
if self.synchronizer_path != 'None' and self.config:
# call synchronizer custom clean
try:
self.synchronizer.load_config(self.config)
self.synchronizer.clean()
exce... | You are a Python code analyst, evaluating scripts for potential improvements. |
def save(self, *args, **kwargs):
"""
call synchronizer "after_external_layer_saved" method
for any additional operation that must be executed after save
"""
after_save = kwargs.pop('after_save', True)
super(LayerExternal, self).save(*args, **kwargs)
# call after_e... | Write a Python 3 script for
saving the object to the database | You are a Python code architect, reviewing and designing scalable and efficient code |
returns true if user has permission to edit the object | Can you generate the documentation for the following Python 3 function
def get_can_edit(self, obj):
view = self.context.get('view')
request = copy(self.context.get('request'))
request._method = 'PUT'
try:
view.check_object_permissions(request, obj)
except (PermissionD... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_details(self, obj):
""" returns uri of API image resource """
args = {
'slug': obj.node.slug,
'pk': obj.pk
}
return reverse('api_node_image_detail',
kwargs=args,
request=self.context.get('request', None)) | Implement a Python 3 function for
returning uri of API image resource | As a Python code analyst, you investigate and solve complex coding mysteries |
def has_permission(self, request, view):
""" applies to social-link-list """
if request.method == 'POST':
user = Profile.objects.only('id', 'username').get(username=view.kwargs['username'])
return request.user.id == user.id
return True | Write a Python 3 script to
return True if the user has permission to view the social - link - list. | As a Python code composer, you craft elegant and concise scripts. |
delete image when an image record is deleted | Can you tell what is the following Python 3 function doing
def delete(self, *args, **kwargs):
try:
os.remove(self.file.file.name)
# image does not exist
except (OSError, IOError):
pass
super(Image, self).delete(*args, **kwargs) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_quality(self, type='etx'):
""" used to determine color of links"""
if type == 'etx':
if 0 < self.etx < 1.5:
quality = 1
elif self.etx < 3:
quality = 2
else:
quality = 3
elif type == 'dbm':
if -8... | Can you write a function in Python 3 where it
uses to determine color of links | You are a Python code analyst, evaluating scripts for potential improvements. |
def new_nodes_allowed_for_layer(self):
"""
ensure new nodes are allowed for this layer
"""
if not self.pk and self.layer and not self.layer.new_nodes_allowed:
raise ValidationError(_('New nodes are not allowed for this layer')) | Write a Python 3 function that can
ensure new nodes are allowed for this layer | You are a Python code generator, capable of creating scripts from specifications. |
def nodes_minimum_distance_validation(self):
"""
if minimum distance is specified, ensure node is not too close to other nodes;
"""
if self.layer and self.layer.nodes_minimum_distance:
minimum_distance = self.layer.nodes_minimum_distance
# TODO - lower priority: do this check only when c... | Write a Python 3 script for
validating that the minimum distance of a node is less than the minimum distance of other nodes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Ensure that the node coordinates are contained in the area of the layer. | Can you tell what is the following Python 3 function doing
def node_contained_in_layer_area_validation(self):
# if area is a polygon ensure it contains the node
if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):
raise ValidationError(_('Node must be i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
intercepts changes to is_published and fires layer_is_published_changed signal | Make a summary of the following Python 3 code
def save(self, *args, **kwargs):
super(Layer, self).save(*args, **kwargs)
# if is_published of an existing layer changes
if self.pk and self.is_published != self._current_is_published:
# send django signal
layer_is_published_... | As a python code expert, you are capable of creating scripts from specifications. |
Update published nodes of current layer | Given the following Python 3 function, write the documentation
def update_nodes_published(self):
if self.pk:
self.node_set.all().update(is_published=self.is_published) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_unread(self, request, notifications, mark_as_read):
"""
return unread notifications and mark as read
(unless read=false param is passed)
"""
notifications = notifications.filter(is_read=False)
serializer = UnreadNotificationSerializer(list(notifications), # evalu... | How would you implement a function in Python 3 that
returns a list of unread notifications and mark as read | As a Python code composer, you craft elegant and concise scripts. |
def get_count(self, request, notifications, mark_as_read=False):
""" return count of unread notification """
return Response({'count': notifications.filter(is_read=False).count()}) | Create a Python 3 function to
return the count of unread notifications | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns all the notifications | Given the following Python 3 function, write the documentation
def get_all(self, request, notifications, mark_as_read=False):
return self.list(request, notifications) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_object(self, queryset=None):
""" get privacy settings of current user """
try:
obj = self.get_queryset()
except self.model.DoesNotExist:
raise Http404()
self.check_object_permissions(self.request, obj)
return obj | How would you implement a function in Python 3 that
gets object from queryset | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_link(cls, source, target, topology=None):
"""
Find link between source and target, (or vice versa, order is irrelevant).
:param source: ip or mac addresses
:param target: ip or mac addresses
:param topology: optional topology relation
:returns: Link object
... | Create a Python 3 function to
find a link between source and target. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Tries to find a link with get_link creates a new link if it doesn t exist. | Make a summary of the following Python 3 code
def get_or_create(cls, source, target, cost, topology=None):
try:
return cls.get_link(source, target, topology)
except LinkNotFound as e:
pass
# create link
link = Link(interface_a=e.interface_a,
in... | You are a Python code analyst, evaluating scripts for potential improvements. |
ensure link properties correspond to the specified ones
perform save operation only if necessary
| How would you explain what the following Python 3 function does
def ensure(self, status, cost):
changed = False
status_id = LINK_STATUS[status]
if self.status != status_id:
self.status = status_id
changed = True
if self.metric_value != cost:
self.metri... | You are a Python code analyst, evaluating scripts for potential improvements. |
def send(self, request, queryset):
"""
Send action available in change outward list
"""
send_outward_mails.delay(queryset)
# show message in the admin
messages.info(request, _('Message sent successfully'), fail_silently=True) | Write a Python 3 script to
send the message to the admin. | You are a Python code architect, reviewing and designing scalable and efficient code |
This is the HTTP POST method. | Can you generate a brief explanation for the following Python 3 code
def post(self, request, *args, **kwargs):
try:
self.get_object(**kwargs)
except Http404:
return Response({'detail': _('Not Found')}, status=404)
if not self.is_contactable():
return Response... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get(self, request, *args, **kwargs):
""" return profile of current user if authenticated otherwise 401 """
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(request.user, context=self.get_serializer_context()).data)
e... | Write a Python 3 function that can
return the profile of current user if authenticated otherwise 401 | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate password change operation and return result | Explain what the following Python 3 code does
def post(self, request, format=None):
serializer_class = self.get_serializer_class()
serializer = serializer_class(data=request.data, instance=request.user)
if serializer.is_valid():
serializer.save()
return Response({'detail... | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is used to synchronize the internal state of the internal state of the internal state of the external source with the internal state of the external source. | Can you generate the documentation for the following Python 3 function
def sync(self):
self.before_start()
self.retrieve_data()
self.parse()
# TRICK: disable new_nodes_allowed_for_layer validation
try:
Node._additional_validation.remove('new_nodes_allowed_for_layer')... | You are a Python code generator, capable of creating scripts from specifications. |
retrieve data from an HTTP URL | How would you explain what the following Python 3 function does
def retrieve_data(self):
# shortcuts for readability
url = self.config.get('url')
timeout = float(self.config.get('timeout', 10))
# perform HTTP request and store content
self.data = requests.get(url, verify=self.ver... | As a Python code analyst, you investigate and solve complex coding mysteries |
returns text content of an xml tag | Make a summary of the following Python 3 code
def get_text(item, tag, default=False):
try:
xmlnode = item.getElementsByTagName(tag)[0].firstChild
except IndexError as e:
if default is not False:
return default
else:
raise IndexError(e)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _convert_item(self, item):
"""
take a parsed item as input and returns a python dictionary
the keys will be saved into the Node model
either in their respective fields or in the hstore "data" field
:param item: object representing parsed item
"""
item = self.... | Can you implement a function in Python 3 that
converts a parsed item as input and returns a python dictionary containing the keys of the node model that can be used to store the item in the hstore. data field. | As a Python code analyst, you investigate and solve complex coding mysteries |
save data into DB | Here you have a function in Python 3, explain what it does
def save(self):
self.key_mapping()
# retrieve all items
items = self.parsed_data
# init empty lists
added_nodes = []
changed_nodes = []
unmodified_nodes = []
# retrieve a list of all the slugs of... | You are a Python code generator, capable of creating scripts from specifications. |
Returns only objects which are accessible to the current user. | How would you explain what the following Python 3 function does
def get_queryset(self):
return self.queryset.all().accessible_to(user=self.request.user) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Disconnects from the node. | Can you generate the documentation for the following Python 3 function
def disconnect():
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handler, sender=Node) | As a Python code composer, you craft elegant and concise scripts. |
def reconnect():
""" reconnect signals """
post_save.connect(node_created_handler, sender=Node)
node_status_changed.connect(node_status_changed_handler)
pre_delete.connect(node_deleted_handler, sender=Node) | Write a Python 3 script to
reconnect the node to the next update. | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate that the from_user and to_user are the same. | Given the following Python 3 function, write the documentation
def clean(self, *args, **kwargs):
if self.from_user and self.from_user_id == self.to_user_id:
raise ValidationError(_('A user cannot send a notification to herself/himself')) | As a python code expert, you are capable of creating scripts from specifications. |
custom save method to send email and push notifications through other mediums | How would you explain what the following Python 3 function does
def save(self, *args, **kwargs):
created = self.pk is None
# save notification to database only if user settings allow it
if self.check_user_settings(medium='web'):
super(Notification, self).save(*args, **kwargs)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def send_email(self):
""" send email notification according to user settings """
# send only if user notification setting is set to true
if self.check_user_settings():
send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email])
return Tr... | Write a Python 3 script for
sending email notification according to user settings | As a python code expert, you are capable of creating scripts from specifications. |
def check_user_settings(self, medium='email'):
"""
Ensure user is ok with receiving this notification through the specified medium.
Available mediums are 'web' and 'email', while 'mobile' notifications will
hopefully be implemented in the future.
"""
# custom notification... | Can you create a Python 3 function that
checks if the user is ok with receiving this notification through the specified medium. | As a Python code analyst, you investigate and solve complex coding mysteries |
def email_message(self):
""" compose complete email message text """
url = settings.SITE_URL
hello_text = __("Hi %s," % self.to_user.get_full_name())
action_text = __("\n\nMore details here: %s") % url
explain_text = __(
"This is an automatic notification sent from fr... | How would you implement a function in Python 3 that
composes complete email message text | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a new email confirmation key and return it. | Can you tell what is the following Python 3 function doing
def generate_key(self, email):
salt = sha1(str(random())).hexdigest()[:5]
return sha1(salt + email).hexdigest() | As a python code expert, you are capable of creating scripts from specifications. |
def create_emailconfirmation(self, email_address):
"Create an email confirmation obj from the given email address obj"
confirmation_key = self.generate_key(email_address.email)
confirmation = self.create(
email_address=email_address,
created_at=now(),
key=conf... | Write a Python 3 script for
creating an email confirmation obj from the given email address obj | As a Python code composer, you craft elegant and concise scripts. |
collect metrics about user logins | How would you explain what the following Python 3 function does
def user_loggedin(sender, **kwargs):
values = {
'value': 1,
'path': kwargs['request'].path,
'user_id': str(kwargs['user'].pk),
'username': kwargs['user'].username,
}
write('user_logins', values=values) | As a Python code analyst, you investigate and solve complex coding mysteries |
def user_deleted(sender, **kwargs):
""" collect metrics about new users signing up """
if kwargs.get('created'):
write('user_variations', {'variation': 1}, tags={'action': 'created'})
write('user_count', {'total': User.objects.count()}) | Implement a Python 3 function for
collecting metrics about new users signing up | As a Python code composer, you craft elegant and concise scripts. |
def _node_rating_count(self):
"""
Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count
"""
try:
return self.noderatingcount
except ObjectDoesNotExist:
node_rating_count = NodeRatingCount(node=self)
... | Implement a Python 3 function for
returning node_rating_count record or create it usage | As a Python code composer, you craft elegant and concise scripts. |
Return node_participation_settings record if it does not exist | Explain what the following Python 3 code does
def _node_participation_settings(self):
try:
return self.node_participation_settings
except ObjectDoesNotExist:
node_participation_settings = NodeParticipationSettings(node=self)
node_participation_settings.save()
return node_particip... | As a python code expert, you are capable of creating scripts from specifications. |
def _action_allowed(self, action):
"""
participation actions can be disabled on layer level, or disabled on a per node basis
"""
if getattr(self.layer.participation_settings, '{0}_allowed'.format(action)) is False:
return False
else:
return getattr(self.participation_settings, '{0}_a... | How would you code a function in Python 3 to
check if participation actions can be performed on the node level or per node basis. | As a Python code composer, you craft elegant and concise scripts. |
create node rating count and settings | Can you generate a brief explanation for the following Python 3 code
def create_node_rating_counts_settings(sender, **kwargs):
created = kwargs['created']
node = kwargs['instance']
if created:
# create node_rating_count and settings
# task will be executed in background unless settings.CELER... | You are a Python code generator, capable of creating scripts from specifications. |
def create_layer_rating_settings(sender, **kwargs):
""" create layer rating settings """
created = kwargs['created']
layer = kwargs['instance']
if created:
# create layer participation settings
# task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True
# if... | Write a Python 3 script for
creating layer rating settings | You are a Python code architect, reviewing and designing scalable and efficient code |
Saves the instance to the database. | Can you generate the documentation for the following Python 3 function
def save(self, *args, **kwargs):
created = self.pk is None
sync_emailaddress = kwargs.pop('sync_emailaddress', True)
# ensure usable password
if created and self.has_usable_password() is False:
self.set_pa... | As a Python code composer, you craft elegant and concise scripts. |
def needs_confirmation(self):
"""
set is_active to False if needs email confirmation
"""
if EMAIL_CONFIRMATION:
self.is_active = False
self.save()
return True
else:
return False | Can you create a Python 3 function that
returns True if the user needs email confirmation | As a Python code composer, you craft elegant and concise scripts. |
def change_password(self, new_password):
"""
Changes password and sends a signal
"""
self.set_password(new_password)
self.save()
password_changed.send(sender=self.__class__, user=self) | How would you code a function in Python 3 to
change password and sends a signal password_changed signal | You are a Python code analyst, evaluating scripts for potential improvements. |
Custom initial method that creates a node and sets the queryset to only comments of current node | Make a summary of the following Python 3 code
def initial(self, request, *args, **kwargs):
super(NodeRelationViewMixin, self).initial(request, *args, **kwargs)
self.node = get_object_or_404(Node, **{'slug': self.kwargs['slug']})
self.queryset = self.model.objects.filter(node_id=self.node.id) | You are a Python code analyst, evaluating scripts for potential improvements. |
This decorator adds the User Notification Settings fields dynamically to the User Notification Settings models. | Can you tell what is the following Python 3 function doing
def add_notifications(myclass):
for key, value in TEXTS.items():
# custom notifications cannot be disabled
if 'custom' in [key, value]:
continue
field_type = USER_SETTING[key]['type']
if field_type == 'boolean':... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.