Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|># Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New sync attribute.
SyncAttribs.extend('CL_EVENT_HANDLE', 0x309C, c_int, None)
# New values for SyncTypes and SyncConditions.
# TODO: Replace the namedtuple instances with extensible enumerations.
SYNC_CL_EVENT = 0x30FE
SYNC_CL_EVENT_COMPLETE = 0x30FF
# New Sync subclass.
<|code_end|>
, generate the next line using the imports in this file:
from ctypes import c_int
from .khr_sync import FenceSync, SyncAttribs
and context (functions, classes, or occasionally code) from other files:
# Path: src/pegl/ext/khr_sync.py
# class FenceSync(Sync):
# '''Represents the "fence" type of sync object.
#
# Class attributes:
# extension -- The name string of the fence sync extension.
# sync_type -- SyncTypes.FENCE.
#
# Instance attributes:
# synchandle, display, status, signaled, sync_type -- As per the
# superclass, Sync.
# attribs -- Always an empty AttribList.
# sync_condition -- The condition under which this sync object
# will be automatically set to signaled. A value from the
# SyncConditions tuple.
#
# '''
# extension = 'EGL_KHR_fence_sync'
# sync_type = SyncTypes.FENCE
#
# def __init__(self, display):
# '''Create the fence sync object.
#
# Keyword arguments:
# display -- As the instance attribute.
#
# '''
# # Fence sync objects have empty attribute lists.
# super().__init__(display, {})
#
# @property
# def sync_condition(self):
# '''Get the condition under which this sync object gets signaled.'''
# return self._attr(SyncAttribs.SYNC_CONDITION)
#
# class SyncAttribs(Attribs):
# '''The set of attributes relevant to sync objects.
#
# Class attributes:
# details -- As per the superclass, Attribs.
# Additionally, symbolic constants for all the known attributes
# are available as class attributes. Their names are the same as
# in the extension specification, except without the EGL_ prefix
# and _KHR suffix.
#
# '''
# # Only for querying; this is not set at creation, but can be toggled later.
# SYNC_STATUS = 0x30F1
# # Only for querying; at creation, this is passed as its own parameter.
# SYNC_TYPE = 0x30F7
# # As above, plus only valid for fence sync objects.
# SYNC_CONDITION = 0x30F8
#
# details = {SYNC_TYPE: Details('The type of this sync object', c_int, 0),
# SYNC_STATUS: Details('Which state this sync object is in',
# c_int, SyncStatus.UNSIGNALED),
# SYNC_CONDITION: Details('Under what condition this sync object '
# 'will be automatically signaled', c_int,
# SyncConditions.PRIOR_COMMANDS_COMPLETE)}
. Output only the next line. | class OpenCLSync(FenceSync): |
Here is a snippet: <|code_start|>
Note that, because it puts an OpenCL event handle into an attribute list
where (especially on 64-bit systems) it is not guaranteed to fit, this
extension is deprecated and replaced by khr_clevent2.
http://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_cl_event.txt
'''
# Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New sync attribute.
<|code_end|>
. Write the next line using the current file imports:
from ctypes import c_int
from .khr_sync import FenceSync, SyncAttribs
and context from other files:
# Path: src/pegl/ext/khr_sync.py
# class FenceSync(Sync):
# '''Represents the "fence" type of sync object.
#
# Class attributes:
# extension -- The name string of the fence sync extension.
# sync_type -- SyncTypes.FENCE.
#
# Instance attributes:
# synchandle, display, status, signaled, sync_type -- As per the
# superclass, Sync.
# attribs -- Always an empty AttribList.
# sync_condition -- The condition under which this sync object
# will be automatically set to signaled. A value from the
# SyncConditions tuple.
#
# '''
# extension = 'EGL_KHR_fence_sync'
# sync_type = SyncTypes.FENCE
#
# def __init__(self, display):
# '''Create the fence sync object.
#
# Keyword arguments:
# display -- As the instance attribute.
#
# '''
# # Fence sync objects have empty attribute lists.
# super().__init__(display, {})
#
# @property
# def sync_condition(self):
# '''Get the condition under which this sync object gets signaled.'''
# return self._attr(SyncAttribs.SYNC_CONDITION)
#
# class SyncAttribs(Attribs):
# '''The set of attributes relevant to sync objects.
#
# Class attributes:
# details -- As per the superclass, Attribs.
# Additionally, symbolic constants for all the known attributes
# are available as class attributes. Their names are the same as
# in the extension specification, except without the EGL_ prefix
# and _KHR suffix.
#
# '''
# # Only for querying; this is not set at creation, but can be toggled later.
# SYNC_STATUS = 0x30F1
# # Only for querying; at creation, this is passed as its own parameter.
# SYNC_TYPE = 0x30F7
# # As above, plus only valid for fence sync objects.
# SYNC_CONDITION = 0x30F8
#
# details = {SYNC_TYPE: Details('The type of this sync object', c_int, 0),
# SYNC_STATUS: Details('Which state this sync object is in',
# c_int, SyncStatus.UNSIGNALED),
# SYNC_CONDITION: Details('Under what condition this sync object '
# 'will be automatically signaled', c_int,
# SyncConditions.PRIOR_COMMANDS_COMPLETE)}
, which may include functions, classes, or code. Output only the next line. | SyncAttribs.extend('CL_EVENT_HANDLE', 0x309C, c_int, None) |
Next line prediction: <|code_start|>http://www.khronos.org/registry/egl/extensions/EXT/EGL_EXT_create_context_robustness.txt
'''
# Copyright © 2012-13 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New context attributes.
ResetStrategies = namedtuple('ResetStrategies_tuple',
('NO_RESET_NOTIFICATION',
'LOSE_CONTEXT_ON_RESET'),
)(0x31BE, 0x31BF)
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from ..attribs.context import ContextAttribs)
and context including class names, function names, or small code snippets from other files:
# Path: src/pegl/attribs/context.py
# class ContextAttribs(Attribs):
# '''The set of EGL attributes relevant to context objects.'''
# CONFIG_ID = ConfigAttribs.CONFIG_ID
# RENDER_BUFFER = 0x3086
# CONTEXT_CLIENT_TYPE, CONTEXT_CLIENT_VERSION = 0x3097, 0x3098
# details = {CONFIG_ID: Details('The unique identifier of the configuration '
# 'used to create this context', c_int, 0),
# RENDER_BUFFER: Details('Which buffer type this context renders '
# 'into', RenderBufferTypes,
# RenderBufferTypes.BACK),
# CONTEXT_CLIENT_TYPE: Details('The client API for which this '
# 'context was created', ContextAPIs,
# NONE),
# CONTEXT_CLIENT_VERSION: Details('The client API version for '
# 'which this context was '
# 'created', c_int, 1)}
. Output only the next line. | ContextAttribs.extend('OPENGL_ROBUST_ACCESS', 0x30BF, bool, False) |
Next line prediction: <|code_start|>
@csrf_exempt
def store(request):
"""
Main API method storing pushed data.
TODO: Needs a lot of work, security, validation etc.
"""
if request.method == 'POST':
data = request.raw_post_data
data = json.loads(base64.b64decode(data).decode('zlib'))
# Get the Metric for provided api_key, otherwise fail with Forbidden.
try:
<|code_end|>
. Use current file imports:
(import base64
import json
from datetime import datetime
from django.http import HttpResponseForbidden, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from holodeck.models import Metric, Sample)
and context including class names, function names, or small code snippets from other files:
# Path: holodeck/models.py
# class Metric(models.Model):
# name = models.CharField(max_length=255)
# description = models.TextField(
# blank=True,
# null=True,
# )
# dashboard = models.ForeignKey('holodeck.Dashboard')
# widget_type = models.CharField(
# max_length=64,
# choices=get_widget_type_choices()
# )
# api_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# position = models.IntegerField(
# blank=True,
# null=True,
# )
#
# def __unicode__(self):
# return self.name
#
# @property
# def widget(self):
# return load_class_by_string(self.widget_type)()
#
# def render(self, context, minimal=False):
# return self.widget.render(self, context, minimal)
#
# def export(self, workbook):
# """
# Given a xlwt Excel workbook creates a sheet and populates it
# with samples for this metric.
# """
# samples = {}
# worksheet = workbook.add_sheet(self.name[:31])
#
# samples = self.sample_set.all()
#
# date_format = 'D-MMM-YY H:MM:SS'
# date_style = xlwt.easyxf(num_format_str=date_format)
#
# # Write distinct reverse sorted timestamps as first column.
# timestamps = list(set([sample.timestamp for sample in samples]))
# timestamps.sort(reverse=True)
# for i, timestamp in enumerate(timestamps):
# worksheet.write(i + 1, 0, timestamp, date_style)
#
# # Set timestamp column width.
# # Each character's approximated width is 256
# worksheet.col(0).width = (1 + len(date_format)) * 256
#
# # Write distinct sorted string values as first row.
# string_values = list(set([sample.string_value for sample in samples]))
# string_values.sort()
# for i, string_value in enumerate(string_values):
# worksheet.write(0, i + 1, string_value)
# worksheet.col(i + 1).width = (1 + len(string_value)) * 256
#
# # Write sample values as they correspond to timestamp and string_value.
# for sample in samples:
# row = timestamps.index(sample.timestamp) + 1
# col = string_values.index(sample.string_value) + 1
#
# try:
# worksheet.write(row, col, sample.integer_value)
# if len(str(sample.integer_value)) > len(sample.string_value):
# worksheet.col(col).width = (
# 1 + len(str(sample.integer_value))
# ) * 256
# except Exception, e:
# if 'overwrite' in e.message:
# # Ignore duplicate samples.
# # XXX: Enforce on import.
# pass
# else:
# raise e
#
# def save(self, *args, **kwargs):
# if not self.api_key:
# self.api_key = generate_key()
# if not self.share_key:
# self.share_key = generate_key()
# super(Metric, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['position', '-id']
#
# class Sample(models.Model):
# metric = models.ForeignKey('holodeck.Metric')
# integer_value = models.IntegerField(
# default=0
# )
# string_value = models.CharField(max_length=64)
# timestamp = models.DateTimeField()
#
# class Meta:
# unique_together = (
# ("metric", "string_value", "timestamp"),
# )
. Output only the next line. | metric = Metric.objects.get(api_key=data['api_key']) |
Given the code snippet: <|code_start|>
@csrf_exempt
def store(request):
"""
Main API method storing pushed data.
TODO: Needs a lot of work, security, validation etc.
"""
if request.method == 'POST':
data = request.raw_post_data
data = json.loads(base64.b64decode(data).decode('zlib'))
# Get the Metric for provided api_key, otherwise fail with Forbidden.
try:
metric = Metric.objects.get(api_key=data['api_key'])
except Metric.DoesNotExist:
return HttpResponseForbidden()
timestamp = datetime.strptime(data['timestamp'], '%Y-%m-%d %H:%M:%S')
for sample in data['samples']:
# Samples overide on metric, string and timestamp values.
<|code_end|>
, generate the next line using the imports in this file:
import base64
import json
from datetime import datetime
from django.http import HttpResponseForbidden, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from holodeck.models import Metric, Sample
and context (functions, classes, or occasionally code) from other files:
# Path: holodeck/models.py
# class Metric(models.Model):
# name = models.CharField(max_length=255)
# description = models.TextField(
# blank=True,
# null=True,
# )
# dashboard = models.ForeignKey('holodeck.Dashboard')
# widget_type = models.CharField(
# max_length=64,
# choices=get_widget_type_choices()
# )
# api_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# position = models.IntegerField(
# blank=True,
# null=True,
# )
#
# def __unicode__(self):
# return self.name
#
# @property
# def widget(self):
# return load_class_by_string(self.widget_type)()
#
# def render(self, context, minimal=False):
# return self.widget.render(self, context, minimal)
#
# def export(self, workbook):
# """
# Given a xlwt Excel workbook creates a sheet and populates it
# with samples for this metric.
# """
# samples = {}
# worksheet = workbook.add_sheet(self.name[:31])
#
# samples = self.sample_set.all()
#
# date_format = 'D-MMM-YY H:MM:SS'
# date_style = xlwt.easyxf(num_format_str=date_format)
#
# # Write distinct reverse sorted timestamps as first column.
# timestamps = list(set([sample.timestamp for sample in samples]))
# timestamps.sort(reverse=True)
# for i, timestamp in enumerate(timestamps):
# worksheet.write(i + 1, 0, timestamp, date_style)
#
# # Set timestamp column width.
# # Each character's approximated width is 256
# worksheet.col(0).width = (1 + len(date_format)) * 256
#
# # Write distinct sorted string values as first row.
# string_values = list(set([sample.string_value for sample in samples]))
# string_values.sort()
# for i, string_value in enumerate(string_values):
# worksheet.write(0, i + 1, string_value)
# worksheet.col(i + 1).width = (1 + len(string_value)) * 256
#
# # Write sample values as they correspond to timestamp and string_value.
# for sample in samples:
# row = timestamps.index(sample.timestamp) + 1
# col = string_values.index(sample.string_value) + 1
#
# try:
# worksheet.write(row, col, sample.integer_value)
# if len(str(sample.integer_value)) > len(sample.string_value):
# worksheet.col(col).width = (
# 1 + len(str(sample.integer_value))
# ) * 256
# except Exception, e:
# if 'overwrite' in e.message:
# # Ignore duplicate samples.
# # XXX: Enforce on import.
# pass
# else:
# raise e
#
# def save(self, *args, **kwargs):
# if not self.api_key:
# self.api_key = generate_key()
# if not self.share_key:
# self.share_key = generate_key()
# super(Metric, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['position', '-id']
#
# class Sample(models.Model):
# metric = models.ForeignKey('holodeck.Metric')
# integer_value = models.IntegerField(
# default=0
# )
# string_value = models.CharField(max_length=64)
# timestamp = models.DateTimeField()
#
# class Meta:
# unique_together = (
# ("metric", "string_value", "timestamp"),
# )
. Output only the next line. | sample_obj, created = Sample.objects.get_or_create( |
Using the snippet: <|code_start|>
register = template.Library()
@register.inclusion_tag('holodeck/inclusion_tags/dashboard_dropdown.html', takes_context=True)
def dashboard_dropdown(context):
context.update({
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy
from django import template
from holodeck.models import Dashboard
from holodeck.widgets import LineChart, SampleDeviation
and context (class names, function names, or code) available:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
#
# Path: holodeck/widgets.py
# class LineChart(Widget):
# name = 'Line Chart'
# template_name = 'holodeck/widgets/line_chart.html'
# width = 8
#
# def get_context(self, metric):
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# groups = self.get_groups(metric)
#
# if not groups:
# context['no_samples'] = True
# return context
#
# grouped_samples = []
# group_maxes = []
# sample_count = 20
# for group in groups:
# samples = [(int(time.mktime(sample.timestamp.timetuple()) * 1000),
# sample.integer_value)
# for sample in metric.sample_set.filter(
# string_value=group
# ).order_by('-timestamp')[:sample_count]]
# grouped_samples.append((group, samples))
# group_maxes.append(max([sample[1] for sample in samples]))
# samples = json.dumps([{'label': group[0], 'data': group[1]}
# for group in grouped_samples])
#
# context.update({
# 'samples': samples,
# 'y_max': max(group_maxes) * 1.025,
# })
# return context
#
# class SampleDeviation(Widget):
# name = 'Sample Deviation'
# template_name = 'holodeck/widgets/sample_deviation.html'
# width = 4
#
# def calc_deviation(self, primary, secondary):
# if secondary == 0:
# return primary * 100
# return int((primary * 100.0) / secondary) - 100
#
# def gen_deviation(self, primary, secondary):
# dev = self.calc_deviation(primary, secondary)
# color = 'green'
# if dev >= -10 and dev <= 10:
# color = 'orange'
# if dev < -10:
# color = 'red'
# return {
# 'percentage': '%s%s' % ('+' if dev > 0 else '', dev),
# 'color': color
# }
#
# def get_context(self, metric):
# from django.db.models import Avg, Max
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# try:
# current = metric.sample_set.all().order_by(
# '-timestamp')[0].integer_value
# except IndexError:
# context['no_samples'] = True
# return context
#
# try:
# previous = metric.sample_set.all().order_by(
# '-timestamp')[1].integer_value
# except IndexError:
# previous = 0
#
# average = int(metric.sample_set.all().aggregate(
# Avg('integer_value'))['integer_value__avg'])
# peak = int(metric.sample_set.all().aggregate(
# Max('integer_value'))['integer_value__max'])
#
# context.update({
# 'current': current,
# 'previous': self.gen_deviation(current, previous),
# 'average': self.gen_deviation(current, average),
# 'peak': self.gen_deviation(current, peak),
# })
#
# return context
. Output only the next line. | 'dashboard_list': Dashboard.objects.all().order_by('name') |
Predict the next line for this snippet: <|code_start|> 'dashboard_list': Dashboard.objects.all().order_by('name')
})
return context
@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
context = copy(context)
return {'result': metric.render(context, minimal)}
@register.inclusion_tag('holodeck/inclusion_tags/dashboard_list_summary.html')
def dashboard_list_summary(dashboard):
context = {
'dashboard': dashboard,
}
metrics = dashboard.metric_set.filter(
widget_type='holodeck.widgets.LineChart'
)
sampled_metric = None
for metric in metrics:
if metric.sample_set.all():
sampled_metric = metric
break
if not sampled_metric:
return context
<|code_end|>
with the help of current file imports:
from copy import copy
from django import template
from holodeck.models import Dashboard
from holodeck.widgets import LineChart, SampleDeviation
and context from other files:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
#
# Path: holodeck/widgets.py
# class LineChart(Widget):
# name = 'Line Chart'
# template_name = 'holodeck/widgets/line_chart.html'
# width = 8
#
# def get_context(self, metric):
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# groups = self.get_groups(metric)
#
# if not groups:
# context['no_samples'] = True
# return context
#
# grouped_samples = []
# group_maxes = []
# sample_count = 20
# for group in groups:
# samples = [(int(time.mktime(sample.timestamp.timetuple()) * 1000),
# sample.integer_value)
# for sample in metric.sample_set.filter(
# string_value=group
# ).order_by('-timestamp')[:sample_count]]
# grouped_samples.append((group, samples))
# group_maxes.append(max([sample[1] for sample in samples]))
# samples = json.dumps([{'label': group[0], 'data': group[1]}
# for group in grouped_samples])
#
# context.update({
# 'samples': samples,
# 'y_max': max(group_maxes) * 1.025,
# })
# return context
#
# class SampleDeviation(Widget):
# name = 'Sample Deviation'
# template_name = 'holodeck/widgets/sample_deviation.html'
# width = 4
#
# def calc_deviation(self, primary, secondary):
# if secondary == 0:
# return primary * 100
# return int((primary * 100.0) / secondary) - 100
#
# def gen_deviation(self, primary, secondary):
# dev = self.calc_deviation(primary, secondary)
# color = 'green'
# if dev >= -10 and dev <= 10:
# color = 'orange'
# if dev < -10:
# color = 'red'
# return {
# 'percentage': '%s%s' % ('+' if dev > 0 else '', dev),
# 'color': color
# }
#
# def get_context(self, metric):
# from django.db.models import Avg, Max
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# try:
# current = metric.sample_set.all().order_by(
# '-timestamp')[0].integer_value
# except IndexError:
# context['no_samples'] = True
# return context
#
# try:
# previous = metric.sample_set.all().order_by(
# '-timestamp')[1].integer_value
# except IndexError:
# previous = 0
#
# average = int(metric.sample_set.all().aggregate(
# Avg('integer_value'))['integer_value__avg'])
# peak = int(metric.sample_set.all().aggregate(
# Max('integer_value'))['integer_value__max'])
#
# context.update({
# 'current': current,
# 'previous': self.gen_deviation(current, previous),
# 'average': self.gen_deviation(current, average),
# 'peak': self.gen_deviation(current, peak),
# })
#
# return context
, which may contain function names, class names, or code. Output only the next line. | chart_context = LineChart().get_context(sampled_metric) |
Predict the next line for this snippet: <|code_start|> return context
@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
context = copy(context)
return {'result': metric.render(context, minimal)}
@register.inclusion_tag('holodeck/inclusion_tags/dashboard_list_summary.html')
def dashboard_list_summary(dashboard):
context = {
'dashboard': dashboard,
}
metrics = dashboard.metric_set.filter(
widget_type='holodeck.widgets.LineChart'
)
sampled_metric = None
for metric in metrics:
if metric.sample_set.all():
sampled_metric = metric
break
if not sampled_metric:
return context
chart_context = LineChart().get_context(sampled_metric)
# TODO: Calculate this here, unused context calculated.
<|code_end|>
with the help of current file imports:
from copy import copy
from django import template
from holodeck.models import Dashboard
from holodeck.widgets import LineChart, SampleDeviation
and context from other files:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
#
# Path: holodeck/widgets.py
# class LineChart(Widget):
# name = 'Line Chart'
# template_name = 'holodeck/widgets/line_chart.html'
# width = 8
#
# def get_context(self, metric):
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# groups = self.get_groups(metric)
#
# if not groups:
# context['no_samples'] = True
# return context
#
# grouped_samples = []
# group_maxes = []
# sample_count = 20
# for group in groups:
# samples = [(int(time.mktime(sample.timestamp.timetuple()) * 1000),
# sample.integer_value)
# for sample in metric.sample_set.filter(
# string_value=group
# ).order_by('-timestamp')[:sample_count]]
# grouped_samples.append((group, samples))
# group_maxes.append(max([sample[1] for sample in samples]))
# samples = json.dumps([{'label': group[0], 'data': group[1]}
# for group in grouped_samples])
#
# context.update({
# 'samples': samples,
# 'y_max': max(group_maxes) * 1.025,
# })
# return context
#
# class SampleDeviation(Widget):
# name = 'Sample Deviation'
# template_name = 'holodeck/widgets/sample_deviation.html'
# width = 4
#
# def calc_deviation(self, primary, secondary):
# if secondary == 0:
# return primary * 100
# return int((primary * 100.0) / secondary) - 100
#
# def gen_deviation(self, primary, secondary):
# dev = self.calc_deviation(primary, secondary)
# color = 'green'
# if dev >= -10 and dev <= 10:
# color = 'orange'
# if dev < -10:
# color = 'red'
# return {
# 'percentage': '%s%s' % ('+' if dev > 0 else '', dev),
# 'color': color
# }
#
# def get_context(self, metric):
# from django.db.models import Avg, Max
# context = {
# 'metric': metric,
# 'width': self.width,
# }
#
# try:
# current = metric.sample_set.all().order_by(
# '-timestamp')[0].integer_value
# except IndexError:
# context['no_samples'] = True
# return context
#
# try:
# previous = metric.sample_set.all().order_by(
# '-timestamp')[1].integer_value
# except IndexError:
# previous = 0
#
# average = int(metric.sample_set.all().aggregate(
# Avg('integer_value'))['integer_value__avg'])
# peak = int(metric.sample_set.all().aggregate(
# Max('integer_value'))['integer_value__max'])
#
# context.update({
# 'current': current,
# 'previous': self.gen_deviation(current, previous),
# 'average': self.gen_deviation(current, average),
# 'peak': self.gen_deviation(current, peak),
# })
#
# return context
, which may contain function names, class names, or code. Output only the next line. | deviation_context = SampleDeviation().get_context(sampled_metric) |
Next line prediction: <|code_start|>
class Dashboard(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, null=True)
share_key = models.CharField(
max_length=32,
unique=True,
blank=True,
null=True
)
def save(self, *args, **kwargs):
if not self.share_key:
self.share_key = generate_key()
super(Dashboard, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Metric(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(
blank=True,
null=True,
)
dashboard = models.ForeignKey('holodeck.Dashboard')
widget_type = models.CharField(
max_length=64,
<|code_end|>
. Use current file imports:
(import uuid
import xlwt
from django.contrib.auth.models import User
from django.db import models
from holodeck.utils import get_widget_type_choices, load_class_by_string)
and context including class names, function names, or small code snippets from other files:
# Path: holodeck/utils.py
# def get_widget_type_choices():
# """
# Generates Django model field choices based on widgets
# in holodeck.widgets.
# """
# choices = []
# for name, member in inspect.getmembers(widgets, inspect.isclass):
# if member != widgets.Widget:
# choices.append((
# "%s.%s" % (member.__module__, member.__name__),
# member.name
# ))
# return choices
#
# def load_class_by_string(class_path):
# """
# Returns a class when given its full name in
# Python dot notation, including modules.
# """
# parts = class_path.split('.')
# module_name = '.'.join(parts[:-1])
# class_name = parts[-1]
# __import__(module_name)
# mod = sys.modules[module_name]
# return getattr(mod, class_name)
. Output only the next line. | choices=get_widget_type_choices() |
Given the following code snippet before the placeholder: <|code_start|> blank=True,
null=True,
)
dashboard = models.ForeignKey('holodeck.Dashboard')
widget_type = models.CharField(
max_length=64,
choices=get_widget_type_choices()
)
api_key = models.CharField(
max_length=32,
unique=True,
blank=True,
null=True
)
share_key = models.CharField(
max_length=32,
unique=True,
blank=True,
null=True
)
position = models.IntegerField(
blank=True,
null=True,
)
def __unicode__(self):
return self.name
@property
def widget(self):
<|code_end|>
, predict the next line using imports from the current file:
import uuid
import xlwt
from django.contrib.auth.models import User
from django.db import models
from holodeck.utils import get_widget_type_choices, load_class_by_string
and context including class names, function names, and sometimes code from other files:
# Path: holodeck/utils.py
# def get_widget_type_choices():
# """
# Generates Django model field choices based on widgets
# in holodeck.widgets.
# """
# choices = []
# for name, member in inspect.getmembers(widgets, inspect.isclass):
# if member != widgets.Widget:
# choices.append((
# "%s.%s" % (member.__module__, member.__name__),
# member.name
# ))
# return choices
#
# def load_class_by_string(class_path):
# """
# Returns a class when given its full name in
# Python dot notation, including modules.
# """
# parts = class_path.split('.')
# module_name = '.'.join(parts[:-1])
# class_name = parts[-1]
# __import__(module_name)
# mod = sys.modules[module_name]
# return getattr(mod, class_name)
. Output only the next line. | return load_class_by_string(self.widget_type)() |
Based on the snippet: <|code_start|>
admin.autodiscover()
urlpatterns = patterns('',
# Accounts.
url(r'^login/$', views.login, name='holodeck-login'),
url(r'^logout/$', views.logout, name='holodeck-logout'),
# Dashboards.
url(r'^dashboards/new/$', views.new_dashboard, name='holodeck-new-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)$', views.view_dashboard, name='holodeck-view-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/manage/$', views.manage_dashboard, name='holodeck-manage-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/sort/$', views.sort_dashboard, name='holodeck-sort-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/export/$', views.export_dashboard, name='holodeck-export-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/export/(?P<share_key>[\w-]+)/$', views.export_shared_dashboard, name='holodeck-export-shared-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/remove/$', views.remove_dashboard, name='holodeck-remove-dashboard'),
url(r'^dashboards/(?P<dashboard_id>\d+)/(?P<share_key>[\w-]+)/$', views.share_dashboard, name='holodeck-share-dashboard'),
# Metrics.
url(r'^metrics/(?P<dashboard_id>\d+)/new/$', views.new_metric, name='holodeck-new-metric'),
url(r'^metrics/(?P<metric_id>\d+)/edit/$', views.manage_metric, name='holodeck-manage-metric'),
url(r'^metrics/(?P<metric_id>\d+)/change/(?P<type_id>\d+)/$', views.type_change_metric, name='holodeck-type-change-metric'),
url(r'^metrics/(?P<metric_id>\d+)/(?P<share_key>[\w-]+)/share.png$', views.share_metric, name='holodeck-share-metric'),
url(r'^metrics/(?P<metric_id>\d+)/remove/$', views.remove_metric, name='holodeck-remove-metric'),
url(r'^metrics/(?P<metric_id>\d+)/purge-samples/$', views.purge_metric_samples, name='holodeck-purge-metric-samples'),
# API.
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from holodeck import api, views
and context (classes, functions, sometimes code) from other files:
# Path: holodeck/api.py
# def store(request):
#
# Path: holodeck/views.py
# def holodeck(request):
# def login(request):
# def logout(request):
# def manage_dashboard(request, dashboard_id):
# def new_dashboard(request):
# def _export_dashboard(request, dashboard_id):
# def _view_dashboard(request, dashboard_id, template):
# def export_dashboard(request, dashboard_id):
# def export_shared_dashboard(request, dashboard_id, share_key):
# def remove_dashboard(request, dashboard_id):
# def share_dashboard(request, dashboard_id, share_key):
# def sort_dashboard(request, dashboard_id):
# def view_dashboard(request, dashboard_id):
# def new_metric(request, dashboard_id):
# def manage_metric(request, metric_id):
# def type_change_metric(request, metric_id, type_id):
# def share_metric(request, metric_id, share_key):
# def remove_metric(request, metric_id):
# def purge_metric_samples(request, metric_id):
. Output only the next line. | url(r'^api/store/$', api.store, name='holodeck-api-store'), |
Given snippet: <|code_start|>
def load_class_by_string(class_path):
"""
Returns a class when given its full name in
Python dot notation, including modules.
"""
parts = class_path.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
__import__(module_name)
mod = sys.modules[module_name]
return getattr(mod, class_name)
def get_widget_type_choices():
"""
Generates Django model field choices based on widgets
in holodeck.widgets.
"""
choices = []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import inspect
import sys
from holodeck import widgets
and context:
# Path: holodeck/widgets.py
# class Widget(object):
# class Gage(Widget):
# class Map(Widget):
# class LineChart(Widget):
# class PieChart(Widget):
# class SampleDeviation(Widget):
# def get_context(self, metric):
# def get_groups(self, metric):
# def render(self, metric, context, minimal):
# def get_context(self, metric):
# def get_context(self, metric):
# def get_context(self, metric):
# def get_context(self, metric):
# def calc_deviation(self, primary, secondary):
# def gen_deviation(self, primary, secondary):
# def get_context(self, metric):
which might include code, classes, or functions. Output only the next line. | for name, member in inspect.getmembers(widgets, inspect.isclass): |
Given the code snippet: <|code_start|>
class NewDashboardForm(forms.ModelForm):
name = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={
'placeholder': _('e.g. My Dashboard Name')
})
)
class Meta:
fields = ('name', 'owner')
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from django.utils.translation import ugettext_lazy as _
from holodeck.models import Dashboard, Metric
and context (functions, classes, or occasionally code) from other files:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
#
# class Metric(models.Model):
# name = models.CharField(max_length=255)
# description = models.TextField(
# blank=True,
# null=True,
# )
# dashboard = models.ForeignKey('holodeck.Dashboard')
# widget_type = models.CharField(
# max_length=64,
# choices=get_widget_type_choices()
# )
# api_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# position = models.IntegerField(
# blank=True,
# null=True,
# )
#
# def __unicode__(self):
# return self.name
#
# @property
# def widget(self):
# return load_class_by_string(self.widget_type)()
#
# def render(self, context, minimal=False):
# return self.widget.render(self, context, minimal)
#
# def export(self, workbook):
# """
# Given a xlwt Excel workbook creates a sheet and populates it
# with samples for this metric.
# """
# samples = {}
# worksheet = workbook.add_sheet(self.name[:31])
#
# samples = self.sample_set.all()
#
# date_format = 'D-MMM-YY H:MM:SS'
# date_style = xlwt.easyxf(num_format_str=date_format)
#
# # Write distinct reverse sorted timestamps as first column.
# timestamps = list(set([sample.timestamp for sample in samples]))
# timestamps.sort(reverse=True)
# for i, timestamp in enumerate(timestamps):
# worksheet.write(i + 1, 0, timestamp, date_style)
#
# # Set timestamp column width.
# # Each character's approximated width is 256
# worksheet.col(0).width = (1 + len(date_format)) * 256
#
# # Write distinct sorted string values as first row.
# string_values = list(set([sample.string_value for sample in samples]))
# string_values.sort()
# for i, string_value in enumerate(string_values):
# worksheet.write(0, i + 1, string_value)
# worksheet.col(i + 1).width = (1 + len(string_value)) * 256
#
# # Write sample values as they correspond to timestamp and string_value.
# for sample in samples:
# row = timestamps.index(sample.timestamp) + 1
# col = string_values.index(sample.string_value) + 1
#
# try:
# worksheet.write(row, col, sample.integer_value)
# if len(str(sample.integer_value)) > len(sample.string_value):
# worksheet.col(col).width = (
# 1 + len(str(sample.integer_value))
# ) * 256
# except Exception, e:
# if 'overwrite' in e.message:
# # Ignore duplicate samples.
# # XXX: Enforce on import.
# pass
# else:
# raise e
#
# def save(self, *args, **kwargs):
# if not self.api_key:
# self.api_key = generate_key()
# if not self.share_key:
# self.share_key = generate_key()
# super(Metric, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['position', '-id']
. Output only the next line. | model = Dashboard |
Continue the code snippet: <|code_start|>
class NewDashboardForm(forms.ModelForm):
name = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={
'placeholder': _('e.g. My Dashboard Name')
})
)
class Meta:
fields = ('name', 'owner')
model = Dashboard
class ManageDashboardForm(NewDashboardForm):
class Meta:
fields = ('name', 'owner')
model = Dashboard
class NewMetricForm(forms.ModelForm):
name = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={
'placeholder': _('e.g. My Metric Name')
})
)
class Meta:
fields = ('name', 'widget_type', )
<|code_end|>
. Use current file imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from holodeck.models import Dashboard, Metric
and context (classes, functions, or code) from other files:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
#
# class Metric(models.Model):
# name = models.CharField(max_length=255)
# description = models.TextField(
# blank=True,
# null=True,
# )
# dashboard = models.ForeignKey('holodeck.Dashboard')
# widget_type = models.CharField(
# max_length=64,
# choices=get_widget_type_choices()
# )
# api_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
# position = models.IntegerField(
# blank=True,
# null=True,
# )
#
# def __unicode__(self):
# return self.name
#
# @property
# def widget(self):
# return load_class_by_string(self.widget_type)()
#
# def render(self, context, minimal=False):
# return self.widget.render(self, context, minimal)
#
# def export(self, workbook):
# """
# Given a xlwt Excel workbook creates a sheet and populates it
# with samples for this metric.
# """
# samples = {}
# worksheet = workbook.add_sheet(self.name[:31])
#
# samples = self.sample_set.all()
#
# date_format = 'D-MMM-YY H:MM:SS'
# date_style = xlwt.easyxf(num_format_str=date_format)
#
# # Write distinct reverse sorted timestamps as first column.
# timestamps = list(set([sample.timestamp for sample in samples]))
# timestamps.sort(reverse=True)
# for i, timestamp in enumerate(timestamps):
# worksheet.write(i + 1, 0, timestamp, date_style)
#
# # Set timestamp column width.
# # Each character's approximated width is 256
# worksheet.col(0).width = (1 + len(date_format)) * 256
#
# # Write distinct sorted string values as first row.
# string_values = list(set([sample.string_value for sample in samples]))
# string_values.sort()
# for i, string_value in enumerate(string_values):
# worksheet.write(0, i + 1, string_value)
# worksheet.col(i + 1).width = (1 + len(string_value)) * 256
#
# # Write sample values as they correspond to timestamp and string_value.
# for sample in samples:
# row = timestamps.index(sample.timestamp) + 1
# col = string_values.index(sample.string_value) + 1
#
# try:
# worksheet.write(row, col, sample.integer_value)
# if len(str(sample.integer_value)) > len(sample.string_value):
# worksheet.col(col).width = (
# 1 + len(str(sample.integer_value))
# ) * 256
# except Exception, e:
# if 'overwrite' in e.message:
# # Ignore duplicate samples.
# # XXX: Enforce on import.
# pass
# else:
# raise e
#
# def save(self, *args, **kwargs):
# if not self.api_key:
# self.api_key = generate_key()
# if not self.share_key:
# self.share_key = generate_key()
# super(Metric, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['position', '-id']
. Output only the next line. | model = Metric |
Predict the next line for this snippet: <|code_start|>
def login_required(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
if not request.user.is_authenticated():
request.session['_next'] = request.build_absolute_uri()
return HttpResponseRedirect(reverse('holodeck-login'))
return func(request, *args, **kwargs)
return wrapped
def validate_share(func):
@wraps(func)
def wrapped(request, dashboard_id, share_key, *args, **kwargs):
try:
<|code_end|>
with the help of current file imports:
from functools import wraps
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from holodeck.models import Dashboard
and context from other files:
# Path: holodeck/models.py
# class Dashboard(models.Model):
# name = models.CharField(max_length=255)
# owner = models.ForeignKey(User, null=True)
# share_key = models.CharField(
# max_length=32,
# unique=True,
# blank=True,
# null=True
# )
#
# def save(self, *args, **kwargs):
# if not self.share_key:
# self.share_key = generate_key()
# super(Dashboard, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.name
, which may contain function names, class names, or code. Output only the next line. | Dashboard.objects.get(id=dashboard_id, share_key=share_key) |
Here is a snippet: <|code_start|>
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
<|code_end|>
. Write the next line using the current file imports:
import sys
import pytest
import MySQLdb
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
and context from other files:
# Path: opentracing_instrumentation/client_hooks/mysqldb.py
# class MySQLdbPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
, which may include functions, classes, or code. Output only the next line. | mysqldb_hooks.install_patches() |
Given snippet: <|code_start|> yield
finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import pytest
import MySQLdb
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
and context:
# Path: opentracing_instrumentation/client_hooks/mysqldb.py
# class MySQLdbPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
which might include code, classes, or functions. Output only the next line. | with span_in_context(root_span): |
Using the snippet: <|code_start|>
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
<|code_end|>
, determine the next line of code. You have imports:
import sys
import pytest
import MySQLdb
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
and context (class names, function names, or code) available:
# Path: opentracing_instrumentation/client_hooks/mysqldb.py
# class MySQLdbPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
. Output only the next line. | metadata.create_all(engine) |
Given snippet: <|code_start|> finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_in_context(root_span):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import pytest
import MySQLdb
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
and context:
# Path: opentracing_instrumentation/client_hooks/mysqldb.py
# class MySQLdbPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
which might include code, classes, or functions. Output only the next line. | user = User(name='user', fullname='User', password='password') |
Next line prediction: <|code_start|> try:
dynamodb.Table('users').delete()
except ClientError as error:
# you can not just use ResourceNotFoundException class
# to catch an error since it doesn't exist until it's raised
if error.__class__.__name__ != 'ResourceNotFoundException':
raise
create_users_table(dynamodb)
# waiting until the table exists
dynamodb.meta.client.get_waiter('table_exists').wait(TableName='users')
return dynamodb
@pytest.fixture
def s3_mock():
with moto.mock_s3():
s3 = boto3.client('s3', region_name='us-east-1')
yield s3
@pytest.fixture
def s3():
return boto3.client('s3', **S3_CONFIG)
@pytest.fixture(autouse=True)
def patch_boto3():
<|code_end|>
. Use current file imports:
(import datetime
import io
import boto3
import mock
import pytest
import requests
import testfixtures
import moto
import moto
import moto
from botocore.exceptions import ClientError
from opentracing.ext import tags
from opentracing_instrumentation.client_hooks import boto3 as boto3_hooks)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/client_hooks/boto3.py
# class Boto3Patcher(Patcher):
# class InstrumentedExecutor(_Executor):
# S3_FUNCTIONS_TO_INSTRUMENT = (
# 'copy',
# 'download_file',
# 'download_fileobj',
# 'upload_file',
# 'upload_fileobj',
# )
# def __init__(self):
# def _install_patches(self):
# def _reset_patches(self):
# def set_request_id_tag(span, response):
# def _get_service_action_call_wrapper(self):
# def service_action_call_wrapper(service, parent, *args, **kwargs):
# def _get_client_make_api_call_wrapper(self):
# def make_api_call_wrapper(client, operation_name, api_params):
# def _get_s3_call_wrapper(self, original_func):
# def s3_call_wrapper(*args, **kwargs):
# def perform_call(self, original_func, kind, service_name, operation_name,
# *args, **kwargs):
# def _get_instrumented_executor_cls(self):
# def submit(self, task, *args, **kwargs):
. Output only the next line. | boto3_hooks.install_patches() |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
<|code_end|>
with the help of current file imports:
import pytest
import sqlalchemy.engine.url
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import (
sqlalchemy as sqlalchemy_hooks
)
from .sql_common import metadata, User
and context from other files:
# Path: opentracing_instrumentation/client_hooks/sqlalchemy.py
# class SQLAlchemyPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
# def before_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
# def after_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
, which may contain function names, class names, or code. Output only the next line. | sqlalchemy_hooks.install_patches() |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
<|code_end|>
with the help of current file imports:
import pytest
import sqlalchemy.engine.url
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import (
sqlalchemy as sqlalchemy_hooks
)
from .sql_common import metadata, User
and context from other files:
# Path: opentracing_instrumentation/client_hooks/sqlalchemy.py
# class SQLAlchemyPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
# def before_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
# def after_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
, which may contain function names, class names, or code. Output only the next line. | metadata.create_all(engine) |
Continue the code snippet: <|code_start|>@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
sqlalchemy_hooks.install_patches()
try:
yield
finally:
sqlalchemy_hooks.reset_patches()
def assert_span(span, operation):
assert span.operation_name == 'SQL ' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
assert span.tags.get(tags.DATABASE_TYPE) == 'sqlite'
assert span.tags.get(tags.DATABASE_INSTANCE) == 'sqlite://'
assert span.tags.get(tags.COMPONENT) == 'sqlalchemy'
def test_db(tracer, session):
<|code_end|>
. Use current file imports:
import pytest
import sqlalchemy.engine.url
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import (
sqlalchemy as sqlalchemy_hooks
)
from .sql_common import metadata, User
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/client_hooks/sqlalchemy.py
# class SQLAlchemyPatcher(Patcher):
# def _install_patches(self):
# def _reset_patches(self):
# def before_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
# def after_cursor_execute(conn, cursor, statement, parameters, context,
# executemany):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
. Output only the next line. | user = User(name='user', fullname='User', password='password') |
Given the code snippet: <|code_start|>
def _get_client_make_api_call_wrapper(self):
def make_api_call_wrapper(client, operation_name, api_params):
"""Wraps BaseClient._make_api_call"""
service_name = client._service_model.service_name
formatted_operation_name = xform_name(operation_name)
return self.perform_call(
_client_make_api_call, 'client',
service_name, formatted_operation_name,
client, operation_name, api_params
)
return make_api_call_wrapper
def _get_s3_call_wrapper(self, original_func):
operation_name = original_func.__name__
def s3_call_wrapper(*args, **kwargs):
"""Wraps __call__ of S3 client methods"""
return self.perform_call(
original_func, 'client', 's3', operation_name, *args, **kwargs
)
return s3_call_wrapper
def perform_call(self, original_func, kind, service_name, operation_name,
*args, **kwargs):
<|code_end|>
, generate the next line using the imports in this file:
import logging
from opentracing.ext import tags
from tornado.stack_context import wrap as keep_stack_context
from opentracing_instrumentation import utils
from ..request_context import get_current_span, span_in_stack_context
from ._patcher import Patcher
from boto3.resources.action import ServiceAction
from boto3.s3 import inject as s3_functions
from botocore import xform_name
from botocore.client import BaseClient
from botocore.exceptions import ClientError
from s3transfer.futures import BoundedExecutor
and context (functions, classes, or occasionally code) from other files:
# Path: opentracing_instrumentation/utils.py
# def start_child_span(operation_name, tracer=None, parent=None, tags=None):
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | span = utils.start_child_span( |
Given the code snippet: <|code_start|>
service_name = client._service_model.service_name
formatted_operation_name = xform_name(operation_name)
return self.perform_call(
_client_make_api_call, 'client',
service_name, formatted_operation_name,
client, operation_name, api_params
)
return make_api_call_wrapper
def _get_s3_call_wrapper(self, original_func):
operation_name = original_func.__name__
def s3_call_wrapper(*args, **kwargs):
"""Wraps __call__ of S3 client methods"""
return self.perform_call(
original_func, 'client', 's3', operation_name, *args, **kwargs
)
return s3_call_wrapper
def perform_call(self, original_func, kind, service_name, operation_name,
*args, **kwargs):
span = utils.start_child_span(
operation_name='boto3:{}:{}:{}'.format(
kind, service_name, operation_name
),
<|code_end|>
, generate the next line using the imports in this file:
import logging
from opentracing.ext import tags
from tornado.stack_context import wrap as keep_stack_context
from opentracing_instrumentation import utils
from ..request_context import get_current_span, span_in_stack_context
from ._patcher import Patcher
from boto3.resources.action import ServiceAction
from boto3.s3 import inject as s3_functions
from botocore import xform_name
from botocore.client import BaseClient
from botocore.exceptions import ClientError
from s3transfer.futures import BoundedExecutor
and context (functions, classes, or occasionally code) from other files:
# Path: opentracing_instrumentation/utils.py
# def start_child_span(operation_name, tracer=None, parent=None, tags=None):
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | parent=get_current_span() |
Next line prediction: <|code_start|> client, operation_name, api_params
)
return make_api_call_wrapper
def _get_s3_call_wrapper(self, original_func):
operation_name = original_func.__name__
def s3_call_wrapper(*args, **kwargs):
"""Wraps __call__ of S3 client methods"""
return self.perform_call(
original_func, 'client', 's3', operation_name, *args, **kwargs
)
return s3_call_wrapper
def perform_call(self, original_func, kind, service_name, operation_name,
*args, **kwargs):
span = utils.start_child_span(
operation_name='boto3:{}:{}:{}'.format(
kind, service_name, operation_name
),
parent=get_current_span()
)
span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
span.set_tag(tags.COMPONENT, 'boto3')
span.set_tag('boto3.service_name', service_name)
<|code_end|>
. Use current file imports:
(import logging
from opentracing.ext import tags
from tornado.stack_context import wrap as keep_stack_context
from opentracing_instrumentation import utils
from ..request_context import get_current_span, span_in_stack_context
from ._patcher import Patcher
from boto3.resources.action import ServiceAction
from boto3.s3 import inject as s3_functions
from botocore import xform_name
from botocore.client import BaseClient
from botocore.exceptions import ClientError
from s3transfer.futures import BoundedExecutor)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/utils.py
# def start_child_span(operation_name, tracer=None, parent=None, tags=None):
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | with span, span_in_stack_context(span): |
Based on the snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_service_action_call = ServiceAction.__call__
_client_make_api_call = BaseClient._make_api_call
_Executor = BoundedExecutor.EXECUTOR_CLS
logger = logging.getLogger(__name__)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from opentracing.ext import tags
from tornado.stack_context import wrap as keep_stack_context
from opentracing_instrumentation import utils
from ..request_context import get_current_span, span_in_stack_context
from ._patcher import Patcher
from boto3.resources.action import ServiceAction
from boto3.s3 import inject as s3_functions
from botocore import xform_name
from botocore.client import BaseClient
from botocore.exceptions import ClientError
from s3transfer.futures import BoundedExecutor
and context (classes, functions, sometimes code) from other files:
# Path: opentracing_instrumentation/utils.py
# def start_child_span(operation_name, tracer=None, parent=None, tags=None):
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | class Boto3Patcher(Patcher): |
Here is a snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
def test_creates_instance():
wsgi_environ = {
'SERVER_NAME': 'localhost',
'SERVER_PORT': '8888',
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/Farnsworth',
'HTTP_X_FOO': 'bar',
'REMOTE_ADDR': 'localhost',
'REMOTE_PORT': '80',
'wsgi.url_scheme': 'http'
}
<|code_end|>
. Write the next line using the current file imports:
import mock
from opentracing_instrumentation.http_server import WSGIRequestWrapper
from opentracing_instrumentation import config
and context from other files:
# Path: opentracing_instrumentation/http_server.py
# class WSGIRequestWrapper(AbstractRequestWrapper):
# """
# Wraps WSGI environment and exposes several properties
# used by the tracing methods.
# """
#
# def __init__(self, wsgi_environ, headers):
# self.wsgi_environ = wsgi_environ
# self._headers = headers
#
# @classmethod
# def from_wsgi_environ(cls, wsgi_environ):
# instance = cls(wsgi_environ=wsgi_environ,
# headers=cls._parse_wsgi_headers(wsgi_environ))
# return instance
#
# @staticmethod
# def _parse_wsgi_headers(wsgi_environ):
# """
# HTTP headers are presented in WSGI environment with 'HTTP_' prefix.
# This method finds those headers, removes the prefix, converts
# underscores to dashes, and converts to lower case.
#
# :param wsgi_environ:
# :return: returns a dictionary of headers
# """
# prefix = 'HTTP_'
# p_len = len(prefix)
# # use .items() despite suspected memory pressure bc GC occasionally
# # collects wsgi_environ.iteritems() during iteration.
# headers = {
# key[p_len:].replace('_', '-').lower():
# val for (key, val) in wsgi_environ.items()
# if key.startswith(prefix)}
# return headers
#
# @property
# def full_url(self):
# """
# Taken from
# http://legacy.python.org/dev/peps/pep-3333/#url-reconstruction
#
# :return: Reconstructed URL from WSGI environment.
# """
# environ = self.wsgi_environ
# url = environ['wsgi.url_scheme'] + '://'
#
# if environ.get('HTTP_HOST'):
# url += environ['HTTP_HOST']
# else:
# url += environ['SERVER_NAME']
#
# if environ['wsgi.url_scheme'] == 'https':
# if environ['SERVER_PORT'] != '443':
# url += ':' + environ['SERVER_PORT']
# else:
# if environ['SERVER_PORT'] != '80':
# url += ':' + environ['SERVER_PORT']
#
# url += urllib.parse.quote(environ.get('SCRIPT_NAME', ''))
# url += urllib.parse.quote(environ.get('PATH_INFO', ''))
# if environ.get('QUERY_STRING'):
# url += '?' + environ['QUERY_STRING']
# return url
#
# @property
# def headers(self):
# return self._headers
#
# @property
# def method(self):
# return self.wsgi_environ.get('REQUEST_METHOD')
#
# @property
# def remote_ip(self):
# return self.wsgi_environ.get('REMOTE_ADDR', None)
#
# @property
# def remote_port(self):
# return self.wsgi_environ.get('REMOTE_PORT', None)
#
# @property
# def server_port(self):
# return self.wsgi_environ.get('SERVER_PORT', None)
, which may include functions, classes, or code. Output only the next line. | request = WSGIRequestWrapper.from_wsgi_environ(wsgi_environ) |
Predict the next line after this snippet: <|code_start|># The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
try:
asyncio_available = True
except ImportError:
asyncio_available = False
@pytest.fixture(name='response_handler_hook')
def patch_requests(hook):
if hook:
# using regular method instead of mock.Mock() to be sure
# that it works as expected with Python 2.7
def response_handler_hook(response, span):
response_handler_hook.called_with = response, span
response_handler_hook.called_with = None
else:
response_handler_hook = None
<|code_end|>
using the current file's imports:
import threading
import mock
import pytest
import requests
import tornado.httpserver
import tornado.ioloop
import tornado.web
import asyncio
from opentracing_instrumentation.client_hooks.requests import patcher
from opentracing_instrumentation.request_context import span_in_context
and any relevant context from other files:
# Path: opentracing_instrumentation/client_hooks/requests.py
# class RequestsPatcher(Patcher):
# class RequestWrapper(AbstractRequestWrapper):
# def set_response_handler_hook(self, response_handler_hook):
# def _install_patches(self):
# def _reset_patches(self):
# def _get_send_wrapper(self):
# def send_wrapper(http_adapter, request, **kwargs):
# def __init__(self, request):
# def add_header(self, key, value):
# def method(self):
# def full_url(self):
# def _headers(self):
# def host_port(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
. Output only the next line. | patcher.install_patches() |
Next line prediction: <|code_start|> # In python 3+ we should make ioloop in new thread explicitly.
asyncio.set_event_loop(asyncio.new_event_loop())
io_loop = tornado.ioloop.IOLoop.current()
http_server = tornado.httpserver.HTTPServer(app)
http_server.add_socket(_unused_port[0])
def stop():
http_server.stop()
io_loop.add_callback(io_loop.stop)
thread.join()
# finalizer should be added before starting of the IO loop
request.addfinalizer(stop)
io_loop.start()
# running an http server in a separate thread in purpose
# to make it accessible for the requests from the current thread
thread = threading.Thread(target=run_http_server)
thread.start()
return base_url + '/'
def _test_requests(url, root_span, tracer, response_handler_hook):
if root_span:
root_span = tracer.start_span('root-span')
else:
root_span = None
<|code_end|>
. Use current file imports:
(import threading
import mock
import pytest
import requests
import tornado.httpserver
import tornado.ioloop
import tornado.web
import asyncio
from opentracing_instrumentation.client_hooks.requests import patcher
from opentracing_instrumentation.request_context import span_in_context)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/client_hooks/requests.py
# class RequestsPatcher(Patcher):
# class RequestWrapper(AbstractRequestWrapper):
# def set_response_handler_hook(self, response_handler_hook):
# def _install_patches(self):
# def _reset_patches(self):
# def _get_send_wrapper(self):
# def send_wrapper(http_adapter, request, **kwargs):
# def __init__(self, request):
# def add_header(self, key, value):
# def method(self):
# def full_url(self):
# def _headers(self):
# def host_port(self):
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
. Output only the next line. | with span_in_context(span=root_span): |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_task_apply_async = Task.apply_async
def task_apply_async_wrapper(task, args=None, kwargs=None, **other_kwargs):
operation_name = 'Celery:apply_async:{}'.format(task.name)
span = opentracing.tracer.start_span(operation_name=operation_name,
<|code_end|>
with the help of current file imports:
import opentracing
from opentracing.ext import tags
from ..request_context import get_current_span, span_in_context
from ._patcher import Patcher
from celery.app.task import Task
from celery.signals import (
before_task_publish, task_prerun, task_success, task_failure
)
and context from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
, which may contain function names, class names, or code. Output only the next line. | child_of=get_current_span()) |
Using the snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_task_apply_async = Task.apply_async
def task_apply_async_wrapper(task, args=None, kwargs=None, **other_kwargs):
operation_name = 'Celery:apply_async:{}'.format(task.name)
span = opentracing.tracer.start_span(operation_name=operation_name,
child_of=get_current_span())
set_common_tags(span, task, tags.SPAN_KIND_RPC_CLIENT)
<|code_end|>
, determine the next line of code. You have imports:
import opentracing
from opentracing.ext import tags
from ..request_context import get_current_span, span_in_context
from ._patcher import Patcher
from celery.app.task import Task
from celery.signals import (
before_task_publish, task_prerun, task_success, task_failure
)
and context (class names, function names, or code) available:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | with span_in_context(span), span: |
Given the following code snippet before the placeholder: <|code_start|>
task.request.span = span = opentracing.tracer.start_span(
operation_name=operation_name,
child_of=child_of,
)
set_common_tags(span, task, tags.SPAN_KIND_RPC_SERVER)
span.set_tag('celery.task_id', task_id)
request.tracing_context = span_in_context(span)
request.tracing_context.__enter__()
def finish_current_span(task, exc_type=None, exc_val=None, exc_tb=None):
task.request.span.finish()
task.request.tracing_context.__exit__(exc_type, exc_val, exc_tb)
def task_success_handler(sender, **kwargs):
finish_current_span(task=sender)
def task_failure_handler(sender, exception, traceback, **kwargs):
finish_current_span(
task=sender,
exc_type=type(exception),
exc_val=exception,
exc_tb=traceback,
)
<|code_end|>
, predict the next line using imports from the current file:
import opentracing
from opentracing.ext import tags
from ..request_context import get_current_span, span_in_context
from ._patcher import Patcher
from celery.app.task import Task
from celery.signals import (
before_task_publish, task_prerun, task_success, task_failure
)
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | class CeleryPatcher(Patcher): |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
@singleton
def install_patches():
def build_handler(base_type, base_cls=None):
"""Build a urrllib2 handler from a base_type."""
class DerivedHandler(base_type):
"""The class derived from base_type."""
def do_open(self, req, conn):
request_wrapper = Urllib2RequestWrapper(request=req)
span = before_http_request(
request=request_wrapper,
current_span_extractor=current_span_func)
with span:
if base_cls:
# urllib2.AbstractHTTPHandler doesn't support super()
resp = base_cls.do_open(self, conn, req)
else:
resp = super(DerivedHandler, self).do_open(conn, req)
if resp.code is not None:
span.set_tag(ext_tags.HTTP_STATUS_CODE, resp.code)
return resp
return DerivedHandler
<|code_end|>
. Write the next line using the current file imports:
import logging
import six
import http.client
import urllib.request
import urllib2
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags as ext_tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from ._singleton import singleton
from ._current_span import current_span_func
and context from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
, which may include functions, classes, or code. Output only the next line. | class Urllib2RequestWrapper(AbstractRequestWrapper): |
Continue the code snippet: <|code_start|>#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
log = logging.getLogger(__name__)
@singleton
def install_patches():
def build_handler(base_type, base_cls=None):
"""Build a urrllib2 handler from a base_type."""
class DerivedHandler(base_type):
"""The class derived from base_type."""
def do_open(self, req, conn):
request_wrapper = Urllib2RequestWrapper(request=req)
<|code_end|>
. Use current file imports:
import logging
import six
import http.client
import urllib.request
import urllib2
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags as ext_tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from ._singleton import singleton
from ._current_span import current_span_func
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | span = before_http_request( |
Based on the snippet: <|code_start|> span.set_tag(ext_tags.HTTP_STATUS_CODE, resp.code)
return resp
return DerivedHandler
class Urllib2RequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.request = request
self._norm_headers = None
def add_header(self, key, value):
self.request.add_header(key, value)
@property
def method(self):
return self.request.get_method()
@property
def full_url(self):
return self.request.get_full_url()
@property
def _headers(self):
if self._norm_headers is None:
self._norm_headers = HTTPHeaders(self.request.headers)
return self._norm_headers
@property
def host_port(self):
host_string = self.request.host
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import six
import http.client
import urllib.request
import urllib2
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags as ext_tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from ._singleton import singleton
from ._current_span import current_span_func
and context (classes, functions, sometimes code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | return split_host_and_port(host_string=host_string, |
Based on the snippet: <|code_start|># Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
log = logging.getLogger(__name__)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import six
import http.client
import urllib.request
import urllib2
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags as ext_tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from ._singleton import singleton
from ._current_span import current_span_func
and context (classes, functions, sometimes code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | @singleton |
Given the following code snippet before the placeholder: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
log = logging.getLogger(__name__)
@singleton
def install_patches():
def build_handler(base_type, base_cls=None):
"""Build a urrllib2 handler from a base_type."""
class DerivedHandler(base_type):
"""The class derived from base_type."""
def do_open(self, req, conn):
request_wrapper = Urllib2RequestWrapper(request=req)
span = before_http_request(
request=request_wrapper,
<|code_end|>
, predict the next line using imports from the current file:
import logging
import six
import http.client
import urllib.request
import urllib2
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags as ext_tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from ._singleton import singleton
from ._current_span import current_span_func
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | current_span_extractor=current_span_func) |
Predict the next line after this snippet: <|code_start|># copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
# Try to save the original entry points
try:
except ImportError:
pass
else:
_MySQLdb_connect = MySQLdb.connect
class MySQLdbPatcher(Patcher):
applicable = '_MySQLdb_connect' in globals()
def _install_patches(self):
factory = ConnectionFactory(connect_func=MySQLdb.connect,
module_name='MySQLdb',
<|code_end|>
using the current file's imports:
from ._dbapi2 import ContextManagerConnectionWrapper as ConnectionWrapper
from ._dbapi2 import ConnectionFactory
from ._patcher import Patcher
import MySQLdb
and any relevant context from other files:
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ContextManagerConnectionWrapper(ConnectionWrapper):
# """
# Extends ConnectionWrapper by implementing `__enter__` and `__exit__`
# methods of the context manager API, for connections that can be used
# in as context managers to control the transactions, e.g.
#
# .. code-block:: python
#
# with MySQLdb.connect(...) as cursor:
# cursor.execute(...)
# """
#
# def __init__(self, connection, module_name, connect_params,
# cursor_wrapper):
# super(ContextManagerConnectionWrapper, self).__init__(
# connection=connection,
# module_name=module_name,
# connect_params=connect_params,
# cursor_wrapper=cursor_wrapper
# )
#
# def __getattr__(self, name):
# # Tip suggested here:
# # https://gist.github.com/mjallday/3d4c92e7e6805af1e024.
# if name == '_sqla_unwrap':
# return self.__wrapped__
# return super(ContextManagerConnectionWrapper, self).__getattr__(name)
#
# def __enter__(self):
# with func_span('%s:begin_transaction' % self._module_name):
# cursor = self.__wrapped__.__enter__()
#
# return CursorWrapper(cursor=cursor,
# module_name=self._module_name,
# connect_params=self._connect_params)
#
# def __exit__(self, exc, value, tb):
# outcome = _COMMIT if exc is None else _ROLLBACK
# with db_span(sql_statement=outcome, module_name=self._module_name):
# return self.__wrapped__.__exit__(exc, value, tb)
#
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ConnectionFactory(object):
# """
# Wraps connect_func of the DB API v2 module by creating a wrapper object
# for the actual connection.
# """
#
# def __init__(self, connect_func, module_name, conn_wrapper_ctor=None,
# cursor_wrapper=CursorWrapper):
# self._connect_func = connect_func
# self._module_name = module_name
# if hasattr(connect_func, '__name__'):
# self._connect_func_name = '%s:%s' % (module_name,
# connect_func.__name__)
# else:
# self._connect_func_name = '%s:%s' % (module_name, connect_func)
# self._wrapper_ctor = conn_wrapper_ctor \
# if conn_wrapper_ctor is not None else ConnectionWrapper
# self._cursor_wrapper = cursor_wrapper
#
# def __call__(self, *args, **kwargs):
# safe_kwargs = kwargs
# if 'passwd' in kwargs or 'password' in kwargs or 'conv' in kwargs:
# safe_kwargs = dict(kwargs)
# if 'passwd' in safe_kwargs:
# del safe_kwargs['passwd']
# if 'password' in safe_kwargs:
# del safe_kwargs['password']
# if 'conv' in safe_kwargs: # don't log conversion functions
# del safe_kwargs['conv']
# connect_params = (args, safe_kwargs) if args or safe_kwargs else None
# tags = {ext_tags.SPAN_KIND: ext_tags.SPAN_KIND_RPC_CLIENT}
# with func_span(self._connect_func_name, tags=tags):
# return self._wrapper_ctor(
# connection=self._connect_func(*args, **kwargs),
# module_name=self._module_name,
# connect_params=connect_params,
# cursor_wrapper=self._cursor_wrapper)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | conn_wrapper_ctor=ConnectionWrapper) |
Continue the code snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
# Try to save the original entry points
try:
except ImportError:
pass
else:
_MySQLdb_connect = MySQLdb.connect
class MySQLdbPatcher(Patcher):
applicable = '_MySQLdb_connect' in globals()
def _install_patches(self):
<|code_end|>
. Use current file imports:
from ._dbapi2 import ContextManagerConnectionWrapper as ConnectionWrapper
from ._dbapi2 import ConnectionFactory
from ._patcher import Patcher
import MySQLdb
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ContextManagerConnectionWrapper(ConnectionWrapper):
# """
# Extends ConnectionWrapper by implementing `__enter__` and `__exit__`
# methods of the context manager API, for connections that can be used
# in as context managers to control the transactions, e.g.
#
# .. code-block:: python
#
# with MySQLdb.connect(...) as cursor:
# cursor.execute(...)
# """
#
# def __init__(self, connection, module_name, connect_params,
# cursor_wrapper):
# super(ContextManagerConnectionWrapper, self).__init__(
# connection=connection,
# module_name=module_name,
# connect_params=connect_params,
# cursor_wrapper=cursor_wrapper
# )
#
# def __getattr__(self, name):
# # Tip suggested here:
# # https://gist.github.com/mjallday/3d4c92e7e6805af1e024.
# if name == '_sqla_unwrap':
# return self.__wrapped__
# return super(ContextManagerConnectionWrapper, self).__getattr__(name)
#
# def __enter__(self):
# with func_span('%s:begin_transaction' % self._module_name):
# cursor = self.__wrapped__.__enter__()
#
# return CursorWrapper(cursor=cursor,
# module_name=self._module_name,
# connect_params=self._connect_params)
#
# def __exit__(self, exc, value, tb):
# outcome = _COMMIT if exc is None else _ROLLBACK
# with db_span(sql_statement=outcome, module_name=self._module_name):
# return self.__wrapped__.__exit__(exc, value, tb)
#
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ConnectionFactory(object):
# """
# Wraps connect_func of the DB API v2 module by creating a wrapper object
# for the actual connection.
# """
#
# def __init__(self, connect_func, module_name, conn_wrapper_ctor=None,
# cursor_wrapper=CursorWrapper):
# self._connect_func = connect_func
# self._module_name = module_name
# if hasattr(connect_func, '__name__'):
# self._connect_func_name = '%s:%s' % (module_name,
# connect_func.__name__)
# else:
# self._connect_func_name = '%s:%s' % (module_name, connect_func)
# self._wrapper_ctor = conn_wrapper_ctor \
# if conn_wrapper_ctor is not None else ConnectionWrapper
# self._cursor_wrapper = cursor_wrapper
#
# def __call__(self, *args, **kwargs):
# safe_kwargs = kwargs
# if 'passwd' in kwargs or 'password' in kwargs or 'conv' in kwargs:
# safe_kwargs = dict(kwargs)
# if 'passwd' in safe_kwargs:
# del safe_kwargs['passwd']
# if 'password' in safe_kwargs:
# del safe_kwargs['password']
# if 'conv' in safe_kwargs: # don't log conversion functions
# del safe_kwargs['conv']
# connect_params = (args, safe_kwargs) if args or safe_kwargs else None
# tags = {ext_tags.SPAN_KIND: ext_tags.SPAN_KIND_RPC_CLIENT}
# with func_span(self._connect_func_name, tags=tags):
# return self._wrapper_ctor(
# connection=self._connect_func(*args, **kwargs),
# module_name=self._module_name,
# connect_params=connect_params,
# cursor_wrapper=self._cursor_wrapper)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | factory = ConnectionFactory(connect_func=MySQLdb.connect, |
Given the code snippet: <|code_start|># Copyright (c) 2015,2019 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
# Try to save the original entry points
try:
except ImportError:
pass
else:
_MySQLdb_connect = MySQLdb.connect
<|code_end|>
, generate the next line using the imports in this file:
from ._dbapi2 import ContextManagerConnectionWrapper as ConnectionWrapper
from ._dbapi2 import ConnectionFactory
from ._patcher import Patcher
import MySQLdb
and context (functions, classes, or occasionally code) from other files:
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ContextManagerConnectionWrapper(ConnectionWrapper):
# """
# Extends ConnectionWrapper by implementing `__enter__` and `__exit__`
# methods of the context manager API, for connections that can be used
# in as context managers to control the transactions, e.g.
#
# .. code-block:: python
#
# with MySQLdb.connect(...) as cursor:
# cursor.execute(...)
# """
#
# def __init__(self, connection, module_name, connect_params,
# cursor_wrapper):
# super(ContextManagerConnectionWrapper, self).__init__(
# connection=connection,
# module_name=module_name,
# connect_params=connect_params,
# cursor_wrapper=cursor_wrapper
# )
#
# def __getattr__(self, name):
# # Tip suggested here:
# # https://gist.github.com/mjallday/3d4c92e7e6805af1e024.
# if name == '_sqla_unwrap':
# return self.__wrapped__
# return super(ContextManagerConnectionWrapper, self).__getattr__(name)
#
# def __enter__(self):
# with func_span('%s:begin_transaction' % self._module_name):
# cursor = self.__wrapped__.__enter__()
#
# return CursorWrapper(cursor=cursor,
# module_name=self._module_name,
# connect_params=self._connect_params)
#
# def __exit__(self, exc, value, tb):
# outcome = _COMMIT if exc is None else _ROLLBACK
# with db_span(sql_statement=outcome, module_name=self._module_name):
# return self.__wrapped__.__exit__(exc, value, tb)
#
# Path: opentracing_instrumentation/client_hooks/_dbapi2.py
# class ConnectionFactory(object):
# """
# Wraps connect_func of the DB API v2 module by creating a wrapper object
# for the actual connection.
# """
#
# def __init__(self, connect_func, module_name, conn_wrapper_ctor=None,
# cursor_wrapper=CursorWrapper):
# self._connect_func = connect_func
# self._module_name = module_name
# if hasattr(connect_func, '__name__'):
# self._connect_func_name = '%s:%s' % (module_name,
# connect_func.__name__)
# else:
# self._connect_func_name = '%s:%s' % (module_name, connect_func)
# self._wrapper_ctor = conn_wrapper_ctor \
# if conn_wrapper_ctor is not None else ConnectionWrapper
# self._cursor_wrapper = cursor_wrapper
#
# def __call__(self, *args, **kwargs):
# safe_kwargs = kwargs
# if 'passwd' in kwargs or 'password' in kwargs or 'conv' in kwargs:
# safe_kwargs = dict(kwargs)
# if 'passwd' in safe_kwargs:
# del safe_kwargs['passwd']
# if 'password' in safe_kwargs:
# del safe_kwargs['password']
# if 'conv' in safe_kwargs: # don't log conversion functions
# del safe_kwargs['conv']
# connect_params = (args, safe_kwargs) if args or safe_kwargs else None
# tags = {ext_tags.SPAN_KIND: ext_tags.SPAN_KIND_RPC_CLIENT}
# with func_span(self._connect_func_name, tags=tags):
# return self._wrapper_ctor(
# connection=self._connect_func(*args, **kwargs),
# module_name=self._module_name,
# connect_params=connect_params,
# cursor_wrapper=self._cursor_wrapper)
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
. Output only the next line. | class MySQLdbPatcher(Patcher): |
Based on the snippet: <|code_start|> It must have a signature `(response, span)`,
where `response` and `span` are positional arguments,
so you can use different names for them if needed.
"""
self.response_handler_hook = response_handler_hook
def _install_patches(self):
requests.adapters.HTTPAdapter.send = self._get_send_wrapper()
def _reset_patches(self):
requests.adapters.HTTPAdapter.send = _HTTPAdapter_send
def _get_send_wrapper(self):
def send_wrapper(http_adapter, request, **kwargs):
"""Wraps HTTPAdapter.send"""
request_wrapper = self.RequestWrapper(request=request)
span = before_http_request(request=request_wrapper,
current_span_extractor=current_span_func
)
with span:
response = _HTTPAdapter_send(http_adapter, request, **kwargs)
if getattr(response, 'status_code', None) is not None:
span.set_tag(tags.HTTP_STATUS_CODE, response.status_code)
if self.response_handler_hook is not None:
self.response_handler_hook(response, span)
return response
return send_wrapper
<|code_end|>
, predict the immediate next line with the help of imports:
from future import standard_library
from opentracing.ext import tags
from ..http_client import AbstractRequestWrapper
from ..http_client import before_http_request
from ..http_client import split_host_and_port
from ._patcher import Patcher
from ._current_span import current_span_func
import logging
import urllib.parse
import requests.adapters
and context (classes, functions, sometimes code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | class RequestWrapper(AbstractRequestWrapper): |
Next line prediction: <|code_start|>
class RequestsPatcher(Patcher):
applicable = '_HTTPAdapter_send' in globals()
response_handler_hook = None
def set_response_handler_hook(self, response_handler_hook):
"""
Set a hook that will be called when a response is received.
The hook can be set in purpose to set custom tags to spans
depending on content or some metadata of responses.
:param response_handler_hook: hook method
It must have a signature `(response, span)`,
where `response` and `span` are positional arguments,
so you can use different names for them if needed.
"""
self.response_handler_hook = response_handler_hook
def _install_patches(self):
requests.adapters.HTTPAdapter.send = self._get_send_wrapper()
def _reset_patches(self):
requests.adapters.HTTPAdapter.send = _HTTPAdapter_send
def _get_send_wrapper(self):
def send_wrapper(http_adapter, request, **kwargs):
"""Wraps HTTPAdapter.send"""
request_wrapper = self.RequestWrapper(request=request)
<|code_end|>
. Use current file imports:
(from future import standard_library
from opentracing.ext import tags
from ..http_client import AbstractRequestWrapper
from ..http_client import before_http_request
from ..http_client import split_host_and_port
from ._patcher import Patcher
from ._current_span import current_span_func
import logging
import urllib.parse
import requests.adapters)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | span = before_http_request(request=request_wrapper, |
Next line prediction: <|code_start|> return response
return send_wrapper
class RequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.request = request
self.scheme, rest = urllib.parse.splittype(request.url)
if self.scheme and rest:
self.host_str, _ = urllib.parse.splithost(rest)
else:
self.host_str = ''
def add_header(self, key, value):
self.request.headers[key] = value
@property
def method(self):
return self.request.method
@property
def full_url(self):
return self.request.url
@property
def _headers(self):
return self.request.headers
@property
def host_port(self):
<|code_end|>
. Use current file imports:
(from future import standard_library
from opentracing.ext import tags
from ..http_client import AbstractRequestWrapper
from ..http_client import before_http_request
from ..http_client import split_host_and_port
from ._patcher import Patcher
from ._current_span import current_span_func
import logging
import urllib.parse
import requests.adapters)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | return split_host_and_port(host_string=self.host_str, |
Predict the next line after this snippet: <|code_start|># copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
log = logging.getLogger(__name__)
# Try to save the original entry points
try:
except ImportError:
pass
else:
_HTTPAdapter_send = requests.adapters.HTTPAdapter.send
<|code_end|>
using the current file's imports:
from future import standard_library
from opentracing.ext import tags
from ..http_client import AbstractRequestWrapper
from ..http_client import before_http_request
from ..http_client import split_host_and_port
from ._patcher import Patcher
from ._current_span import current_span_func
import logging
import urllib.parse
import requests.adapters
and any relevant context from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | class RequestsPatcher(Patcher): |
Given the following code snippet before the placeholder: <|code_start|>class RequestsPatcher(Patcher):
applicable = '_HTTPAdapter_send' in globals()
response_handler_hook = None
def set_response_handler_hook(self, response_handler_hook):
"""
Set a hook that will be called when a response is received.
The hook can be set in purpose to set custom tags to spans
depending on content or some metadata of responses.
:param response_handler_hook: hook method
It must have a signature `(response, span)`,
where `response` and `span` are positional arguments,
so you can use different names for them if needed.
"""
self.response_handler_hook = response_handler_hook
def _install_patches(self):
requests.adapters.HTTPAdapter.send = self._get_send_wrapper()
def _reset_patches(self):
requests.adapters.HTTPAdapter.send = _HTTPAdapter_send
def _get_send_wrapper(self):
def send_wrapper(http_adapter, request, **kwargs):
"""Wraps HTTPAdapter.send"""
request_wrapper = self.RequestWrapper(request=request)
span = before_http_request(request=request_wrapper,
<|code_end|>
, predict the next line using imports from the current file:
from future import standard_library
from opentracing.ext import tags
from ..http_client import AbstractRequestWrapper
from ..http_client import before_http_request
from ..http_client import split_host_and_port
from ._patcher import Patcher
from ._current_span import current_span_func
import logging
import urllib.parse
import requests.adapters
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
#
# def __init__(self):
# self.patches_installed = False
#
# @property
# def applicable(self):
# raise NotImplementedError
#
# def install_patches(self):
# if self.patches_installed:
# return
#
# if self.applicable:
# self._install_patches()
# self.patches_installed = True
#
# def reset_patches(self):
# if self.applicable:
# self._reset_patches()
# self.patches_installed = False
#
# def _install_patches(self):
# raise NotImplementedError
#
# def _reset_patches(self):
# raise NotImplementedError
#
# @classmethod
# def configure_hook_module(cls, context):
# def set_patcher(custom_patcher):
# context['patcher'] = custom_patcher
#
# def install_patches():
# context['patcher'].install_patches()
#
# def reset_patches():
# context['patcher'].reset_patches()
#
# context['patcher'] = cls()
# context['set_patcher'] = set_patcher
# context['install_patches'] = install_patches
# context['reset_patches'] = reset_patches
#
# Path: opentracing_instrumentation/client_hooks/_current_span.py
# def set_current_span_func(span_extractor_func):
. Output only the next line. | current_span_extractor=current_span_func |
Continue the code snippet: <|code_start|># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
if six.PY2:
@pytest.yield_fixture
def install_hooks(request):
urllibver = request.getfixturevalue('urllibver')
if urllibver == 'urllib2':
if six.PY3:
yield None
return
module = urllib2
else:
module = urllib.request
old_opener = module._opener
old_callee_headers = CONFIG.callee_name_headers
old_endpoint_headers = CONFIG.callee_endpoint_headers
<|code_end|>
. Use current file imports:
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing_instrumentation.client_hooks import urllib2 as urllib2_hooks
from opentracing_instrumentation.config import CONFIG
from opentracing_instrumentation.request_context import span_in_context
import mock
import pytest
import six
import urllib2
import urllib.request
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/client_hooks/urllib2.py
# def install_patches():
# def build_handler(base_type, base_cls=None):
# def do_open(self, req, conn):
# def __init__(self, request):
# def add_header(self, key, value):
# def method(self):
# def full_url(self):
# def _headers(self):
# def host_port(self):
# def install_for_module(module, do_open_base=None):
# def http_open(self, req):
# def https_open(self, req):
# class DerivedHandler(base_type):
# class Urllib2RequestWrapper(AbstractRequestWrapper):
# class TracedHTTPHandler(httpBase):
# class TracedHTTPSHandler(httpsBase):
#
# Path: opentracing_instrumentation/config.py
# CONFIG = _Config()
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
. Output only the next line. | urllib2_hooks.install_patches.__original_func() |
Predict the next line for this snippet: <|code_start|>#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
standard_library.install_aliases()
if six.PY2:
@pytest.yield_fixture
def install_hooks(request):
urllibver = request.getfixturevalue('urllibver')
if urllibver == 'urllib2':
if six.PY3:
yield None
return
module = urllib2
else:
module = urllib.request
old_opener = module._opener
<|code_end|>
with the help of current file imports:
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing_instrumentation.client_hooks import urllib2 as urllib2_hooks
from opentracing_instrumentation.config import CONFIG
from opentracing_instrumentation.request_context import span_in_context
import mock
import pytest
import six
import urllib2
import urllib.request
and context from other files:
# Path: opentracing_instrumentation/client_hooks/urllib2.py
# def install_patches():
# def build_handler(base_type, base_cls=None):
# def do_open(self, req, conn):
# def __init__(self, request):
# def add_header(self, key, value):
# def method(self):
# def full_url(self):
# def _headers(self):
# def host_port(self):
# def install_for_module(module, do_open_base=None):
# def http_open(self, req):
# def https_open(self, req):
# class DerivedHandler(base_type):
# class Urllib2RequestWrapper(AbstractRequestWrapper):
# class TracedHTTPHandler(httpBase):
# class TracedHTTPSHandler(httpsBase):
#
# Path: opentracing_instrumentation/config.py
# CONFIG = _Config()
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
, which may contain function names, class names, or code. Output only the next line. | old_callee_headers = CONFIG.callee_name_headers |
Predict the next line after this snippet: <|code_start|>
if module is None:
pytest.skip('Skipping %s on Py3' % urllibver)
class Response(object):
def __init__(self):
self.code = 200
self.msg = ''
def info(self):
return None
if root_span:
root_span = tracer.start_span('root-span')
else:
root_span = None
# ideally we should have started a test server and tested with real HTTP
# request, but doing that for https is more difficult, so we mock the
# request sending part.
if urllibver == 'urllib2':
p_do_open = mock.patch(
'urllib2.AbstractHTTPHandler.do_open', return_value=Response()
)
else:
cls = module.AbstractHTTPHandler
p_do_open = mock.patch.object(
cls, 'do_open', return_value=Response()
)
<|code_end|>
using the current file's imports:
from future import standard_library
from tornado.httputil import HTTPHeaders
from opentracing_instrumentation.client_hooks import urllib2 as urllib2_hooks
from opentracing_instrumentation.config import CONFIG
from opentracing_instrumentation.request_context import span_in_context
import mock
import pytest
import six
import urllib2
import urllib.request
and any relevant context from other files:
# Path: opentracing_instrumentation/client_hooks/urllib2.py
# def install_patches():
# def build_handler(base_type, base_cls=None):
# def do_open(self, req, conn):
# def __init__(self, request):
# def add_header(self, key, value):
# def method(self):
# def full_url(self):
# def _headers(self):
# def host_port(self):
# def install_for_module(module, do_open_base=None):
# def http_open(self, req):
# def https_open(self, req):
# class DerivedHandler(base_type):
# class Urllib2RequestWrapper(AbstractRequestWrapper):
# class TracedHTTPHandler(httpBase):
# class TracedHTTPSHandler(httpsBase):
#
# Path: opentracing_instrumentation/config.py
# CONFIG = _Config()
#
# Path: opentracing_instrumentation/request_context.py
# def span_in_context(span):
# """
# Create a context manager that stores the given span in the thread-local
# request context. This function should only be used in single-threaded
# applications like Flask / uWSGI.
#
# ## Usage example in WSGI middleware:
#
# .. code-block:: python
# from opentracing_instrumentation.http_server import WSGIRequestWrapper
# from opentracing_instrumentation.http_server import before_request
# from opentracing_instrumentation import request_context
#
# def create_wsgi_tracing_middleware(other_wsgi):
#
# def wsgi_tracing_middleware(environ, start_response):
# request = WSGIRequestWrapper.from_wsgi_environ(environ)
# span = before_request(request=request, tracer=tracer)
#
# # Wrapper around the real start_response object to log
# # additional information to opentracing Span
# def start_response_wrapper(status, response_headers,
# exc_info=None):
# if exc_info is not None:
# span.log(event='exception', payload=exc_info)
# span.finish()
#
# return start_response(status, response_headers)
#
# with request_context.span_in_context(span):
# return other_wsgi(environ, start_response_wrapper)
#
# return wsgi_tracing_middleware
#
# :param span: OpenTracing Span
# :return:
# Return context manager that wraps the request context.
# """
#
# # Return a no-op Scope if None was specified.
# if span is None:
# return opentracing.Scope(None, None)
#
# return opentracing.tracer.scope_manager.activate(span, False)
. Output only the next line. | with p_do_open, span_in_context(span=root_span): |
Continue the code snippet: <|code_start|># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
SKIP_REASON = 'Postgres is not running or cannot connect'
POSTGRES_CONNECTION_STRING = 'postgresql://postgres@localhost/test'
@pytest.fixture
def engine():
try:
yield create_engine(POSTGRES_CONNECTION_STRING)
except:
pass
@pytest.fixture
def session():
Session = sessionmaker()
Session.configure(bind=engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True)
def patch_postgres():
<|code_end|>
. Use current file imports:
import mock
import psycopg2 as psycopg2_client
import pytest
from psycopg2 import extensions as pg_extensions, sql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import psycopg2
from .sql_common import metadata, User
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/client_hooks/psycopg2.py
# class Psycopg2CursorWrapper(CursorWrapper):
# def execute(self, sql, params=NO_ARG):
# def executemany(self, sql, seq_of_parameters):
# def install_patches():
# def register_type(obj, conn_or_curs=None):
# def quote_ident(string, scope):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
. Output only the next line. | psycopg2.install_patches() |
Given snippet: <|code_start|>def session():
Session = sessionmaker()
Session.configure(bind=engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True)
def patch_postgres():
psycopg2.install_patches()
@pytest.fixture()
def connection():
return psycopg2_client.connect(POSTGRES_CONNECTION_STRING)
def is_postgres_running():
try:
with psycopg2_client.connect(POSTGRES_CONNECTION_STRING):
pass
return True
except:
return False
@pytest.mark.skipif(not is_postgres_running(), reason=SKIP_REASON)
def test_db(tracer, engine, session):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import mock
import psycopg2 as psycopg2_client
import pytest
from psycopg2 import extensions as pg_extensions, sql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import psycopg2
from .sql_common import metadata, User
and context:
# Path: opentracing_instrumentation/client_hooks/psycopg2.py
# class Psycopg2CursorWrapper(CursorWrapper):
# def execute(self, sql, params=NO_ARG):
# def executemany(self, sql, seq_of_parameters):
# def install_patches():
# def register_type(obj, conn_or_curs=None):
# def quote_ident(string, scope):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
which might include code, classes, or functions. Output only the next line. | metadata.create_all(engine) |
Using the snippet: <|code_start|> Session = sessionmaker()
Session.configure(bind=engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True)
def patch_postgres():
psycopg2.install_patches()
@pytest.fixture()
def connection():
return psycopg2_client.connect(POSTGRES_CONNECTION_STRING)
def is_postgres_running():
try:
with psycopg2_client.connect(POSTGRES_CONNECTION_STRING):
pass
return True
except:
return False
@pytest.mark.skipif(not is_postgres_running(), reason=SKIP_REASON)
def test_db(tracer, engine, session):
metadata.create_all(engine)
<|code_end|>
, determine the next line of code. You have imports:
import mock
import psycopg2 as psycopg2_client
import pytest
from psycopg2 import extensions as pg_extensions, sql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import psycopg2
from .sql_common import metadata, User
and context (class names, function names, or code) available:
# Path: opentracing_instrumentation/client_hooks/psycopg2.py
# class Psycopg2CursorWrapper(CursorWrapper):
# def execute(self, sql, params=NO_ARG):
# def executemany(self, sql, seq_of_parameters):
# def install_patches():
# def register_type(obj, conn_or_curs=None):
# def quote_ident(string, scope):
#
# Path: tests/opentracing_instrumentation/sql_common.py
# class User(object):
# def __init__(self, name, fullname, password):
. Output only the next line. | user1 = User(name='user1', fullname='User 1', password='password') |
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
VAL = b'opentracing is fun and easy!'
@pytest.yield_fixture(autouse=True, scope='module')
def patch_redis():
<|code_end|>
, predict the next line using imports from the current file:
from builtins import object
from opentracing.ext import tags
from opentracing_instrumentation.client_hooks import strict_redis
import redis
import random
import opentracing
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/client_hooks/strict_redis.py
# IPV4_RE = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
# METHOD_NAMES = ['execute_command', 'get', 'set', 'setex', 'setnx']
# ORIG_METHODS = {}
# def install_patches():
# def peer_tags(self):
# def get(self, name, **kwargs):
# def set(self, name, value, ex=None, px=None, nx=False, xx=False, **kwargs):
# def setex(self, name, time, value, **kwargs):
# def setnx(self, name, value, **kwargs):
# def execute_command(self, cmd, *args, **kwargs):
# def reset_patches():
. Output only the next line. | strict_redis.install_patches() |
Predict the next line after this snippet: <|code_start|>
CELERY_3 = celery_module.__version__.split('.', 1)[0] == '3'
@pytest.fixture(autouse=True, scope='module')
def patch_celery():
<|code_end|>
using the current file's imports:
import celery as celery_module
import mock
import pytest
from celery import Celery
from celery.signals import (
before_task_publish, after_task_publish, task_postrun
)
from celery.states import SUCCESS, FAILURE
from celery.worker import state as celery_worker_state
from kombu import Connection
from opentracing.ext import tags
from opentracing_instrumentation.client_hooks import celery as celery_hooks
and any relevant context from other files:
# Path: opentracing_instrumentation/client_hooks/celery.py
# def task_apply_async_wrapper(task, args=None, kwargs=None, **other_kwargs):
# def set_common_tags(span, task, span_kind):
# def before_task_publish_handler(headers, **kwargs):
# def task_prerun_handler(task, task_id, **kwargs):
# def finish_current_span(task, exc_type=None, exc_val=None, exc_tb=None):
# def task_success_handler(sender, **kwargs):
# def task_failure_handler(sender, exception, traceback, **kwargs):
# def _install_patches(self):
# def _reset_patches(self):
# class CeleryPatcher(Patcher):
. Output only the next line. | celery_hooks.install_patches() |
Given the following code snippet before the placeholder: <|code_start|> builder = TracedPatcherBuilder()
builder.patch()
def reset_patchers():
try:
except ImportError:
pass
else:
setattr(
simple.SimpleAsyncHTTPClient,
'fetch_impl',
_SimpleAsyncHTTPClient_fetch_impl,
)
try:
except ImportError:
pass
else:
setattr(
curl.CurlAsyncHTTPClient,
'fetch_impl',
_CurlAsyncHTTPClient_fetch_impl,
)
def traced_fetch_impl(real_fetch_impl):
@functools.wraps(real_fetch_impl)
def new_fetch_impl(self, request, callback):
request_wrapper = TornadoRequestWrapper(request=request)
<|code_end|>
, predict the next line using imports from the current file:
from future import standard_library
from builtins import object
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from opentracing_instrumentation import get_current_span
from ._singleton import singleton
import functools
import logging
import urllib.parse
import tornado.simple_httpclient
import tornado.curl_httpclient
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
. Output only the next line. | span = before_http_request(request=request_wrapper, |
Given the following code snippet before the placeholder: <|code_start|> span.finish()
return callback(response)
real_fetch_impl(self, request, new_callback)
return new_fetch_impl
class TornadoRequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.request = request
self._norm_headers = None
def add_header(self, key, value):
self.request.headers[key] = value
@property
def _headers(self):
if self._norm_headers is None:
if type(self.request.headers) is HTTPHeaders:
self._norm_headers = self.request.headers
else:
self._norm_headers = HTTPHeaders(self.request.headers)
return self._norm_headers
@property
def host_port(self):
res = urllib.parse.urlparse(self.full_url)
if res:
<|code_end|>
, predict the next line using imports from the current file:
from future import standard_library
from builtins import object
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from opentracing_instrumentation import get_current_span
from ._singleton import singleton
import functools
import logging
import urllib.parse
import tornado.simple_httpclient
import tornado.curl_httpclient
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
. Output only the next line. | return split_host_and_port(host_string=res.netloc, |
Given the code snippet: <|code_start|> builder.patch()
def reset_patchers():
try:
except ImportError:
pass
else:
setattr(
simple.SimpleAsyncHTTPClient,
'fetch_impl',
_SimpleAsyncHTTPClient_fetch_impl,
)
try:
except ImportError:
pass
else:
setattr(
curl.CurlAsyncHTTPClient,
'fetch_impl',
_CurlAsyncHTTPClient_fetch_impl,
)
def traced_fetch_impl(real_fetch_impl):
@functools.wraps(real_fetch_impl)
def new_fetch_impl(self, request, callback):
request_wrapper = TornadoRequestWrapper(request=request)
span = before_http_request(request=request_wrapper,
<|code_end|>
, generate the next line using the imports in this file:
from future import standard_library
from builtins import object
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from opentracing_instrumentation import get_current_span
from ._singleton import singleton
import functools
import logging
import urllib.parse
import tornado.simple_httpclient
import tornado.curl_httpclient
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
and context (functions, classes, or occasionally code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
. Output only the next line. | current_span_extractor=get_current_span) |
Based on the snippet: <|code_start|> for obj, attr, repl in self._tornado():
self._build_patcher(obj, attr, repl)
@staticmethod
def _build_patcher(obj, patched_attribute, replacement):
if not hasattr(obj, patched_attribute):
return
return setattr(obj, patched_attribute, replacement)
@staticmethod
def _tornado():
try:
except ImportError:
pass
else:
new_fetch_impl = traced_fetch_impl(
_SimpleAsyncHTTPClient_fetch_impl
)
yield simple.SimpleAsyncHTTPClient, 'fetch_impl', new_fetch_impl
try:
except ImportError:
pass
else:
new_fetch_impl = traced_fetch_impl(
_CurlAsyncHTTPClient_fetch_impl
)
yield curl.CurlAsyncHTTPClient, 'fetch_impl', new_fetch_impl
<|code_end|>
, predict the immediate next line with the help of imports:
from future import standard_library
from builtins import object
from tornado.httputil import HTTPHeaders
from opentracing.ext import tags
from opentracing_instrumentation.http_client import AbstractRequestWrapper
from opentracing_instrumentation.http_client import before_http_request
from opentracing_instrumentation.http_client import split_host_and_port
from opentracing_instrumentation import get_current_span
from ._singleton import singleton
import functools
import logging
import urllib.parse
import tornado.simple_httpclient
import tornado.curl_httpclient
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
import tornado.simple_httpclient as simple
import tornado.curl_httpclient as curl
and context (classes, functions, sometimes code) from other files:
# Path: opentracing_instrumentation/http_client.py
# class AbstractRequestWrapper(object):
#
# def add_header(self, key, value):
# pass
#
# @property
# def _headers(self):
# return {}
#
# @property
# def host_port(self):
# return None, None
#
# @property
# def service_name(self):
# for header in CONFIG.callee_name_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return value
# return None
#
# @property
# def operation(self):
# for header in CONFIG.callee_endpoint_headers:
# value = self._headers.get(header, None)
# if value is not None:
# return '%s:%s' % (self.method, value)
# return self.method
#
# @property
# def method(self):
# raise NotImplementedError
#
# @property
# def full_url(self):
# raise NotImplementedError
#
# Path: opentracing_instrumentation/http_client.py
# def before_http_request(request, current_span_extractor):
# """
# A hook to be executed before HTTP request is executed.
# It returns a Span object that can be used as a context manager around
# the actual HTTP call implementation, or in case of async callback,
# it needs its `finish()` method to be called explicitly.
#
# :param request: request must match API defined by AbstractRequestWrapper
# :param current_span_extractor: function that extracts current span
# from some context
# :return: returns child tracing span encapsulating this request
# """
#
# span = utils.start_child_span(
# operation_name=request.operation,
# parent=current_span_extractor()
# )
#
# span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
# span.set_tag(tags.HTTP_URL, request.full_url)
#
# service_name = request.service_name
# host, port = request.host_port
# if service_name:
# span.set_tag(tags.PEER_SERVICE, service_name)
# if host:
# span.set_tag(tags.PEER_HOST_IPV4, host)
# if port:
# span.set_tag(tags.PEER_PORT, port)
#
# # fire interceptors
# for interceptor in ClientInterceptors.get_interceptors():
# interceptor.process(request=request, span=span)
#
# try:
# carrier = {}
# opentracing.tracer.inject(span_context=span.context,
# format=Format.HTTP_HEADERS,
# carrier=carrier)
# for key, value in six.iteritems(carrier):
# request.add_header(key, value)
# except opentracing.UnsupportedFormatException:
# pass
#
# return span
#
# Path: opentracing_instrumentation/http_client.py
# def split_host_and_port(host_string, scheme='http'):
# is_secure = True if scheme == 'https' else False
# m = HOST_PORT_RE.match(host_string)
# if m:
# host, port = m.groups()
# return host, int(port)
# elif is_secure is None:
# return host_string, None
# elif is_secure:
# return host_string, 443
# else:
# return host_string, 80
#
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# Path: opentracing_instrumentation/client_hooks/_singleton.py
# def singleton(func):
# """
# This decorator allows you to make sure that a function is called once and
# only once. Note that recursive functions will still work.
#
# WARNING: Not thread-safe!!!
# """
#
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if wrapper.__call_state__ == CALLED:
# return
# ret = func(*args, **kwargs)
# wrapper.__call_state__ = CALLED
# return ret
#
# def reset():
# wrapper.__call_state__ = NOT_CALLED
#
# wrapper.reset = reset
# reset()
#
# # save original func to be able to patch and restore multiple times from
# # unit tests
# wrapper.__original_func = func
# return wrapper
. Output only the next line. | @singleton |
Continue the code snippet: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def test__request_context_is_thread_safe(thread_safe_tracer):
"""
Port of Uber's internal tornado-extras (by @sema).
This test illustrates that the default Tornado's StackContext
is not thread-safe. The test can be made to fail by commenting
out these lines in the ThreadSafeStackContext constructor:
if hasattr(self, 'contexts'):
# only patch if context exists
self.contexts = LocalContexts()
"""
num_iterations = 1000
num_workers = 10
exception = [0]
def async_task():
time.sleep(0.001)
<|code_end|>
. Use current file imports:
import time
from threading import Thread
from tornado.stack_context import wrap
from opentracing_instrumentation.request_context import (
get_current_span, span_in_stack_context,
)
and context (classes, functions, or code) from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
. Output only the next line. | assert get_current_span() is not None |
Next line prediction: <|code_start|> This test illustrates that the default Tornado's StackContext
is not thread-safe. The test can be made to fail by commenting
out these lines in the ThreadSafeStackContext constructor:
if hasattr(self, 'contexts'):
# only patch if context exists
self.contexts = LocalContexts()
"""
num_iterations = 1000
num_workers = 10
exception = [0]
def async_task():
time.sleep(0.001)
assert get_current_span() is not None
class Worker(Thread):
def __init__(self, fn):
super(Worker, self).__init__()
self.fn = fn
def run(self):
try:
for _ in range(0, num_iterations):
self.fn()
except Exception as e:
exception[0] = e
raise
<|code_end|>
. Use current file imports:
(import time
from threading import Thread
from tornado.stack_context import wrap
from opentracing_instrumentation.request_context import (
get_current_span, span_in_stack_context,
))
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
. Output only the next line. | with span_in_stack_context(span='span'): |
Predict the next line after this snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
@patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager()))
class TornadoTraceContextTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
span1 = 'Bender is great!'
span2 = 'Fry is dumb!'
@gen.coroutine
def check(span_to_check):
<|code_end|>
using the current file's imports:
import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing_instrumentation.request_context import (
get_current_span,
span_in_stack_context,
RequestContext,
RequestContextManager,
)
from mock import patch
from tornado import gen
from tornado import stack_context
from tornado.testing import AsyncTestCase, gen_test
and any relevant context from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# class RequestContext(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# RequestContext represents the context of a request being executed.
#
# Useful when a service needs to make downstream calls to other services
# and requires access to some aspects of the original request, such as
# tracing information.
#
# It is designed to hold a reference to the current OpenTracing Span,
# but the class can be extended to store more information.
# """
#
# __slots__ = ('span', )
#
# def __init__(self, span):
# self.span = span
#
# class RequestContextManager(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# A context manager that saves RequestContext in thread-local state.
#
# Intended for use with ThreadSafeStackContext (a thread-safe
# replacement for Tornado's StackContext) or as context manager
# in a WSGI middleware.
# """
#
# _state = threading.local()
# _state.context = None
#
# @classmethod
# def current_context(cls):
# """Get the current request context.
#
# :rtype: opentracing_instrumentation.RequestContext
# :returns: The current request context, or None.
# """
# return getattr(cls._state, 'context', None)
#
# def __init__(self, context=None, span=None):
# # normally we want the context parameter, but for backwards
# # compatibility we make it optional and allow span as well
# if span:
# self._context = RequestContext(span=span)
# elif isinstance(context, opentracing.Span):
# self._context = RequestContext(span=context)
# else:
# self._context = context
#
# def __enter__(self):
# self._prev_context = self.__class__.current_context()
# self.__class__._state.context = self._context
# return self._context
#
# def __exit__(self, *_):
# self.__class__._state.context = self._prev_context
# self._prev_context = None
# return False
. Output only the next line. | assert get_current_span() == span_to_check |
Next line prediction: <|code_start|> @gen_test
def test_request_context_manager_backwards_compatible(self):
span = opentracing.tracer.start_span(operation_name='test')
@gen.coroutine
def check():
assert get_current_span() == span
# Bypass ScopeManager/span_in_stack_context() and use
# RequestContextManager directly.
def run_coroutine(span, coro):
def mgr():
return RequestContextManager(span)
with stack_context.StackContext(mgr):
return coro()
yield run_coroutine(span, check)
def run_coroutine_with_span(span, coro, *args, **kwargs):
"""Wrap the execution of a Tornado coroutine func in a tracing span.
This makes the span available through the get_current_span() function.
:param span: The tracing span to expose.
:param coro: Co-routine to execute in the scope of tracing span.
:param args: Positional args to func, if any.
:param kwargs: Keyword args to func, if any.
"""
<|code_end|>
. Use current file imports:
(import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing_instrumentation.request_context import (
get_current_span,
span_in_stack_context,
RequestContext,
RequestContextManager,
)
from mock import patch
from tornado import gen
from tornado import stack_context
from tornado.testing import AsyncTestCase, gen_test)
and context including class names, function names, or small code snippets from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# class RequestContext(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# RequestContext represents the context of a request being executed.
#
# Useful when a service needs to make downstream calls to other services
# and requires access to some aspects of the original request, such as
# tracing information.
#
# It is designed to hold a reference to the current OpenTracing Span,
# but the class can be extended to store more information.
# """
#
# __slots__ = ('span', )
#
# def __init__(self, span):
# self.span = span
#
# class RequestContextManager(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# A context manager that saves RequestContext in thread-local state.
#
# Intended for use with ThreadSafeStackContext (a thread-safe
# replacement for Tornado's StackContext) or as context manager
# in a WSGI middleware.
# """
#
# _state = threading.local()
# _state.context = None
#
# @classmethod
# def current_context(cls):
# """Get the current request context.
#
# :rtype: opentracing_instrumentation.RequestContext
# :returns: The current request context, or None.
# """
# return getattr(cls._state, 'context', None)
#
# def __init__(self, context=None, span=None):
# # normally we want the context parameter, but for backwards
# # compatibility we make it optional and allow span as well
# if span:
# self._context = RequestContext(span=span)
# elif isinstance(context, opentracing.Span):
# self._context = RequestContext(span=context)
# else:
# self._context = context
#
# def __enter__(self):
# self._prev_context = self.__class__.current_context()
# self.__class__._state.context = self._context
# return self._context
#
# def __exit__(self, *_):
# self.__class__._state.context = self._prev_context
# self._prev_context = None
# return False
. Output only the next line. | with span_in_stack_context(span): |
Given snippet: <|code_start|>
@patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager()))
class TornadoTraceContextTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
span1 = 'Bender is great!'
span2 = 'Fry is dumb!'
@gen.coroutine
def check(span_to_check):
assert get_current_span() == span_to_check
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span1, check, span2)
@gen.coroutine
def nested(nested_span_to_check, span_to_check):
yield run_coroutine_with_span(span1, check, nested_span_to_check)
assert get_current_span() == span_to_check
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span2, nested, span1, span1)
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span2, nested, span2, span2)
# successful case
yield run_coroutine_with_span(span2, nested, span1, span2)
def test_no_span(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing_instrumentation.request_context import (
get_current_span,
span_in_stack_context,
RequestContext,
RequestContextManager,
)
from mock import patch
from tornado import gen
from tornado import stack_context
from tornado.testing import AsyncTestCase, gen_test
and context:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# class RequestContext(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# RequestContext represents the context of a request being executed.
#
# Useful when a service needs to make downstream calls to other services
# and requires access to some aspects of the original request, such as
# tracing information.
#
# It is designed to hold a reference to the current OpenTracing Span,
# but the class can be extended to store more information.
# """
#
# __slots__ = ('span', )
#
# def __init__(self, span):
# self.span = span
#
# class RequestContextManager(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# A context manager that saves RequestContext in thread-local state.
#
# Intended for use with ThreadSafeStackContext (a thread-safe
# replacement for Tornado's StackContext) or as context manager
# in a WSGI middleware.
# """
#
# _state = threading.local()
# _state.context = None
#
# @classmethod
# def current_context(cls):
# """Get the current request context.
#
# :rtype: opentracing_instrumentation.RequestContext
# :returns: The current request context, or None.
# """
# return getattr(cls._state, 'context', None)
#
# def __init__(self, context=None, span=None):
# # normally we want the context parameter, but for backwards
# # compatibility we make it optional and allow span as well
# if span:
# self._context = RequestContext(span=span)
# elif isinstance(context, opentracing.Span):
# self._context = RequestContext(span=context)
# else:
# self._context = context
#
# def __enter__(self):
# self._prev_context = self.__class__.current_context()
# self.__class__._state.context = self._context
# return self._context
#
# def __exit__(self, *_):
# self.__class__._state.context = self._prev_context
# self._prev_context = None
# return False
which might include code, classes, or functions. Output only the next line. | ctx = RequestContextManager(context=RequestContext(span='x')) |
Given the following code snippet before the placeholder: <|code_start|>
@patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager()))
class TornadoTraceContextTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
span1 = 'Bender is great!'
span2 = 'Fry is dumb!'
@gen.coroutine
def check(span_to_check):
assert get_current_span() == span_to_check
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span1, check, span2)
@gen.coroutine
def nested(nested_span_to_check, span_to_check):
yield run_coroutine_with_span(span1, check, nested_span_to_check)
assert get_current_span() == span_to_check
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span2, nested, span1, span1)
with self.assertRaises(Exception): # passing mismatching spans
yield run_coroutine_with_span(span2, nested, span2, span2)
# successful case
yield run_coroutine_with_span(span2, nested, span1, span2)
def test_no_span(self):
<|code_end|>
, predict the next line using imports from the current file:
import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing_instrumentation.request_context import (
get_current_span,
span_in_stack_context,
RequestContext,
RequestContextManager,
)
from mock import patch
from tornado import gen
from tornado import stack_context
from tornado.testing import AsyncTestCase, gen_test
and context including class names, function names, and sometimes code from other files:
# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
# """
# Access current request context and extract current Span from it.
# :return:
# Return current span associated with the current request context.
# If no request context is present in thread local, or the context
# has no span, return None.
# """
# # Check against the old, ScopeManager-less implementation,
# # for backwards compatibility.
# context = RequestContextManager.current_context()
# if context is not None:
# return context.span
#
# active = opentracing.tracer.scope_manager.active
# return active.span if active else None
#
# def span_in_stack_context(span):
# """
# Create Tornado's StackContext that stores the given span in the
# thread-local request context. This function is intended for use
# in Tornado applications based on IOLoop, although will work fine
# in single-threaded apps like Flask, albeit with more overhead.
#
# ## Usage example in Tornado application
#
# Suppose you have a method `handle_request(request)` in the http server.
# Instead of calling it directly, use a wrapper:
#
# .. code-block:: python
#
# from opentracing_instrumentation import request_context
#
# @tornado.gen.coroutine
# def handle_request_wrapper(request, actual_handler, *args, **kwargs)
#
# request_wrapper = TornadoRequestWrapper(request=request)
# span = http_server.before_request(request=request_wrapper)
#
# with request_context.span_in_stack_context(span):
# return actual_handler(*args, **kwargs)
#
# :param span:
# :return:
# Return StackContext that wraps the request context.
# """
#
# if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
# raise RuntimeError('scope_manager is not TornadoScopeManager')
#
# # Enter the newly created stack context so we have
# # storage available for Span activation.
# context = tracer_stack_context()
# entered_context = _TracerEnteredStackContext(context)
#
# if span is None:
# return entered_context
#
# opentracing.tracer.scope_manager.activate(span, False)
# assert opentracing.tracer.active_span is not None
# assert opentracing.tracer.active_span is span
#
# return entered_context
#
# class RequestContext(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# RequestContext represents the context of a request being executed.
#
# Useful when a service needs to make downstream calls to other services
# and requires access to some aspects of the original request, such as
# tracing information.
#
# It is designed to hold a reference to the current OpenTracing Span,
# but the class can be extended to store more information.
# """
#
# __slots__ = ('span', )
#
# def __init__(self, span):
# self.span = span
#
# class RequestContextManager(object):
# """
# DEPRECATED, use either span_in_context() or span_in_stack_context()
# instead.
#
# A context manager that saves RequestContext in thread-local state.
#
# Intended for use with ThreadSafeStackContext (a thread-safe
# replacement for Tornado's StackContext) or as context manager
# in a WSGI middleware.
# """
#
# _state = threading.local()
# _state.context = None
#
# @classmethod
# def current_context(cls):
# """Get the current request context.
#
# :rtype: opentracing_instrumentation.RequestContext
# :returns: The current request context, or None.
# """
# return getattr(cls._state, 'context', None)
#
# def __init__(self, context=None, span=None):
# # normally we want the context parameter, but for backwards
# # compatibility we make it optional and allow span as well
# if span:
# self._context = RequestContext(span=span)
# elif isinstance(context, opentracing.Span):
# self._context = RequestContext(span=context)
# else:
# self._context = context
#
# def __enter__(self):
# self._prev_context = self.__class__.current_context()
# self.__class__._state.context = self._context
# return self._context
#
# def __exit__(self, *_):
# self.__class__._state.context = self._prev_context
# self._prev_context = None
# return False
. Output only the next line. | ctx = RequestContextManager(context=RequestContext(span='x')) |
Using the snippet: <|code_start|>parser.add_option("-w", "--width", action="store", dest="image_width", type="int", help="image width in pixels (default %default)")
parser.add_option("-h", "--height", action="store", dest="image_height", type="int", help="image height in pixels (default %default)")
parser.add_option("-f", "--fft", action="store", dest="fft_size", type="int", help="fft size, power of 2 for increased performance (default %default)")
parser.add_option("-p", "--profile", action="store_true", dest="profile", help="run profiler and output profiling information")
parser.set_defaults(output_filename_w=None, output_filename_s=None, image_width=500, image_height=171, fft_size=2048)
(options, args) = parser.parse_args()
if len(args) == 0:
parser.print_help()
parser.error("not enough arguments")
if len(args) > 1 and (options.output_filename_w != None or options.output_filename_s != None):
parser.error("when processing multiple files you can't define the output filename!")
'''
def progress_callback(percentage):
sys.stdout.write(str(percentage) + "% ")
sys.stdout.flush()
# process all files so the user can use wildcards like *.wav
def genimages(input_file, output_file_w, output_file_s, output_file_m, options):
args = (input_file, output_file_w, output_file_s, output_file_m, options.image_width, options.image_height,
options.fft_size, progress_callback, options.f_min, options.f_max, options.scale_exp, options.pallete)
print("processing file %s:\n\t" % input_file, end="")
try:
<|code_end|>
, determine the next line of code. You have imports:
import sys
from compmusic.extractors.imagelib.MelSpectrogramImage import create_wave_images
from processing import AudioProcessingException
and context (class names, function names, or code) available:
# Path: compmusic/extractors/imagelib/MelSpectrogramImage.py
# def create_wave_images(input_filename, output_filename_w, output_filename_s, output_filename_m, image_width,
# image_height, fft_size, progress_callback=None, f_min=None, f_max=None, scale_exp=None,
# pallete=None):
# """
# Utility function for creating both wavefile and spectrum images from an audio input file.
# """
# numMelBands = 26 # as in htk
# processor = AudioProcessor(input_filename, fft_size, np.hanning)
# inv_processor = InvMFCCAudioProcessor(input_filename, fft_size, numMelBands)
# samples_per_pixel = processor.audio_file.nframes / float(image_width)
#
# waveform = WaveformImage(image_width, image_height)
# spectrogram = SpectrogramImage(image_width, image_height, fft_size, f_min, f_max, scale_exp, pallete)
# mel_spectrogram = MelSpectrogramImage(image_width, image_height, scale_exp, pallete, numMelBands)
#
# for x in range(image_width):
#
# if image_width >= 10:
# if progress_callback and x % (image_width / 10) == 0:
# progress_callback((x * 100) / image_width)
#
# seek_point = int(x * samples_per_pixel)
# next_seek_point = int((x + 1) * samples_per_pixel)
#
# (spectral_centroid, db_spectrum) = processor.spectral_centroid(seek_point)
# peaks = processor.peaks(seek_point, next_seek_point)
#
# inv_mfcc_spectrum = inv_processor.compute_inv_mfcc(
# seek_point) # inv MFCC computation results in a mel spectrogram
# waveform.draw_peaks(x, peaks, spectral_centroid)
# spectrogram.draw_spectrum(x, db_spectrum)
# mel_spectrogram.draw_spectrum(x, inv_mfcc_spectrum)
#
# if progress_callback:
# progress_callback(100)
#
# waveform.save(output_filename_w)
# spectrogram.save(output_filename_s)
# mel_spectrogram.save(output_filename_m)
. Output only the next line. | create_wave_images(*args) |
Based on the snippet: <|code_start|>
class MakamTagTest(unittest.TestCase):
def test_usul(self):
t = "usul: something"
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from compmusic import tags
and context (classes, functions, sometimes code) from other files:
# Path: compmusic/tags.py
# def has_carnatic_form(tag):
# def has_raaga(tag):
# def has_taala(tag):
# def has_raag(tag):
# def has_taal(tag):
# def has_laya(tag):
# def has_section(tag):
# def has_makam(tag):
# def has_usul(tag):
# def has_makam_form(tag):
# def has_hindustani_form(tag):
# def parse_raaga(raaga):
# def parse_taala(taala):
# def parse_makam(makam):
# def _parse_num_and_value(expression, target):
# def parse_usul(usul):
# def parse_makam_form(form):
# def parse_raag(raag):
# def parse_taal(taal):
# def parse_hindustani_form(form):
# def parse_carnatic_form(form):
# def parse_laya(laya):
# def group_makam_tags(makams, forms, usuls):
. Output only the next line. | self.assertEqual(True, tags.has_usul(t)) |
Here is a snippet: <|code_start|> if not isinstance(collections, list):
raise ValueError('`collections` must be a list')
COLLECTIONS = collections
def _get_collections():
extra_headers = None
if COLLECTIONS:
extra_headers = {}
extra_headers['Dunya-Collection'] = ','.join(COLLECTIONS)
return extra_headers
def get_recordings(recording_detail=False):
""" Get a list of carnatic recordings in the database.
This function will automatically page through API results.
:param recording_detail: if True, return full details for each recording like :func:`get_recording`
:returns: A list of dictionaries containing recording information::
{"mbid": MusicBrainz recording ID, "title": Title of the recording}
For additional information about each recording use :func:`get_recording`.
"""
extra_headers = _get_collections()
args = {}
if recording_detail:
args['detail'] = '1'
<|code_end|>
. Write the next line using the current file imports:
import errno
import logging
import os
import compmusic.dunya.docserver
from compmusic.dunya import conn
and context from other files:
# Path: compmusic/dunya/conn.py
# HOSTNAME = "https://dunya.compmusic.upf.edu"
# TOKEN = None
# HOSTNAME = hostname
# TOKEN = token
# class HTTPError(Exception):
# class ConnectionError(Exception):
# def set_hostname(hostname):
# def set_token(token):
# def _get_paged_json(path, **kwargs):
# def _dunya_url_query(url, extra_headers=None):
# def _dunya_post(url, data=None, files=None):
# def _make_url(path, **kwargs):
# def _dunya_query_json(path, **kwargs):
# def _dunya_query_file(path, **kwargs):
, which may include functions, classes, or code. Output only the next line. | return conn._get_paged_json("api/carnatic/recording", extra_headers=extra_headers, **args) |
Given the following code snippet before the placeholder: <|code_start|> return localscore
##########################################################################################
def hanning(n):
window = 0.5 - 0.5 * np.cos(2 * math.pi * np.arange(n) / (n - 1));
return window
###########################################################################################
def normMax(y, alpha=0):
z = y.copy()
z = z / (np.max(np.abs(y)) + alpha);
return z
###########################################################################################
def normalizeFeature(featMat, normP):
''' Assuming that each column is a feature vector, the normalization is along the columns
'''
featNorm = np.zeros(featMat.shape).astype(complex)
T = featMat.shape[1]
for t in range(T):
n = np.linalg.norm(featMat[:, t], normP)
featNorm[:, t] = featMat[:, t] / n
return featNorm
###########################################################################################
def compute_fourierCoefficients(s, win, noverlap, f, fs):
<|code_end|>
, predict the next line using imports from the current file:
import math
import essentia as es
import essentia.standard as ess
import numpy as np
import scipy.stats as scistats
import parameters as params
from compmusic.extractors import log
and context including class names, function names, and sometimes code from other files:
# Path: compmusic/extractors/log.py
# class ExtractorAdapter(logging.LoggerAdapter):
# def set_documentid(self, docid):
# def set_sourcefileid(self, sfid):
# def process(self, msg, kwargs):
# def get_logger(modulename, moduleversion=None):
. Output only the next line. | logger = log.get_logger("rhythm") |
Continue the code snippet: <|code_start|> COLLECTIONS = collections
def _get_collections():
extra_headers = None
if COLLECTIONS:
extra_headers = {}
extra_headers['Dunya-Collection'] = ','.join(COLLECTIONS)
return extra_headers
def get_recordings(recording_detail=False):
""" Get a list of jingju recordings in the database.
This function will automatically page through API results.
:param recording_detail: if True, return full details for each recording like :func:`get_recording`
returns: A list of dictionaries containing recording information::
{"mbid": Musicbrainz recording id,
"title": Title of the recording
}
For additional information about each recording use :func:`get_recording`.
"""
extra_headers = _get_collections()
args = {}
if recording_detail:
args['detail'] = '1'
<|code_end|>
. Use current file imports:
import errno
import logging
import os
import compmusic.dunya.docserver
from requests.exceptions import HTTPError
from compmusic.dunya import conn
and context (classes, functions, or code) from other files:
# Path: compmusic/dunya/conn.py
# HOSTNAME = "https://dunya.compmusic.upf.edu"
# TOKEN = None
# HOSTNAME = hostname
# TOKEN = token
# class HTTPError(Exception):
# class ConnectionError(Exception):
# def set_hostname(hostname):
# def set_token(token):
# def _get_paged_json(path, **kwargs):
# def _dunya_url_query(url, extra_headers=None):
# def _dunya_post(url, data=None, files=None):
# def _make_url(path, **kwargs):
# def _dunya_query_json(path, **kwargs):
# def _dunya_query_file(path, **kwargs):
. Output only the next line. | return conn._get_paged_json("api/jingju/recording", extra_headers=extra_headers, **args) |
Predict the next line for this snippet: <|code_start|>
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
<|code_end|>
with the help of current file imports:
import unittest
from compmusic.dunya.conn import _make_url
and context from other files:
# Path: compmusic/dunya/conn.py
# def _make_url(path, **kwargs):
# if "://" in HOSTNAME:
# protocol, hostname = HOSTNAME.split("://")
# else:
# protocol = "http"
# hostname = HOSTNAME
#
# if not kwargs:
# kwargs = {}
# for key, value in kwargs.items():
# if isinstance(value, str):
# kwargs[key] = value.encode('utf8')
# url = urllibparse.urlunparse((
# protocol,
# hostname,
# '%s' % path,
# '',
# urllibparse.urlencode(kwargs),
# ''
# ))
# return url
, which may contain function names, class names, or code. Output only the next line. | url = _make_url("path", **params) |
Given snippet: <|code_start|>
mb.set_useragent("Dunya", "0.1")
mb.set_rate_limit(False)
mb.set_hostname("musicbrainz.sb.upf.edu")
MUSICBRAINZ_COLLECTION_CARNATIC = ""
MUSICBRAINZ_COLLECTION_HINDUSTANI = ""
MUSICBRAINZ_COLLECTION_MAKAM = ""
headers = {"User-Agent": "Dunya/0.1 python-musicbrainzngs"}
requests_session = requests.Session()
requests_session.mount('https://musicbrainz.org', HTTPAdapter(max_retries=5))
def ws_ids(xml):
ids = []
tree = etree.fromstring(xml)
count = int(list(list(tree)[0])[2].attrib["count"])
for rel in list(list(list(tree)[0])[2]):
ids.append(rel.attrib["id"])
return (count, ids)
def _get_items_in_collection(collectionid, collectiontype):
items = []
count = 25
offset = 0
while offset < count:
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import musicbrainzngs as mb
import requests
import time
import xml.etree.ElementTree as etree
from requests.adapters import HTTPAdapter
from compmusic.log import log
and context:
# Path: compmusic/log.py
which might include code, classes, or functions. Output only the next line. | log.debug("offset", offset) |
Given the following code snippet before the placeholder: <|code_start|>
class TechGetSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class TechPostSerializer(serializers.ModelSerializer):
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class CommitSerializer(serializers.ModelSerializer):
class Meta:
model = Commit
fields = ['id', 'solution', 'tech', 'posted', 'text', 'url']
class VoteSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context including class names, function names, and sometimes code from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Vote |
Continue the code snippet: <|code_start|> model = Vote
fields = "__all__"
class SolutionGetSerializer(serializers.ModelSerializer):
votes = VoteSerializer(many=True, read_only=True)
commits = CommitSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
class Meta:
model = Solution
fields = ['id', 'description', 'time_required', 'parts_cost',
'problem', 'tech', 'posted', 'score', 'commits',
'votes', 'url']
class SolutionPostSerializer(serializers.ModelSerializer):
class Meta:
model = Solution
fields = ['id', 'description', 'time_required', 'parts_cost',
'problem', 'tech', 'posted', 'score', 'url']
class ProblemGetSerializer(serializers.ModelSerializer):
solutions = SolutionGetSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
system = SystemSerializer(many=False, read_only=True)
class Meta:
<|code_end|>
. Use current file imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context (classes, functions, or code) from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Problem |
Given the code snippet: <|code_start|>
class TechPostSerializer(serializers.ModelSerializer):
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class CommitSerializer(serializers.ModelSerializer):
class Meta:
model = Commit
fields = ['id', 'solution', 'tech', 'posted', 'text', 'url']
class VoteSerializer(serializers.ModelSerializer):
class Meta:
model = Vote
fields = "__all__"
class SolutionGetSerializer(serializers.ModelSerializer):
votes = VoteSerializer(many=True, read_only=True)
commits = CommitSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context (functions, classes, or occasionally code) from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Solution |
Here is a snippet: <|code_start|>class SystemSerializer(serializers.ModelSerializer):
class Meta:
model = System
fields = ['id', 'name', 'url']
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = User
fields = ['id', 'password', 'email', 'username']
read_only_fields = ['is_staff', 'is_superuser', 'is_active',
'date_joined',]
class TechGetSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
<|code_end|>
. Write the next line using the current file imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
, which may include functions, classes, or code. Output only the next line. | model = Tech |
Using the snippet: <|code_start|>class SolutionPostSerializer(serializers.ModelSerializer):
class Meta:
model = Solution
fields = ['id', 'description', 'time_required', 'parts_cost',
'problem', 'tech', 'posted', 'score', 'url']
class ProblemGetSerializer(serializers.ModelSerializer):
solutions = SolutionGetSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
system = SystemSerializer(many=False, read_only=True)
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url', 'solutions']
class ProblemPostSerializer(serializers.ModelSerializer):
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url']
class RatingSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, determine the next line of code. You have imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context (class names, function names, or code) available:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Rating |
Here is a snippet: <|code_start|>
class ProblemGetSerializer(serializers.ModelSerializer):
solutions = SolutionGetSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
system = SystemSerializer(many=False, read_only=True)
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url', 'solutions']
class ProblemPostSerializer(serializers.ModelSerializer):
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url']
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = "__all__"
class BrandSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
. Write the next line using the current file imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
, which may include functions, classes, or code. Output only the next line. | model = Brand |
Given snippet: <|code_start|> fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url', 'solutions']
class ProblemPostSerializer(serializers.ModelSerializer):
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url']
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = "__all__"
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = ['id', 'name', 'url']
class ModelSerializer(serializers.ModelSerializer):
brand = BrandSerializer(many=False, read_only=True)
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
which might include code, classes, or functions. Output only the next line. | model = Model |
Based on the snippet: <|code_start|> return user
class Meta:
model = User
fields = ['id', 'password', 'email', 'username']
read_only_fields = ['is_staff', 'is_superuser', 'is_active',
'date_joined',]
class TechGetSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class TechPostSerializer(serializers.ModelSerializer):
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class CommitSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context (classes, functions, sometimes code) from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Commit |
Based on the snippet: <|code_start|> model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url']
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = "__all__"
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = ['id', 'name', 'url']
class ModelSerializer(serializers.ModelSerializer):
brand = BrandSerializer(many=False, read_only=True)
class Meta:
model = Model
fields = ['id', 'name', 'brand', 'year', 'url']
class NotificationSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from .models import Vote, Problem, Solution, Tech, Rating, System, Brand
from .models import Model, Problem_Model, Commit, Notification
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import login
and context (classes, functions, sometimes code) from other files:
# Path: diag_app/models.py
# class Vote(models.Model):
# tech = models.ForeignKey(Tech)
# solution = models.ForeignKey(Solution, related_name='votes')
# value = models.IntegerField(default=1)
#
# class Problem(models.Model):
# title = models.CharField(max_length=65)
# system = models.ForeignKey(System, related_name='problems')
# description = models.TextField(max_length=500)
# tech = models.ForeignKey(Tech, related_name='problems')
# model = models.ForeignKey(Model)
# posted = models.DateTimeField(auto_now=True)
#
# class Solution(models.Model):
# description = models.TextField(max_length=500)
# time_required = models.FloatField(default=0)
# parts_cost = models.DecimalField(max_digits=6, decimal_places=2)
# problem = models.ForeignKey(Problem, related_name='solutions')
# tech = models.ForeignKey(Tech, related_name='solutions')
# posted = models.DateTimeField(auto_now=True)
# score = models.IntegerField(default=0)
#
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
#
# class Rating(models.Model):
# tech = models.ForeignKey(Tech)
# value = models.IntegerField(default=5)
#
# class System(models.Model):
# name = models.CharField(max_length=25)
#
# class Brand(models.Model):
# name = models.CharField(max_length=25)
#
# def __repr__(self):
# return str(self.name)
#
# Path: diag_app/models.py
# class Model(models.Model):
# name = models.CharField(max_length=40)
# brand = models.ForeignKey(Brand)
# year = models.IntegerField(default=0)
#
# def __repr__(self):
# return str(self.name)
#
# class Problem_Model(models.Model):
# problem = models.ForeignKey(Problem)
# model = models.ForeignKey(Model)
#
# class Commit(models.Model):
# solution = models.ForeignKey(Solution, related_name='commits')
# tech = models.ForeignKey(Tech)
# posted = models.DateTimeField(auto_now=True)
# text = models.TextField(max_length=200)
#
# class Notification(models.Model):
# tech = models.ForeignKey(Tech, related_name='techs')
# message = models.CharField(max_length=20)
# # is this the best way to link notifications to events?
# solution = models.ForeignKey(Solution, related_name='solution',null=True)
# commit = models.ForeignKey(Commit, related_name='commit',null=True)
# posted = models.DateTimeField(auto_now=True)
. Output only the next line. | model = Notification |
Next line prediction: <|code_start|>
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password', 'email']
class TechForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django import forms
from .models import Tech)
and context including class names, function names, or small code snippets from other files:
# Path: diag_app/models.py
# class Tech(models.Model):
# experience = models.IntegerField(default=0)
# job_title = models.CharField(max_length=25)
# shop = models.CharField(max_length=25)
# user = models.OneToOneField(User)
# tech_rating = models.IntegerField(default=0)
. Output only the next line. | model = Tech |
Predict the next line after this snippet: <|code_start|> for chunk in chunks(items, chunk_size):
yield dict(chunk)
def alexa_top_million():
"""Returns an iterable of objects describing the top million domains from Alexa
It turns out this list can be used as a set and held in memory fairly
easily:
domains = frozenset({item["domain"] for item in alexa_top_million()})
if "google.com" in domains:
return u"safe"
However it might be better to stick this in a *real* database local to
each worker, and update it each day. Might as well use the Redis DB we
have lying around. It might be even better to have a BloomFilter before
even bothering to check the DB.
"""
alexa_table = csv.DictReader(
zipfile.ZipFile(
StringIO.StringIO(
requests.get("http://s3.amazonaws.com/alexa-static/top-1m.csv.zip").content
)
).open("top-1m.csv"),
fieldnames=("score", "domain")
)
return {item["domain"]: item["score"] for item in alexa_table}
def update_alexa():
<|code_end|>
using the current file's imports:
import zipfile
import cStringIO as StringIO
import csv
import redis
from urlparse import urlparse
from publicsuffix import PublicSuffixList
from celery import task
from celery.utils.functional import chunks
from malware_crawl.defaults import redis_db, REQUESTS_SESSIONS
and any relevant context from other files:
# Path: malware_crawl/defaults.py
# REQUESTS_SESSIONS = {
# "api": requests.Session(),
# "probe": requests.Session()
# }
. Output only the next line. | pipe = redis_db["master"].pipeline() |
Predict the next line after this snippet: <|code_start|> list.append(to_unicode(e.title))
return list
titleList = []
for url in urlList:
l = rssParse(url)
titleList = titleList + l
return titleList
ASPELL_KEY = "aspell"
def load_aspell():
dump = subprocess.Popen(
['aspell', '-d', 'en', 'dump', 'master'],
stdout=subprocess.PIPE,
)
expand = subprocess.Popen(
['aspell', '-l', 'en', 'expand'],
stdin=dump.stdout,
stdout=subprocess.PIPE,
)
dump.stdout.close()
return expand.communicate()[0].split('\n')
def update_aspell():
word_list = load_aspell()
print len(word_list)
<|code_end|>
using the current file's imports:
import tweepy
import re
import feedparser
import subprocess
import redis
from six.moves import map
from celery import task
from malware_crawl.defaults import redis_db, REQUESTS_SESSIONS
and any relevant context from other files:
# Path: malware_crawl/defaults.py
# REQUESTS_SESSIONS = {
# "api": requests.Session(),
# "probe": requests.Session()
# }
. Output only the next line. | pipe = redis_db["master"].pipeline(use_transaction=True) |
Predict the next line for this snippet: <|code_start|># def route_for_task(self, task, args=None, kwargs=None):
# if task == 'malware_crawl.scan.capture_hpc.chpc_malware_scan':
# return {'queue': 'capturehpc',
# 'routing_key': 'capturehpc.scan'}
# return None
def redis_cache(key_prefix, prepare, request, items):
items = list(map(prepare, items))
unique_items = list(set(items))
total_response = {}
# get all the items that are already in cache
#pipe = redis_db["slave"].pipeline()
#for item in unique_items:
# pipe.get(key_prefix.format(item=item))
cache_misses = set()
# add those items we already know about to the total_response
#for item, cache in zip(unique_items, pipe.execute()):
# if cache is not None:
# total_response[item] = pickle.loads(cache)
# else:
# cache_misses.add(item)
cache_misses = set(unique_items)
# use the given function to collect the missing values
total_response.update(request(cache_misses))
# add to the cache the result from the INTERNET
<|code_end|>
with the help of current file imports:
from datetime import timedelta
from six.moves import zip, map
from celery import task, current_app
from celery.contrib.batches import Batches
from malware_crawl.defaults import redis_db
from django.conf import settings
from malware_crawl.models import CaptureUrl
from malware_crawl.scan.celery_rpc_client import RevertRpcClient
import time
import cPickle as pickle
and context from other files:
# Path: malware_crawl/defaults.py
# REQUESTS_SESSIONS = {
# "api": requests.Session(),
# "probe": requests.Session()
# }
#
# Path: malware_crawl/models.py
# class CaptureUrl(models.Model):
# url_id = models.BigIntegerField(unique=True, primary_key=True)
# url = models.CharField(max_length=6249)
# currentstatus = models.CharField(max_length=3, blank=True)
# lastvisittime = models.CharField(max_length=69, blank=True)
# operation_id = models.IntegerField(null=True, blank=True)
# class Meta:
# db_table = u'url'
, which may contain function names, class names, or code. Output only the next line. | pipe = redis_db["master"].pipeline() |
Continue the code snippet: <|code_start|> cache_length
)
pipe.execute()
return [total_response[item] for item in items]
@task(base=Batches, flush_every=500, flush_interval=((timedelta(minutes=30).seconds, 0.1)[settings.DEBUG]))
def chpc_malware_scan(requests):
sig = lambda url: url
print requests
reponses = chpc_malware_scan_real(
(sig(*request.args, **request.kwargs) for request in requests)
)
# use mark_as_done to manually return response data
for response, request in zip(reponses, requests):
current_app.backend.mark_as_done(request.id, response)
def chpc_malware_scan_real(urls):
def prepare(url):
return url
def request(urls):
total_response = {}
if not urls:
return total_response
<|code_end|>
. Use current file imports:
from datetime import timedelta
from six.moves import zip, map
from celery import task, current_app
from celery.contrib.batches import Batches
from malware_crawl.defaults import redis_db
from django.conf import settings
from malware_crawl.models import CaptureUrl
from malware_crawl.scan.celery_rpc_client import RevertRpcClient
import time
import cPickle as pickle
and context (classes, functions, or code) from other files:
# Path: malware_crawl/defaults.py
# REQUESTS_SESSIONS = {
# "api": requests.Session(),
# "probe": requests.Session()
# }
#
# Path: malware_crawl/models.py
# class CaptureUrl(models.Model):
# url_id = models.BigIntegerField(unique=True, primary_key=True)
# url = models.CharField(max_length=6249)
# currentstatus = models.CharField(max_length=3, blank=True)
# lastvisittime = models.CharField(max_length=69, blank=True)
# operation_id = models.IntegerField(null=True, blank=True)
# class Meta:
# db_table = u'url'
. Output only the next line. | CaptureUrl.objects.using('capture').all().delete() |
Continue the code snippet: <|code_start|>
requests = REQUESTS_SESSIONS["api"]
wot_api_target = "https://api.mywot.com/0.4/public_link_json"
def redis_cache(key_prefix, prepare, request, items):
items = list(map(prepare, items))
unique_items = list(set(items))
total_response = {}
# get all the items that are already in cache
<|code_end|>
. Use current file imports:
from urlparse import urlparse
from datetime import timedelta
from six.moves import zip, map
from six import binary_type
from celery import task, current_app
from celery.contrib.batches import Batches
from malware_crawl.defaults import redis_db, REQUESTS_SESSIONS
from django.conf import settings
import cPickle as pickle
and context (classes, functions, or code) from other files:
# Path: malware_crawl/defaults.py
# REQUESTS_SESSIONS = {
# "api": requests.Session(),
# "probe": requests.Session()
# }
. Output only the next line. | pipe = redis_db["slave"].pipeline() |
Predict the next line after this snippet: <|code_start|>from __future__ import division
_mal_list = []
def read_from_database_to_dict():
"""
Reads the malwares from the database and returns a mal_dict
"""
<|code_end|>
using the current file's imports:
from pebl.util import levenshtein
from malware_crawl.models import Malicouse_sites
import json
import pkgutil
and any relevant context from other files:
# Path: malware_crawl/models.py
# class Malicouse_sites(models.Model):
# """
# The table which is going to be used for classification
# """
# url = models.CharField(max_length=255)
# malware = models.BooleanField()
. Output only the next line. | malwares = Malicouse_sites.objects.all() |
Predict the next line for this snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Hive2DatacatalogCli:
@staticmethod
def run(argv):
args = Hive2DatacatalogCli.__parse_args(argv)
# Enable logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
if args.service_account_path:
os.environ['GOOGLE_APPLICATION_CREDENTIALS']\
= args.service_account_path
<|code_end|>
with the help of current file imports:
import argparse
import logging
import os
import sys
from .sync import datacatalog_synchronizer
and context from other files:
# Path: google-datacatalog-hive-connector/src/google/datacatalog_connectors/hive/sync/datacatalog_synchronizer.py
# class DataCatalogSynchronizer:
# __CLEAN_UP_EVENTS = [
# entities.SyncEvent.DROP_DATABASE, entities.SyncEvent.DROP_TABLE
# ]
# def __init__(self,
# project_id,
# location_id,
# hive_metastore_db_host=None,
# hive_metastore_db_user=None,
# hive_metastore_db_pass=None,
# hive_metastore_db_name=None,
# hive_metastore_db_type=None,
# metadata_sync_event=None,
# enable_monitoring=None):
# def run(self):
# def __ingest_created_or_updated(self, prepared_entries):
# def __after_run(self):
# def __log_entries(self, prepared_entries):
# def __log_metadata(self, metadata):
# def __cleanup_deleted_tables(cls, cleaner, prepared_entries):
# def __cleanup_deleted_databases(cls, cleaner, prepared_entries):
, which may contain function names, class names, or code. Output only the next line. | datacatalog_synchronizer.DataCatalogSynchronizer( |
Next line prediction: <|code_start|>def uuidstr():
return str(uuid.uuid4())
def uuid2int(uuidv):
return uuid.UUID(uuidv).int
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
return "POLYGON ((%s))" % ",".join("%f %f" % item for item in line)
# upload utils
def attempt_upload(table, fields):
for fieldname in table._upload_fieldnames & set(fields):
value = fields[fieldname]
if not (value is None or isinstance(value, string_types)):
<|code_end|>
. Use current file imports:
(import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table)
and context including class names, function names, or small code snippets from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | if not PY2 and isinstance(value, bytes): |
Given the following code snippet before the placeholder: <|code_start|>
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
return "POLYGON ((%s))" % ",".join("%f %f" % item for item in line)
# upload utils
def attempt_upload(table, fields):
for fieldname in table._upload_fieldnames & set(fields):
value = fields[fieldname]
if not (value is None or isinstance(value, string_types)):
if not PY2 and isinstance(value, bytes):
continue
if hasattr(value, "file") and hasattr(value, "filename"):
new_name = table[fieldname].store(value.file, filename=value.filename)
elif isinstance(value, dict):
if "data" in value and "filename" in value:
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | stream = BytesIO(to_bytes(value["data"])) |
Predict the next line after this snippet: <|code_start|>def bar_unescape(item):
item = item.replace("||", "|")
if item.startswith(UNIT_SEPARATOR):
item = item[1:]
if item.endswith(UNIT_SEPARATOR):
item = item[:-1]
return item
def bar_encode(items):
return "|%s|" % "|".join(bar_escape(item) for item in items if str(item).strip())
def bar_decode_integer(value):
long = integer_types[-1]
if not hasattr(value, "split") and hasattr(value, "read"):
value = value.read()
return [long(x) for x in value.split("|") if x.strip()]
def bar_decode_string(value):
return [bar_unescape(x) for x in re.split(REGEX_UNPACK, value[1:-1]) if x.strip()]
def archive_record(qset, fs, archive_table, current_record):
tablenames = qset.db._adapter.tables(qset.query)
if len(tablenames) != 1:
raise RuntimeError("cannot update join")
for row in qset.select():
fields = archive_table._filter_fields(row)
<|code_end|>
using the current file's imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and any relevant context from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | for k, v in iteritems(fs): |
Given the following code snippet before the placeholder: <|code_start|> raise ValueError("Name conflict in table list: %s" % key)
# Merge
big.update(small)
ret = big
return ret
def bar_escape(item):
item = str(item).replace("|", "||")
if item.startswith("||"):
item = "%s%s" % (UNIT_SEPARATOR, item)
if item.endswith("||"):
item = "%s%s" % (item, UNIT_SEPARATOR)
return item
def bar_unescape(item):
item = item.replace("||", "|")
if item.startswith(UNIT_SEPARATOR):
item = item[1:]
if item.endswith(UNIT_SEPARATOR):
item = item[:-1]
return item
def bar_encode(items):
return "|%s|" % "|".join(bar_escape(item) for item in items if str(item).strip())
def bar_decode_integer(value):
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | long = integer_types[-1] |
Next line prediction: <|code_start|>
def uuidstr():
return str(uuid.uuid4())
def uuid2int(uuidv):
return uuid.UUID(uuidv).int
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
return "POLYGON ((%s))" % ",".join("%f %f" % item for item in line)
# upload utils
def attempt_upload(table, fields):
for fieldname in table._upload_fieldnames & set(fields):
value = fields[fieldname]
<|code_end|>
. Use current file imports:
(import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table)
and context including class names, function names, or small code snippets from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | if not (value is None or isinstance(value, string_types)): |
Given the code snippet: <|code_start|>
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
return "POLYGON ((%s))" % ",".join("%f %f" % item for item in line)
# upload utils
def attempt_upload(table, fields):
for fieldname in table._upload_fieldnames & set(fields):
value = fields[fieldname]
if not (value is None or isinstance(value, string_types)):
if not PY2 and isinstance(value, bytes):
continue
if hasattr(value, "file") and hasattr(value, "filename"):
new_name = table[fieldname].store(value.file, filename=value.filename)
elif isinstance(value, dict):
if "data" in value and "filename" in value:
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (functions, classes, or occasionally code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | stream = BytesIO(to_bytes(value["data"])) |
Given the following code snippet before the placeholder: <|code_start|> # Explicitly add compute upload fields (ex: thumbnail)
fields += [f for f in table.fields if table[f].compute is not None]
else:
fields = table.fields
fields = [
f
for f in fields
if table[f].type == "upload"
and table[f].uploadfield == True
and table[f].autodelete
]
if not fields:
return False
for record in dbset.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fieldname, None)
if not oldname:
continue
if (
upload_fields
and fieldname in upload_fields
and oldname == upload_fields[fieldname]
):
continue
if field.custom_delete:
field.custom_delete(oldname)
else:
uploadfolder = field.uploadfolder
if not uploadfolder:
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | uploadfolder = pjoin(dbset.db._adapter.folder, "..", "uploads") |
Given the following code snippet before the placeholder: <|code_start|> and table[f].autodelete
]
if not fields:
return False
for record in dbset.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fieldname, None)
if not oldname:
continue
if (
upload_fields
and fieldname in upload_fields
and oldname == upload_fields[fieldname]
):
continue
if field.custom_delete:
field.custom_delete(oldname)
else:
uploadfolder = field.uploadfolder
if not uploadfolder:
uploadfolder = pjoin(dbset.db._adapter.folder, "..", "uploads")
if field.uploadseparate:
items = oldname.split(".")
uploadfolder = pjoin(
uploadfolder, "%s.%s" % (items[0], items[1]), items[2][:2]
)
oldpath = pjoin(uploadfolder, oldname)
if field.uploadfs:
oldname = text_type(oldname)
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | if field.uploadfs.exists(oldname): |
Using the snippet: <|code_start|> and table[f].uploadfield == True
and table[f].autodelete
]
if not fields:
return False
for record in dbset.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fieldname, None)
if not oldname:
continue
if (
upload_fields
and fieldname in upload_fields
and oldname == upload_fields[fieldname]
):
continue
if field.custom_delete:
field.custom_delete(oldname)
else:
uploadfolder = field.uploadfolder
if not uploadfolder:
uploadfolder = pjoin(dbset.db._adapter.folder, "..", "uploads")
if field.uploadseparate:
items = oldname.split(".")
uploadfolder = pjoin(
uploadfolder, "%s.%s" % (items[0], items[1]), items[2][:2]
)
oldpath = pjoin(uploadfolder, oldname)
if field.uploadfs:
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (class names, function names, or code) available:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | oldname = text_type(oldname) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
UNIT_SEPARATOR = "\x1f" # ASCII unit separater for delimiting data
def hide_password(uri):
if isinstance(uri, (list, tuple)):
return [hide_password(item) for item in uri]
<|code_end|>
. Use current file imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (classes, functions, or code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | return re.sub(REGEX_CREDENTIALS, "******", uri) |
Here is a snippet: <|code_start|>def bar_escape(item):
item = str(item).replace("|", "||")
if item.startswith("||"):
item = "%s%s" % (UNIT_SEPARATOR, item)
if item.endswith("||"):
item = "%s%s" % (item, UNIT_SEPARATOR)
return item
def bar_unescape(item):
item = item.replace("||", "|")
if item.startswith(UNIT_SEPARATOR):
item = item[1:]
if item.endswith(UNIT_SEPARATOR):
item = item[:-1]
return item
def bar_encode(items):
return "|%s|" % "|".join(bar_escape(item) for item in items if str(item).strip())
def bar_decode_integer(value):
long = integer_types[-1]
if not hasattr(value, "split") and hasattr(value, "read"):
value = value.read()
return [long(x) for x in value.split("|") if x.strip()]
def bar_decode_string(value):
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
, which may include functions, classes, or code. Output only the next line. | return [bar_unescape(x) for x in re.split(REGEX_UNPACK, value[1:-1]) if x.strip()] |
Based on the snippet: <|code_start|> archive_table.insert(**fields)
break
return False
def smart_query(fields, text):
if not isinstance(fields, (list, tuple)):
fields = [fields]
new_fields = []
for field in fields:
if isinstance(field, Field):
new_fields.append(field)
elif isinstance(field, Table):
for ofield in field:
new_fields.append(ofield)
else:
raise RuntimeError("fields must be a list of fields")
fields = new_fields
field_map = {}
for field in fields:
n = field.name.lower()
if not n in field_map:
field_map[n] = field
n = str(field).lower()
if not n in field_map:
field_map[n] = field
constants = {}
i = 0
while True:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (classes, functions, sometimes code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | m = re.search(REGEX_CONST_STRING, text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.