output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def tx2genefile(gtf, out_file=None):
"""
write out a file of transcript->gene mappings.
use the installed tx2gene.csv if it exists, else write a new one out
"""
installed_tx2gene = os.path.join(os.path.dirname(gtf), "tx2gene.csv")
if file_exists(installed_tx2gene):
return installed_tx2ge... | Can you write a function in Python 3 where it
writes out a file of transcript - > gene mappings for a GTF file | As a Python code translator, you convert algorithms and pseudocode into Python. |
return a dictionary keyed by transcript_id of the associated gene_id
| Explain what the following Python 3 code does
def transcript_to_gene(gtf):
gene_lookup = {}
for feature in complete_features(get_gtf_db(gtf)):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id', [None])[0]
gene_lookup[transcript_... | As a Python code composer, you craft elegant and concise scripts. |
def set_freq(self, fout, freq):
"""
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
"""
hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers
n1div_tuple = (1,) + tuple(range(2,129,2)) #
fdco_min =... | Write a Python 3 script for
setting new output frequency for the current entry. | As a Python code composer, you craft elegant and concise scripts. |
Detects alignment requirements for binary files with new nn. util. BinaryFileHeader. | Can you tell what is the following Python 3 function doing
def _get_file_alignment_for_new_binary_file(self, file: File) -> int:
if len(file.data) <= 0x20:
return 0
bom = file.data[0xc:0xc+2]
if bom != b'\xff\xfe' and bom != b'\xfe\xff':
return 0
be = bom == b'\x... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create an analysis with given name and suffix. | Given the following Python 3 function, write the documentation
def create_analyses(name, kernel=None):
if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):
os.system("mkdir analyses")
# __init__.py
init_path = os.path.join(os.getcwd(), 'analyses', '__init__.py')
if not os.path.exists(... | As a Python code composer, you craft elegant and concise scripts. |
Convert two types of spatial references to one type of spatial reference. | Make a summary of the following Python 3 code
def crsConvert(crsIn, crsOut):
if isinstance(crsIn, osr.SpatialReference):
srs = crsIn.Clone()
else:
srs = osr.SpatialReference()
if isinstance(crsIn, int):
crsIn = 'EPSG:{}'.format(crsIn)
if isinstance(c... | You are a Python code generator, capable of creating scripts from specifications. |
def haversine(lat1, lon1, lat2, lon2):
"""
compute the distance in meters between two points in latlon
Parameters
----------
lat1: int or float
the latitude of point 1
lon1: int or float
the longitude of point 1
lat2: int or float
the latitude of point 2
lon2: in... | Implement a Python 3 function for
computing the distance in meters between two points in latlon | As a Python code analyst, you investigate and solve complex coding mysteries |
def gdalwarp(src, dst, options):
"""
a simple wrapper for :osgeo:func:`gdal.Warp`
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters passed t... | Write a Python 3 function that can
wrap for gdal. Warp | As a python code expert, you are capable of creating scripts from specifications. |
Wrapper for GDAL. BuildVRT. | How would you explain what the following Python 3 function does
def gdalbuildvrt(src, dst, options=None, void=True):
options = {} if options is None else options
if 'outputBounds' in options.keys() and gdal.__version__ < '2.4.0':
warnings.warn('\ncreating VRT files with subsetted extent is very lik... | As a python code expert, you are capable of creating scripts from specifications. |
def gdal_translate(src, dst, options):
"""
a simple wrapper for `gdal.Translate <https://gdal.org/python/osgeo.gdal-module.html#Translate>`_
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data s... | Write a Python 3 function for
wrapping for gdal. Translate | As a python code expert, you are capable of creating scripts from specifications. |
Wrapper for gdal. VectorTranslate aka ogr2ogr. | Here you have a function in Python 3, explain what it does
def ogr2ogr(src, dst, options):
out = gdal.VectorTranslate(dst, src, options=gdal.VectorTranslateOptions(**options))
out = None | As a Python code composer, you craft elegant and concise scripts. |
Wrapper for gdal. Rasterize | Make a summary of the following Python 3 code
def gdal_rasterize(src, dst, options):
out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options))
out = None | As a Python code composer, you craft elegant and concise scripts. |
reproject a coordinate from one CRS to another | Make a summary of the following Python 3 code
def coordinate_reproject(x, y, s_crs, t_crs):
source = crsConvert(s_crs, 'osr')
target = crsConvert(t_crs, 'osr')
transform = osr.CoordinateTransformation(source, target)
point = transform.TransformPoint(x, y)[:2]
return point | You are a Python code generator, capable of creating scripts from specifications. |
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None):
""" Creates output_dir, work_dir, and sets up log
"""
output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir')
debug('Saving results into ' + output_dir)
work_dir = safe_mkdir(work_dir or... | Create a Python 3 function to
create output_dir work_dir and log_fpath | You are a Python code analyst, evaluating scripts for potential improvements. |
Iterates over the response data one line at a time. | Can you tell what is the following Python 3 function doing
def _iter_lines_generator(response, decode_unicode):
pending = None
for chunk in _iter_content_generator(response, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
lines = chunk.splitlines()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _raise_for_status(response):
"""Raises stored :class:`HTTPError`, if one occurred.
This is the :meth:`requests.models.Response.raise_for_status` method,
modified to add the response from Space-Track, if given.
"""
http_error_msg = ''
if 400 <= response.status_code < 500:
http_erro... | Can you implement a function in Python 3 that
raises an exception if one occurred. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generic request for the given object. | Here you have a function in Python 3, explain what it does
def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
r"""Generic Space-Track query.
The request class methods use this method internally; the public
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Perform a get request handling rate limiting. | How would you explain what the following Python 3 function does
def _ratelimited_get(self, *args, **kwargs):
with self._ratelimiter:
resp = self.session.get(*args, **kwargs)
# It's possible that Space-Track will return HTTP status 500 with a
# query rate limit violation. This can ha... | You are a Python code generator, capable of creating scripts from specifications. |
Find first controller that matches given request class. | Can you generate the documentation for the following Python 3 function
def _find_controller(self, class_):
for controller, classes in self.request_controllers.items():
if class_ in classes:
return controller
else:
raise ValueError('Unknown request class {!r}'.form... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get raw predicate information for given request class and cache for
subsequent calls. | Given the following Python 3 function, write the documentation
def _download_predicate_data(self, class_, controller):
self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
logger.debug(requests.utils.requote_uri(url))
resp =... | You are a Python code generator, capable of creating scripts from specifications. |
Get full predicate information for given request class and cache
for subsequent calls. | Given the following Python 3 function, write the documentation
def get_predicates(self, class_, controller=None):
if class_ not in self._predicates:
if controller is None:
controller = self._find_controller(class_)
else:
classes = self.request_controllers.... | You are a Python code generator, capable of creating scripts from specifications. |
def on_install(self, editor):
"""
Add the folding menu to the editor, on install.
:param editor: editor instance on which the mode has been installed to.
"""
super(FoldingPanel, self).on_install(editor)
self.context_menu = QtWidgets.QMenu(_('Folding'), self.editor)
... | Implement a Python 3 function for
adding the folding menu to the editor. | As a python code expert, you are capable of creating scripts from specifications. |
Draw the fold zone rectangle using the current style primitive color
or foldIndicatorBackground. | Given the following Python 3 function, write the documentation
def _draw_rect(self, rect, painter):
c = self._custom_color
if self._native:
c = self.get_system_bck_color()
grad = QtGui.QLinearGradient(rect.topLeft(),
rect.topRight())
if sy... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_system_bck_color():
"""
Gets a system color for drawing the fold scope background.
"""
def merged_colors(colorA, colorB, factor):
maxFactor = 100
colorA = QtGui.QColor(colorA)
colorB = QtGui.QColor(colorB)
tmp = colorA
t... | Implement a Python 3 function for
getting a system color for drawing the fold scope background. | You are a Python code analyst, evaluating scripts for potential improvements. |
Draw the fold indicator. | How would you explain what the following Python 3 function does
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter):
rect = QtCore.QRect(0, top, self.sizeHint().width(),
self.sizeHint().height())
if self._native:
if os.environ['QT_API'].lower() not... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_scope_highlight_color(self):
"""
Gets the base scope highlight color (derivated from the editor
background)
"""
color = self.editor.background
if color.lightness() < 128:
color = drift_color(color, 130)
else:
color = drift_color(c... | How would you implement a function in Python 3 that
gets the base scope highlight color | As a Python code composer, you craft elegant and concise scripts. |
Adds a scope decoration that enclose the current scope. | Make a summary of the following Python 3 code
def _add_scope_deco(self, start, end, parent_start, parent_end, base_color,
factor):
"""
Adds a scope decoration that enclose the current scope
:param start: Start of the current scope
:param end: End of the current sc... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add scope decoration on the editor widget. | How would you explain what the following Python 3 function does
def _add_scope_decorations(self, block, start, end):
try:
parent = FoldScope(block).parent()
except ValueError:
parent = None
if TextBlockHelper.is_fold_trigger(block):
base_color = self._get_scop... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _highlight_surrounding_scopes(self, block):
"""
Highlights the scopes surrounding the current fold scope.
:param block: Block that starts the current fold scope.
"""
scope = FoldScope(block)
if (self._current_scope is None or
self._current_scope.get_r... | How would you implement a function in Python 3 that
highlights the scopes surrounding the current fold scope. | As a Python code composer, you craft elegant and concise scripts. |
def leaveEvent(self, event):
"""
Removes scope decorations and background from the editor and the panel
if highlight_caret_scope, else simply update the scope decorations to
match the caret scope.
"""
super(FoldingPanel, self).leaveEvent(event)
QtWidgets.QApplica... | Can you write a function in Python 3 where it
removes scope decorations and background from the editor and the panel. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add fold decorations to the editor. | How would you explain what the following Python 3 function does
def _add_fold_decoration(self, block, region):
deco = TextDecoration(block)
deco.signals.clicked.connect(self._on_fold_deco_clicked)
deco.tooltip = region.text(max_lines=25)
deco.draw_order = 1
deco.block = block
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Toggle a fold trigger block. | Can you tell what is the following Python 3 function doing
def toggle_fold_trigger(self, block):
if not TextBlockHelper.is_fold_trigger(block):
return
region = FoldScope(block)
if region.collapsed:
region.unfold()
if self._mouse_over_line is not None:
... | As a Python code composer, you craft elegant and concise scripts. |
Connect to the cursorPositionChanged signal and disconnect from the new_text_set signal | Can you generate a brief explanation for the following Python 3 code
def on_state_changed(self, state):
if state:
self.editor.key_pressed.connect(self._on_key_pressed)
if self._highlight_caret:
self.editor.cursorPositionChanged.connect(
self._highlight... | As a Python code composer, you craft elegant and concise scripts. |
def _on_key_pressed(self, event):
"""
Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it).
"""
delete_request = event.key() in [QtCore.Qt.Key_Backspace,
QtCore.Qt.Key_Delete]
... | Create a Python 3 function to
override key press to select the current scope if the user wants to delete a folded scope. | You are a Python code generator, capable of creating scripts from specifications. |
Verify that the payload was sent from GitHub instance. | Can you generate a brief explanation for the following Python 3 code
def verify_signature(self, payload, headers):
github_signature = headers.get("x-hub-signature")
if not github_signature:
json_abort(401, "X-Hub-Signature header missing.")
gh_webhook_secret = current_app.config["GI... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_options(self):
"""Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables.
"""
(options, args) = self.parser.parse_args()
# Set values from .visdkrc, but only if they haven't already been set
... | Can you write a function in Python 3 where it
gets the options that have been set. | As a Python code analyst, you investigate and solve complex coding mysteries |
Check for job definitions in known zuul files. | Make a summary of the following Python 3 code
def parse_job_files(self):
repo_jobs = []
for rel_job_file_path, job_info in self.job_files.items():
LOGGER.debug("Checking for job definitions in %s", rel_job_file_path)
jobs = self.parse_job_definitions(rel_job_file_path, job_info)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Changes the current directory. | Can you tell what is the following Python 3 function doing
def change_directory(self, directory):
self._process.write(('cd %s\n' % directory).encode())
if sys.platform == 'win32':
self._process.write((os.path.splitdrive(directory)[0] + '\r\n').encode())
self.clear()
else:... | You are a Python code generator, capable of creating scripts from specifications. |
Gets the icon file name. Read - only. | How would you explain what the following Python 3 function does
def icon(self):
if isinstance(self._icon, str):
if QtGui.QIcon.hasThemeIcon(self._icon):
return QtGui.QIcon.fromTheme(self._icon)
else:
return QtGui.QIcon(self._icon)
elif isinstance(s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Adds the marker to the panel. | Given the following Python 3 function, write the documentation
def add_marker(self, marker):
self._markers.append(marker)
doc = self.editor.document()
assert isinstance(doc, QtGui.QTextDocument)
block = doc.findBlockByLineNumber(marker._position)
marker.block = block
d = ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes a marker from the panel
| How would you explain what the following Python 3 function does
def remove_marker(self, marker):
self._markers.remove(marker)
self._to_remove.append(marker)
if hasattr(marker, 'decoration'):
self.editor.decorations.remove(marker.decoration)
self.repaint() | As a Python code composer, you craft elegant and concise scripts. |
Returns the marker that is displayed at the specified line number if any. | Can you generate a brief explanation for the following Python 3 code
def marker_for_line(self, line):
markers = []
for marker in self._markers:
if line == marker.position:
markers.append(marker)
return markers | As a Python code analyst, you investigate and solve complex coding mysteries |
def _display_tooltip(self, tooltip, top):
"""
Display tooltip at the specified top position.
"""
QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint(
self.sizeHint().width(), top)), tooltip, self) | Implement a function in Python 3 to
display the given tooltip at the specified top position. | As a Python code analyst, you investigate and solve complex coding mysteries |
Search occurrences using str. find instead of regular expressions. | Can you generate a brief explanation for the following Python 3 code
def finditer_noregex(string, sub, whole_word):
start = 0
while True:
start = string.find(sub, start)
if start == -1:
return
if whole_word:
if start:
pchar = string[start - 1]
... | As a python code expert, you are capable of creating scripts from specifications. |
Generator that finds all occurrences of sub in string. | Explain what the following Python 3 code does
def findalliter(string, sub, regex=False, case_sensitive=False,
whole_word=False):
"""
Generator that finds all occurrences of ``sub`` in ``string``
:param string: string to parse
:param sub: string to search
:param regex: True to search... | You are a Python code analyst, evaluating scripts for potential improvements. |
Worker that finds all occurrences of a given string or regular expression in a given text. | Can you generate the documentation for the following Python 3 function
def findall(data):
return list(findalliter(
data['string'], data['sub'], regex=data['regex'],
whole_word=data['whole_word'], case_sensitive=data['case_sensitive'])) | You are a Python code analyst, evaluating scripts for potential improvements. |
Splits a text into a list of words based on a list of word separators. | Can you generate a brief explanation for the following Python 3 code
def split(txt, seps):
# replace all possible separators with a default sep
default_sep = seps[0]
for sep in seps[1:]:
if sep:
txt = txt.replace(sep, default_sep)
# now we can split using the ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Provides completions based on the document words. | Here you have a function in Python 3, explain what it does
def complete(self, code, *args):
completions = []
for word in self.split(code, self.separators):
completions.append({'name': word})
return completions | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a message status to a string. | Here you have a function in Python 3, explain what it does
def status_to_string(cls, status):
strings = {CheckerMessages.INFO: "Info",
CheckerMessages.WARNING: "Warning",
CheckerMessages.ERROR: "Error"}
return strings[status] | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_messages(self, messages):
"""
Adds a message or a list of message.
:param messages: A list of messages or a single message
"""
# remove old messages
if len(messages) > self.limit:
messages = messages[:self.limit]
_logger(self.__class__).log(5,... | How would you code a function in Python 3 to
add a message or a list of messages to the queue. | You are a Python code generator, capable of creating scripts from specifications. |
Removes a message from the list of messages. | Here you have a function in Python 3, explain what it does
def remove_message(self, message):
import time
_logger(self.__class__).log(5, 'removing message %s' % message)
t = time.time()
usd = message.block.userData()
if usd:
try:
usd.messages.remove(me... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _on_work_finished(self, results):
"""
Display results.
:param status: Response status
:param results: Response data, messages.
"""
messages = []
for msg in results:
msg = CheckerMessage(*msg)
if msg.line >= self.editor.blockCount():
... | Can you implement a function in Python 3 that
displays results. :param status: Response status :param results: Response data, messages. | As a python code expert, you are capable of creating scripts from specifications. |
def _request(self):
""" Requests a checking of the editor content. """
try:
self.editor.toPlainText()
except (TypeError, RuntimeError):
return
try:
max_line_length = self.editor.modes.get(
'RightMarginMode').position
except KeyE... | Create a Python 3 function for
requesting a checking of the editor content. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, ... | How would you implement a function in Python 3 that
opens a pty master pair using os. openpty. | You are a Python code analyst, evaluating scripts for potential improvements. |
Open a pty master and return the fd and the filename of the slave end. | Make a summary of the following Python 3 code
def master_open():
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = os.ttyname(slave_fd)
os.close(slave_fd)
return master_fd, slave_name
return _open_terminal() | As a Python code composer, you craft elegant and concise scripts. |
def _open_terminal():
"""Open pty master and return (master_fd, tty_name)."""
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
pty_name = '/dev/pty' + x + y
try:
fd = os.open(pty_name, os.O_RDWR)
except OSError:
continue
... | Can you implement a function in Python 3 that
opens pty master and return ( master_fd tty_name | As a python code expert, you are capable of creating scripts from specifications. |
Open the pty slave and acquire the controlling terminal returning a filedescriptor. | Make a summary of the following Python 3 code
def slave_open(tty_name):
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
... | As a Python code composer, you craft elegant and concise scripts. |
fork - > ( pid master_fd slave_fd | Can you generate the documentation for the following Python 3 function
def fork():
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() alread... | You are a Python code generator, capable of creating scripts from specifications. |
Write all the data to a descriptor. | How would you explain what the following Python 3 function does
def _writen(fd, data):
while data:
n = os.write(fd, data)
data = data[n:] | As a python code expert, you are capable of creating scripts from specifications. |
def _copy(master_fd, master_read=_read, stdin_read=_read):
"""Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read)"""
fds = [master_fd, STDIN_FILENO]
while True:
rfds, wfds, xfds = select(fds, [], [])
... | Create a Python 3 function to
copy the master file into the standard output and stdin files. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new process. | Can you generate a brief explanation for the following Python 3 code
def spawn(argv, master_read=_read, stdin_read=_read):
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
try:
os.execlp(argv[0], *argv)
except:
# If we wanted ... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function only gets called if the property
doesn t have a value in the cache. | Can you generate a brief explanation for the following Python 3 code
def _get_mor(self, name, multivalued):
logger.debug("Querying server for uncached MOR %s", name)
# This will retrieve the value and inject it into the cache
logger.debug("Getting view for MOR")
self.update(properties=[n... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def flush_cache(self, properties=None):
"""Flushes the cache being held for this instance.
:param properties: The list of properties to flush from the cache.
:type properties: list or None (default). If None, flush entire cache.
"""
if hasattr(self, '_cache'):
if pr... | Implement a Python 3 function for
flushing the cache for this instance. | As a python code expert, you are capable of creating scripts from specifications. |
def update(self, properties=None):
"""Updates the properties being held for this instance.
:param properties: The list of properties to update.
:type properties: list or None (default). If None, update all
currently cached properties.
"""
if properties is None:
... | Implement a Python 3 function for
updating the properties being held for this instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_view_data(self, properties=None):
"""Update the local object from the server-side object.
>>> vm = VirtualMachine.find_one(client, filter={"name": "genesis"})
>>> # Update all properties
>>> vm.update_view_data()
>>> # Update the config and summary properties
... | Create a Python 3 function to
update the local object from the server - side object. | You are a Python code generator, capable of creating scripts from specifications. |
Pre - loads the requested properties for each object in the name attribute. | Explain what the following Python 3 code does
def preload(self, name, properties=None):
if properties is None:
raise ValueError("You must specify some properties to preload. To"
" preload all properties use the string \"all\".")
# Don't do anything if the attribu... | As a Python code analyst, you investigate and solve complex coding mysteries |
Update the local object from the passed in object_content. | Can you tell what is the following Python 3 function doing
def _set_view_data(self, object_content):
# A debugging convenience, allows inspection of the object_content
# that was used to create the object
logger.info("Setting view data for a %s", self.__class__)
self._object_content = ob... | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the repository cache used for scraping. | Here you have a function in Python 3, explain what it does
def _initialize_repo_cache():
LOGGER.info("Initializing repository cache")
# Initialize Repo Cache
repo_cache = {}
# Get all repos from Elasticsearch
for hit in GitRepo.search().query("match_all").scan():
# TODO (fschmidt): Maybe we... | You are a Python code architect, reviewing and designing scalable and efficient code |
Gets supported features from the license manager | How would you explain what the following Python 3 function does
def main(options):
client = Client(server=options.server, username=options.username,
password=options.password)
print('Successfully connected to %s' % client.server)
lm_info = client.sc.licenseManager.QuerySupportedFeatures(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds a mode instance to the editor. | Can you tell what is the following Python 3 function doing
def append(self, mode):
_logger().log(5, 'adding mode %r', mode.name)
self._modes[mode.name] = mode
mode.on_install(self.editor)
return mode | As a python code expert, you are capable of creating scripts from specifications. |
Removes a mode from the editor. | Can you tell what is the following Python 3 function doing
def remove(self, name_or_klass):
_logger().log(5, 'removing mode %r', name_or_klass)
mode = self.get(name_or_klass)
mode.on_uninstall()
self._modes.pop(mode.name)
return mode | As a Python code composer, you craft elegant and concise scripts. |
Gets a mode by name or class | Here you have a function in Python 3, explain what it does
def get(self, name_or_klass):
if not isinstance(name_or_klass, str):
name_or_klass = name_or_klass.__name__
return self._modes[name_or_klass] | You are a Python code analyst, evaluating scripts for potential improvements. |
Overrides the base on_install method to set the parent widget as the parent widget. | Can you generate the documentation for the following Python 3 function
def on_install(self, editor):
Mode.on_install(self, editor)
self.setParent(editor)
self.setPalette(QtWidgets.QApplication.instance().palette())
self.setFont(QtWidgets.QApplication.instance().font())
self.edito... | As a Python code analyst, you investigate and solve complex coding mysteries |
def setVisible(self, visible):
"""
Shows/Hides the panel
Automatically call CodeEdit.refresh_panels.
:param visible: Visible state
"""
_logger().log(5, '%s visibility changed', self.name)
super(Panel, self).setVisible(visible)
if self.editor:
... | Implement a Python 3 function for
overriding this method to update the visible state of the Panel. | You are a Python code generator, capable of creating scripts from specifications. |
Adds a text decoration on a CodeEdit instance | Can you generate a brief explanation for the following Python 3 code
def append(self, decoration):
if decoration not in self._decorations:
self._decorations.append(decoration)
self._decorations = sorted(
self._decorations, key=lambda sel: sel.draw_order)
self.... | You are a Python code architect, reviewing and designing scalable and efficient code |
Removes a text decoration from the editor. | Given the following Python 3 function, write the documentation
def remove(self, decoration):
try:
self._decorations.remove(decoration)
self.editor.setExtraSelections(self._decorations)
return True
except ValueError:
return False | You are a Python code architect, reviewing and designing scalable and efficient code |
Clears all text decoration from the editor. | How would you explain what the following Python 3 function does
def clear(self):
self._decorations[:] = []
try:
self.editor.setExtraSelections(self._decorations)
except RuntimeError:
pass | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handles key presses on the key sequence. | Can you tell what is the following Python 3 function doing
def _on_key_pressed(self, event):
if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and
not int(event.modifiers()) & QtCore.Qt.ShiftModifier):
if event.key() == QtCore.Qt.Key_0:
self.editor.reset_zoom... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _on_wheel_event(self, event):
"""
Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent
"""
try:
delta = event.angleDelta().y()
except AttributeError:... | How would you code a function in Python 3 to
increment editor fonts settings on mouse wheel event event | As a Python code composer, you craft elegant and concise scripts. |
Sets the writer function to handle writing to the text edit. | Given the following Python 3 function, write the documentation
def set_writer(self, writer):
if self._writer != writer and self._writer:
self._writer = None
if writer:
self._writer = writer | You are a Python code generator, capable of creating scripts from specifications. |
Starts a process interactively. | Explain what the following Python 3 code does
def start_process(self, process, args=None, cwd=None, env=None):
self.setReadOnly(False)
if env is None:
env = {}
if args is None:
args = []
if not self._running:
self.process = QProcess()
self.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Stop the process (by killing it). | Can you generate the documentation for the following Python 3 function
def stop_process(self):
if self.process is not None:
self._user_stop = True
self.process.kill()
self.setReadOnly(True)
self._running = False | As a Python code analyst, you investigate and solve complex coding mysteries |
def write(text_edit, text, color):
"""
Default write function. Move the cursor to the end and insert text with
the specified color.
:param text_edit: QInteractiveConsole instance
:type text_edit: pyqode.widgets.QInteractiveConsole
:param text: Text to write
:typ... | How would you code a function in Python 3 to
default write function. Move the cursor to the end and insert text with the specified color. | As a Python code analyst, you investigate and solve complex coding mysteries |
def apply_color_scheme(self, color_scheme):
"""
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments sty... | Write a Python 3 script to
apply a pygments color scheme to the console. | As a Python code analyst, you investigate and solve complex coding mysteries |
def convert_to_codec_key(value):
"""
Normalize code key value (encoding codecs must be lower case and must
not contain any dashes).
:param value: value to convert.
"""
if not value:
# fallback to utf-8
value = 'UTF-8'
# UTF-8 -> utf_8
converted = value.replace('-', '_').... | Write a Python 3 function that can
convert a value to a code key that can be used in the code page. | As a python code expert, you are capable of creating scripts from specifications. |
def process_block(self, current_block, previous_block, text):
"""
Processes a block and setup its folding info.
This method call ``detect_fold_level`` and handles most of the tricky
corner cases so that all you have to do is focus on getting the proper
fold level foreach meaning... | Write a Python 3 script to
process a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block to process... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Detects fold level by looking at the indentation guide. | Can you generate a brief explanation for the following Python 3 code
def detect_fold_level(self, prev_block, block):
text = block.text()
# round down to previous indentation guide to ensure contiguous block
# fold level evolution.
return (len(text) - len(text.lstrip())) // self.editor.ta... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reads pylintrc config into a ConfigParser object. | Can you generate the documentation for the following Python 3 function
def read_config(contents):
file_obj = io.StringIO(contents)
config = six.moves.configparser.ConfigParser()
config.readfp(file_obj)
return config | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_local_config(filename):
"""Loads the pylint.config.py file.
Args:
filename (str): The python file containing the local configuration.
Returns:
module: The loaded Python module.
"""
if not filename:
return imp.new_module('local_pylint_config')
module = imp.load_... | Can you create a Python 3 function that
loads the pylint. config. py file. | You are a Python code generator, capable of creating scripts from specifications. |
def determine_final_config(config_module):
"""Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration.
"""
config = Config(
DEFAU... | Can you create a Python 3 function that
determines the final configuration. | As a Python code analyst, you investigate and solve complex coding mysteries |
Lints a group of files using a given rcfile. | Make a summary of the following Python 3 code
def lint_fileset(*dirnames, **kwargs):
try:
rc_filename = kwargs['rc_filename']
description = kwargs['description']
if len(kwargs) != 2:
raise KeyError
except KeyError:
raise KeyError(_LINT_FILESET_MSG)
pylint_shell_c... | As a Python code composer, you craft elegant and concise scripts. |
def make_rc(base_cfg, target_filename,
additions=None, replacements=None):
"""Combines a base rc and additions into single file.
Args:
base_cfg (ConfigParser.ConfigParser): The configuration we are
merging into.
target_filename (str): The filename where the new configura... | Create a Python 3 function for
combining a base rc and additions into a single file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def run_command(args):
"""Script entry point. Lints both sets of files."""
library_rc = 'pylintrc'
test_rc = 'pylintrc.test'
if os.path.exists(library_rc):
os.remove(library_rc)
if os.path.exists(test_rc):
os.remove(test_rc)
default_config = read_config(get_default_config())
... | How would you implement a function in Python 3 that
scripts entry point. Lints both sets of files. | You are a Python code analyst, evaluating scripts for potential improvements. |
Open a connection.
@param u2request: A urllib2 request.
@type u2request: urllib2.Requet.
@return: The opened file-like urllib2 object.
@rtype: fp | Given the following Python 3 function, write the documentation
def u2open(self, u2request):
tm = self.options.timeout
url = build_opener(HTTPSClientAuthHandler(self.context))
if self.u2ver() < 2.6:
socket.setdefaulttimeout(tm)
return url.open(u2request)
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def login(self, username=None, password=None):
"""Login to a vSphere server.
>>> client.login(username='Administrator', password='strongpass')
:param username: The username to authenticate as.
:type username: str
:param password: The password to authenticate with.
:type... | Write a Python 3 function that can
login to a vSphere server. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Invoke a method on the server. | Given the following Python 3 function, write the documentation
def invoke(self, method, _this, **kwargs):
if (self._logged_in is False and
method not in ["Login", "RetrieveServiceContent"]):
logger.critical("Cannot exec %s unless logged in", method)
raise NotLoggedInError("Ca... | As a Python code composer, you craft elegant and concise scripts. |
def _mor_to_pobject(self, mo_ref):
"""Converts a MOR to a psphere object."""
kls = classmapper(mo_ref._type)
new_object = kls(mo_ref, self)
return new_object | Can you write a function in Python 3 where it
converts a MOR to a psphere object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Walks an object and marshals any psphere object into MORs. | How would you explain what the following Python 3 function does
def _marshal(self, obj):
logger.debug("Checking if %s needs to be marshalled", obj)
if isinstance(obj, ManagedObject):
logger.debug("obj is a psphere object, converting to MOR")
return obj._mo_ref
if isinsta... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _unmarshal(self, obj):
"""Walks an object and unmarshals any MORs into psphere objects."""
if isinstance(obj, suds.sudsobject.Object) is False:
logger.debug("%s is not a suds instance, skipping", obj)
return obj
logger.debug("Processing:")
logger.debug(obj)
... | Write a Python 3 function that can
walk an object and unmarshals any MORs into psphere objects. | As a python code expert, you are capable of creating scripts from specifications. |
Create a SOAP object of the requested type. | Here you have a function in Python 3, explain what it does
def create(self, type_, **kwargs):
obj = self.factory.create("ns0:%s" % type_)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.