output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def rename_fmapm(bids_base, basename):
'''
Rename magnitude fieldmap file to BIDS specification
'''
files = dict()
for ext in ['nii.gz', 'json']:
for echo in [1, 2]:
fname = '{0}_e{1}.{2}'.format(basename, echo, ext)
src = os.path.join(bids_base, 'fmap', fname)
... | Can you write a function in Python 3 where it
renames magnitude fieldmap file to BIDS specification | You are a Python code generator, capable of creating scripts from specifications. |
def convert(input, output):
'''
Run dcm2niix on input file
'''
dirname = os.path.dirname(output)
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = os.path.basename(output)
basename = re.sub('.nii(.gz)?', '', basename)
dcm2niix = commons.which('dcm2niix')
cmd = [... | Can you write a function in Python 3 where it
runs dcm2niix on input file and write to output file | As a python code expert, you are capable of creating scripts from specifications. |
def api_errors_to_messages(request, error, fallback_text):
"""
Adds messages for each error returned from the MTP apis
Useful for displaying errors when there's no form on the page
:param request: HttpRequest
:param error: HttpClientError
:param fallback_text: fallback error text
"""
try... | How would you implement a function in Python 3 that
adds messages for each error returned from the MTP API | As a python code expert, you are capable of creating scripts from specifications. |
This method loads all pages from the API endpoint and returns them as a list | Can you tell what is the following Python 3 function doing
def retrieve_all_pages(api_endpoint, **kwargs):
page_size = getattr(settings, 'REQUEST_PAGE_SIZE', 20)
loaded_results = []
offset = 0
while True:
response = api_endpoint(limit=page_size, offset=offset,
**... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method loads all pages for a given path and returns a list of all the results. | Given the following Python 3 function, write the documentation
def retrieve_all_pages_for_path(session, path, **params):
page_size = getattr(settings, 'REQUEST_PAGE_SIZE', 20)
loaded_results = []
offset = 0
while True:
response = session.get(
path,
params=dict(limit=page... | You are a Python code architect, reviewing and designing scalable and efficient code |
def DispatchSpout(*a, **kw):
"""Factory to dispatch spout class based on config."""
spout_class_name = get_config()['Spout']
spout_class = import_name(spout_class_name, default_ns='birding.spout')
return spout_class(*a, **kw) | Implement a function in Python 3 to
dispatch a single object to the appropriate spout class based on config. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def initialize(self, stormconf, context):
"""Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms.
"""
self.terms = get_config()['TermCycleSpout']['terms']
self.term_seq = itertools.cycle(self.terms) | Write a Python 3 script to
initialize the term cycle sequence based on config. | You are a Python code analyst, evaluating scripts for potential improvements. |
Next tuple steps:
1. Emit (term, timestamp) for next term in sequence w/current UTC time. | Given the following Python 3 function, write the documentation
def next_tuple(self):
term = next(self.term_seq)
timestamp = datetime.datetime.utcnow().isoformat()
self.emit([term, timestamp], tup_id=self.pack_tup_id(term, timestamp)) | As a python code expert, you are capable of creating scripts from specifications. |
def cast(s):
'''
Cast a basestring to a more appropriate type.
Example::
>>> from yaxil import cast
>>> type(cast("999"))
<type 'int'>
:param s: String
:type s: basestring
:returns: Casted string
:rtype: int|float|str
'''
if not isinstance(s, basestring):... | Write a Python 3 function that can
cast a basestring to a more appropriate type. | As a Python code composer, you craft elegant and concise scripts. |
def atomic_write(filename, content, overwrite=True, permissions=0o0644, encoding='utf-8'):
'''
Write a file atomically by writing the file content to a
temporary location first, then renaming the file.
TODO: this relies pretty heavily on os.rename to ensure atomicity, but
os.rename does not s... | Write a Python 3 function that can
write a file atomically by writing the content to a temporary location. | You are a Python code analyst, evaluating scripts for potential improvements. |
Same as which command on Linux
| Explain what the following Python 3 code does
def which(x):
'''
Same as which command on Linux
'''
for p in os.environ.get('PATH').split(os.pathsep):
p = os.path.join(p, x)
if os.path.exists(p):
return os.path.abspath(p)
return None | As a python code expert, you are capable of creating scripts from specifications. |
Starts a development server with auto - rebuilding and live - reloading. | Explain what the following Python 3 code does
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030):
try:
from watchdog.observers import Observer
except ImportError:
context.pip_command('install', 'watchdog>0.8,<0.9')
from watchdog.observers import Obser... | As a python code expert, you are capable of creating scripts from specifications. |
Creates directories needed for build outputs | Explain what the following Python 3 code does
def create_build_paths(context: Context):
paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path]
for path in filter(None, paths):
os.makedirs(path, exist_ok=True) | As a python code expert, you are capable of creating scripts from specifications. |
def node_dependencies(context: Context):
"""
Updates node.js dependencies
"""
args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]]
if not context.use_colour:
args.append('--color false')
args.append('install')
return context.shell('npm', *args) | Write a Python 3 script for
updating node. js dependencies | As a Python code translator, you convert algorithms and pseudocode into Python. |
def local_docker(context: Context):
"""
Runs the app in a docker container; for local development only!
Once performed, `docker-compose up` can be used directly
"""
output = io.StringIO()
with contextlib.redirect_stdout(output):
context.shell('docker-machine', 'ip', 'default')
host_m... | Write a Python 3 function for
running the app in a docker container ; for local development only! | As a Python code analyst, you investigate and solve complex coding mysteries |
def bundle_stylesheets(context: Context):
"""
Compiles stylesheets
"""
args = [
'--output', context.app.scss_build_path,
'--output-style', 'compressed',
]
if context.verbosity == 0:
args.append('--quiet')
if not context.use_colour:
args.append('--no-color')
... | Implement a function in Python 3 to
compile stylesheets and returns the code to be used in the bundle. | You are a Python code generator, capable of creating scripts from specifications. |
Tests javascript for code and style errors | Here you have a function in Python 3, explain what it does
def lint_javascript(context: Context):
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'),
'--format', 'stylish',
]
if context.verbosity == 0:
args.append('--qui... | You are a Python code architect, reviewing and designing scalable and efficient code |
Tests stylesheets for code and style errors | Here you have a function in Python 3, explain what it does
def lint_stylesheets(context: Context):
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'),
'--format', 'stylish',
'--syntax', 'scss',
]
if context.verbosity > 1... | As a Python code analyst, you investigate and solve complex coding mysteries |
def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alph... | Write a Python 3 function for
installing GOV. UK template | You are a Python code analyst, evaluating scripts for potential improvements. |
def additional_assets(context: Context):
"""
Collects assets from GOV.UK frontend toolkit
"""
rsync_flags = '-avz' if context.verbosity == 2 else '-az'
for path in context.app.additional_asset_paths:
context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path)) | Write a Python 3 function that can
collect assets from GOV. UK frontend toolkit | As a Python code translator, you convert algorithms and pseudocode into Python. |
Pre - compiles python modules | Explain what the following Python 3 code does
def precompile_python_code(context: Context):
from compileall import compile_dir
kwargs = {}
if context.verbosity < 2:
kwargs['quiet'] = True
compile_dir(context.app.django_app_name, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
def make_messages(context: Context, javascript=False, fuzzy=False):
"""
Collects text into translation source files
"""
kwargs = {
'all': True,
'keep_pot': True,
'no_wrap': True,
}
if fuzzy:
kwargs['allow_fuzzy'] = True
if javascript:
kwargs.update(dom... | Write a Python 3 function that can
make all the messages in the current language. | As a Python code analyst, you investigate and solve complex coding mysteries |
def translations(context: Context, pull=False, push=False):
"""
Synchronises translations with transifex.com
"""
if not (pull or push):
raise TaskError('Specify whether to push or pull translations')
if pull:
context.shell('tx', 'pull')
make_messages(context, javascript=False... | Write a Python 3 script for
synchronising translations with transifex. com | As a python code expert, you are capable of creating scripts from specifications. |
CSRF failure view which converts the failed POST request into GET and calls the original view with a sensible error message presented
to the user. | How would you explain what the following Python 3 function does
def csrf_failure(request, reason=''):
if _csrf_failed_view.no_moj_csrf:
from django.views.csrf import csrf_failure
return csrf_failure(request, reason=reason)
# present a sensible error message to users
if reason == REASON_NO_... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_positions(elinfo, center=True):
'''Computes the positions of the elctrodes based on the elinfo
Parameters
----------
elinfo: dict
Contains electrode information from yaml file (dim, pitch, sortlist, plane, pos)
Returns
-------
positions: np.array
3d points with the ... | Write a Python 3 script for
computing the positions of the elctrodes based on the elinfo dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_mea(mea_yaml_path):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
path = os.path.abspath(mea_yaml_path)
if path.endswith('.yaml') or path.endswith('.yml') and os.path.isfile(path):
wit... | Implement a function in Python 3 to
add the mea design defined by the yaml file in the install folder | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove_mea(mea_name):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
this_dir, this_filename = os.path.split(__file__)
electrodes = [f for f in os.listdir(os.path.join(this_dir, "electrodes"))]
... | Implement a function in Python 3 to
remove the mea design defined by the yaml file in the install folder | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the first and second lines of a single file. | Can you tell what is the following Python 3 function doing
def _get_two_lines(f):
l0 = f.readline()
l1 = f.readline()
return l0, l1 | As a Python code composer, you craft elegant and concise scripts. |
def classify_format(f):
"""
Determine the format of word embedding file by their content. This operation
only looks at the first two lines and does not check the sanity of input
file.
Args:
f (Filelike):
Returns:
class
"""
l0, l1 = _get_two_lines(f)
if loader.glove... | Implement a Python 3 function for
determining the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class | As a python code expert, you are capable of creating scripts from specifications. |
def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None,
format=None, binary=False):
"""
Load pretrained word embedding from a file.
Args:
path (str): Path of file to load.
vocab (str or None): Path to vocabulary file created by word2vec
... | Can you implement a function in Python 3 that
loads a pretrained word embedding from a file. | As a python code expert, you are capable of creating scripts from specifications. |
Save the object to a file. | Can you generate a brief explanation for the following Python 3 code
def save(self, path, format, binary=False, use_load_condition=False):
if use_load_condition:
if self._load_cond is None:
raise ValueError(
b"use_load_condition was specified but the object is not... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a list of paths for use in shell commands | Can you generate the documentation for the following Python 3 function
def paths_for_shell(paths, separator=' '):
paths = filter(None, paths)
paths = map(shlex.quote, paths)
if separator is None:
return paths
return separator.join(paths) | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator to turn a callable into a task
| Explain what the following Python 3 code does
def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False):
def outer(func):
task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code)
overidden_task = self._tasks.p... | You are a Python code architect, reviewing and designing scalable and efficient code |
def lookup_task(self, task):
"""
Looks up a task by name or by callable
"""
if isinstance(task, str):
try:
return self[task]
except KeyError:
pass
raise TaskError('Unknown task %s' % task) | Write a Python 3 function for
looking up a task by name or callable. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the default task if there is only one | Can you generate the documentation for the following Python 3 function
def get_default_task(self):
default_tasks = list(filter(lambda task: task.default, self.values()))
if len(default_tasks) == 1:
return default_tasks[0] | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_callable(cls, func, ignored_parameters=set()):
"""
Reads a function or method signature to produce a set of parameters
"""
group = cls()
signature = inspect.signature(func)
for parameter in signature.parameters.values():
if parameter.name.startswith('... | Create a Python 3 function to
read a function or method signature to produce a set of parameters | As a Python code translator, you convert algorithms and pseudocode into Python. |
def from_mapping(cls, mapping):
"""
Produces a set of parameters from a mapping
"""
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
valu... | Implement a Python 3 function for
producing a set of parameters from a mapping. | As a Python code composer, you craft elegant and concise scripts. |
def to_dict(self):
"""
Converts the set of parameters into a dict
"""
return dict((parameter.name, parameter.value) for parameter in self.values()) | Write a Python 3 function for
converting the set of parameters into a dict. | As a python code expert, you are capable of creating scripts from specifications. |
def consume_arguments(self, argument_list):
"""
Takes arguments from a list while there are parameters that can accept them
"""
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_argume... | Can you create a Python 3 function that
takes arguments from a list while there are parameters that can accept them | As a Python code analyst, you investigate and solve complex coding mysteries |
Updates the set of parameters from a mapping. | Can you tell what is the following Python 3 function doing
def update_from(self, mapping):
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[key].value = value | As a Python code translator, you convert algorithms and pseudocode into Python. |
Produces a parameter from a callable parameter. | Can you tell what is the following Python 3 function doing
def from_callable_parameter(cls, parameter):
if parameter.kind == parameter.KEYWORD_ONLY or \
parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty:
if parameter.annotation is not para... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the constraint callable given a value | Can you tell what is the following Python 3 function doing
def constraint_from_type(cls, value):
if value is None:
return None
value_type = type(value)
if value_type in (str, int, bool):
return value_type
raise ParameterError('Parameter type cannot be %s' % value_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a constraint callable based on choices of a given type | Explain what the following Python 3 code does
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value not in choices:
raise ParameterEr... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the name of the parameter as a command line flag | Here you have a function in Python 3, explain what it does
def arg_name(self):
if self.constraint is bool and self.value:
return '--no-%s' % self.name.replace('_', '-')
return '--%s' % self.name.replace('_', '-') | You are a Python code generator, capable of creating scripts from specifications. |
Takes arguments from a list while this parameter can accept them
| How would you explain what the following Python 3 function does
def consume_arguments(self, argument_list):
if len(argument_list) == 0:
return []
if argument_list[0] == self.arg_name:
argument_list = argument_list[1:]
if self.constraint is bool:
self.v... | You are a Python code architect, reviewing and designing scalable and efficient code |
Runs a pip command | Can you tell what is the following Python 3 function doing
def pip_command(self, command, *args):
try:
from pip._internal import main as pip_main
except ImportError:
from pip import main as pip_main
args = [command] + list(args)
if self.verbosity == 0:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Runs a shell command | Given the following Python 3 function, write the documentation
def shell(self, command, *args, environment=None):
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def management_command(self, command, *args, **kwargs):
"""
Runs a Django management command
"""
self.setup_django()
if 'verbosity' not in kwargs:
kwargs['verbosity'] = self.verbosity
if not self.use_colour:
kwargs['no_color'] = False
self.... | Write a Python 3 function for
running a Django management command | As a Python code analyst, you investigate and solve complex coding mysteries |
Prints help for the current SEO class. | How would you explain what the following Python 3 function does
def help(self, context):
context.info('%s\n%s [global options] [task] [task options]...\n' % (self.name, sys.argv[0]))
def print_parameter(prn, p):
if p.description:
suffix = ' - {0.description}'.format(p)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Log in a user. | Can you generate a brief explanation for the following Python 3 code
def login(request, user):
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUser` is returned.
"""
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KEY]... | Write a Python 3 function for
returning the user model instance associated with the given request session. | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes the authenticated user s ID from the request and flushes their
session data. | Given the following Python 3 function, write the documentation
def logout(request):
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if hasattr(user, 'is_authenticated') and not user.is_authenticated:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def save(f, arr, vocab):
"""
Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API.
"""
f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8'))
for word, idx in vocab:
_write_line(f, arr[idx], word) | How would you implement a function in Python 3 that
saves a list of words to a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator that makes a function spoolable using uWSGI. | Can you generate the documentation for the following Python 3 function
def spoolable(*, pre_condition=True, body_params=()):
def decorator(func):
context_name = None
keyword_kinds = {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}
invalid_body_params = set(body_para... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns all the fields and their raw values for this Orm instance. | Can you generate a brief explanation for the following Python 3 code
def fields(self):
return {k:getattr(self, k, None) for k in self.schema.fields} | As a python code expert, you are capable of creating scripts from specifications. |
create an instance of cls with the passed in fields and set it into the db
| Explain what the following Python 3 code does
def create(cls, fields=None, **fields_kwargs):
# NOTE -- you cannot use hydrate/populate here because populate alters modified fields
instance = cls(fields, **fields_kwargs)
instance.save()
return instance | As a python code expert, you are capable of creating scripts from specifications. |
take the passed in fields combine them with missing fields that should
be there and then run all those through appropriate methods to hydrate this object | Can you generate the documentation for the following Python 3 function
def populate(self, fields=None, **fields_kwargs):
# this will run all the fields of the Orm, not just the fields in fields
# dict, another name would be hydrate
pop_fields = {}
fields = self.make_dict(fields, fields_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get all the fields that need to be saved by the user. | How would you explain what the following Python 3 function does
def depopulate(self, is_update):
fields = {}
schema = self.schema
for k, field in schema.fields.items():
is_modified = k in self.modified_fields
orig_v = getattr(self, k)
v = field.iset(
... | As a Python code analyst, you investigate and solve complex coding mysteries |
persist the field values of this orm | Make a summary of the following Python 3 code
def insert(self):
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
fields[schema.pk.name] = pk
... | As a python code expert, you are capable of creating scripts from specifications. |
re - persist the updated field values of this orm that has a primary key | Here you have a function in Python 3, explain what it does
def update(self):
ret = True
fields = self.depopulate(True)
q = self.query
q.set_fields(fields)
pk = self.pk
if pk:
q.is_field(self.schema.pk.name, pk)
else:
raise ValueError("You... | As a Python code translator, you convert algorithms and pseudocode into Python. |
persist the fields in this object into the db | Can you generate the documentation for the following Python 3 function
def save(self):
ret = False
# we will only use the primary key if it hasn't been modified
pk = None
if self.schema.pk.name not in self.modified_fields:
pk = self.pk
if pk:
ret = self.... | You are a Python code generator, capable of creating scripts from specifications. |
def delete(self):
"""delete the object from the db if pk is set"""
ret = False
q = self.query
pk = self.pk
if pk:
pk_name = self.schema.pk.name
self.query.is_field(pk_name, pk).delete()
setattr(self, pk_name, None)
# mark all the f... | How would you implement a function in Python 3 that
deletes the object from the db | You are a Python code analyst, evaluating scripts for potential improvements. |
def reset_modified(self):
"""
reset field modification tracking
this is handy for when you are loading a new Orm with the results from a query and
you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to
clear all the passed in fields from the ... | Write a Python 3 script to
reset modified_fields to the set of all the passed in fields | You are a Python code architect, reviewing and designing scalable and efficient code |
def modify(self, fields=None, **fields_kwargs):
"""update the fields of this instance with the values in dict fields
this should rarely be messed with, if you would like to manipulate the
fields you should override _modify()
:param fields: dict, the fields in a dict
:param **fi... | Write a Python 3 function for
modifying the fields of this instance | As a Python code analyst, you investigate and solve complex coding mysteries |
def jsonable(self, *args, **options):
"""
return a public version of this instance that can be jsonified
Note that this does not return _id, _created, _updated, the reason why is
because lots of times you have a different name for _id (like if it is a
user object, then you migh... | How would you code a function in Python 3 to
return a public version of this object that can be jsonified by the user. | As a Python code analyst, you investigate and solve complex coding mysteries |
def merge2images(hdu1, hdu2, debugplot):
"""Merge 2 EMIR images, averaging the common region.
Parameters
----------
hdu1 : HDUList object
Input image #1.
hdu2 : HDUList object
Input image #2.
debugplot : int
Determines whether intermediate computations and/or plots
... | Write a Python 3 script to
merge 2 EMIR images. | You are a Python code generator, capable of creating scripts from specifications. |
configure interfaces based on environment variables PROM_DSN and PROM_DSN_N | Can you tell what is the following Python 3 function doing
def configure_environ(dsn_env_name='PROM_DSN', connection_class=DsnConnection):
inters = []
cs = dsnparse.parse_environs(dsn_env_name, parse_class=connection_class)
for c in cs:
inter = c.interface
set_interface(inter, c.name)
... | As a python code expert, you are capable of creating scripts from specifications. |
def configure(dsn, connection_class=DsnConnection):
"""
configure an interface to be used to query a backend
you use this function to configure an Interface using a dsn, then you can get
that interface using the get_interface() method
dsn -- string -- a properly formatted prom dsn, see DsnConnecti... | Can you implement a function in Python 3 that
configures an interface to be used to query a backend | As a Python code composer, you craft elegant and concise scripts. |
def set_interface(interface, name=''):
"""
don't want to bother with a dsn? Use this method to make an interface available
"""
global interfaces
if not interface: raise ValueError('interface is empty')
# close down the interface before we discard it
if name in interfaces:
interface... | Can you create a Python 3 function that
sets the interface for the specified name. | You are a Python code generator, capable of creating scripts from specifications. |
A context manager which serves this websocket. | Here you have a function in Python 3, explain what it does
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622
ws = await create_websocket_server(sock, filter=filter)
try:
yield ws
finally:
await ws.close() | As a Python code analyst, you investigate and solve complex coding mysteries |
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622
"""
A more low-level form of open_websocket_server.
You are responsible for closing this websocket.
"""
ws = Websocket()
await ws.start_server(sock, filter=filter)
return ws | Can you create a Python 3 function that
creates a new websocket server. | You are a Python code analyst, evaluating scripts for potential improvements. |
fields that aren t magic | Here you have a function in Python 3, explain what it does
def normal_fields(self):
return {f:v for f, v in self.fields.items() if not f.startswith('_')} | As a Python code translator, you convert algorithms and pseudocode into Python. |
The normal required fields. | Can you generate a brief explanation for the following Python 3 code
def required_fields(self):
return {f:v for f, v in self.normal_fields.items() if v.required} | You are a Python code architect, reviewing and designing scalable and efficient code |
the magic fields for the schema | Can you generate the documentation for the following Python 3 function
def magic_fields(self):
return {f:v for f, v in self.fields.items() if f.startswith('_')} | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add an index to the schema | Make a summary of the following Python 3 code
def set_index(self, index_name, index):
if not index_name:
raise ValueError("index_name must have a value")
if index_name in self.indexes:
raise ValueError("index_name {} has already been defined on {}".format(
index_n... | As a Python code analyst, you investigate and solve complex coding mysteries |
return the schema instance if this is reference to another table | Can you generate the documentation for the following Python 3 function
def schema(self):
if not hasattr(self, "_schema"):
ret = None
o = self._type
if isinstance(o, type):
ret = getattr(o, "schema", None)
elif isinstance(o, Schema):
... | As a Python code composer, you craft elegant and concise scripts. |
def fval(self, instance):
"""return the raw value that this property is holding internally for instance"""
try:
val = instance.__dict__[self.instance_field_name]
except KeyError as e:
#raise AttributeError(str(e))
val = None
return val | How would you code a function in Python 3 to
return the raw value that this property is holding internally for instance | As a python code expert, you are capable of creating scripts from specifications. |
def set_default_reference(self, method, reference):
"""
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference}
"""
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.... | Write a Python 3 function that can
set the default reference for a method. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the default reference for a method. | Here you have a function in Python 3, explain what it does
def get_default_reference(self, method):
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.format(method))
return self._default_references.get(method) | As a python code expert, you are capable of creating scripts from specifications. |
def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None):
"""
Prints all x-ray transitions for an element, with their different
notations and energy.
{element}
:arg file: file for output, default to standard out
"""
header = ['IUP... | Can you create a Python 3 function that
prints all x - ray transitions for an element with their different notations and energy. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_modules(modulepath):
"""return all found modules at modulepath (eg, foo.bar) including modulepath module"""
m = importlib.import_module(modulepath)
mpath = m.__file__
ret = set([m])
if "__init__." in mpath.lower():
mpath = os.path.dirname(mpath)
# https://docs.python.org/2/... | Create a Python 3 function for
returning all found modules at modulepath including modulepath module | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_subclasses(modulepath, parent_class):
"""given a module return all the parent_class subclasses that are found in
that module and any submodules.
:param modulepath: string, a path like foo.bar.che
:param parent_class: object, the class whose children you are looking for
:returns: set, all th... | Implement a function in Python 3 to
give a module return all the parent_class subclasses that are found in that module and any submodules. | You are a Python code architect, reviewing and designing scalable and efficient code |
build the dump order of the given orm_class | Here you have a function in Python 3, explain what it does
def build_dump_order(orm_class, orm_classes):
if orm_class in orm_classes: return
for field_name, field_val in orm_class.schema.fields.items():
if field_val.is_ref():
build_dump_order(field_val.schema.orm_class, orm_classes)
if... | You are a Python code generator, capable of creating scripts from specifications. |
dump all or part of the prom data | Can you generate the documentation for the following Python 3 function
def main_dump(paths, directory, dry_run):
table_map = get_table_map(paths)
for conn_name, conn_info in table_map.items():
inter = conn_info["interface"]
conn = inter.connection_config
table_names = conn_info["table_n... | You are a Python code architect, reviewing and designing scalable and efficient code |
def main_restore(directory, conn_name):
"""Restore your database dumped with the dump command
just a wrapper around `dump restore` https://github.com/Jaymon/dump
"""
inter = get_interface(conn_name)
conn = inter.connection_config
cmd = get_base_cmd("restore", inter, directory)
run_cmd(cmd) | Implement a Python 3 function for
restoring your database dumped with the dump command just a wrapper around `dump restore` https://github.com/Jaymon/dump | As a python code expert, you are capable of creating scripts from specifications. |
def _get_fields(self, table_name, **kwargs):
"""return all the fields for the given schema"""
ret = {}
query_str = []
query_args = ['f', table_name]
# I had to brush up on my join knowledge while writing this query
# https://en.wikipedia.org/wiki/Join_(SQL)
#
... | Implement a Python 3 function for
returning all the fields for the given schema | As a Python code analyst, you investigate and solve complex coding mysteries |
return all the indexes for the given schema | Can you generate the documentation for the following Python 3 function
def _get_indexes(self, schema, **kwargs):
ret = {}
query_str = []
query_str.append('SELECT')
query_str.append(' tbl.relname AS table_name, i.relname AS index_name, a.attname AS field_name,')
query_str.append(... | As a python code expert, you are capable of creating scripts from specifications. |
def _set_index(self, schema, name, fields, **index_options):
"""
NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html
"""
index_fields =... | How would you implement a function in Python 3 that
sets the index name for the current record. | You are a Python code architect, reviewing and designing scalable and efficient code |
def client_authentication(self, request, auth=None, **kwargs):
"""
Deal with client authentication
:param request: The refresh access token request
:param auth: Client authentication information
:param kwargs: Extra keyword arguments
:return: dictionary containing client... | How would you implement a function in Python 3 that
deals with client authentication | You are a Python code generator, capable of creating scripts from specifications. |
This is where clients come to get their access tokens | Here you have a function in Python 3, explain what it does
def _post_parse_request(self, request, client_id='', **kwargs):
if 'state' in request:
try:
sinfo = self.endpoint_context.sdb[request['code']]
except KeyError:
logger.error('Code not present in Se... | As a Python code analyst, you investigate and solve complex coding mysteries |
def register(self, new_outputs, *args, **kwargs):
"""
Register outputs and metadata.
* ``initial_value`` - used in dynamic calculations
* ``size`` - number of elements per timestep
* ``uncertainty`` - in percent of nominal value
* ``variance`` - dictionary of covariances... | Write a Python 3 function for
registering outputs and metadata. | You are a Python code analyst, evaluating scripts for potential improvements. |
def initial_classification(self, obresult, target_is_sky=False):
"""Classify input frames, """
# lists of targets and sky frames
with obresult.frames[0].open() as baseimg:
# Initial checks
has_bpm_ext = 'BPM' in baseimg
self.logger.debug('images have BPM exte... | Write a Python 3 function for
classifying input frames into a list of images and images_info. | You are a Python code generator, capable of creating scripts from specifications. |
Read CSU information and slits from header | Make a summary of the following Python 3 code
def read_csu_2(barmodel, hdr):
conf = CSUConf(barmodel)
conf.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in conf.bars:
key = "CSUP{}".format(idx)
# UNIT of CSUPOS?
# who know... | As a python code expert, you are capable of creating scripts from specifications. |
Read CSU information and slits from header | How would you explain what the following Python 3 function does
def read_csu_3(barmodel, hdr):
conf = CSUConf(barmodel)
conf.set_state(hdr)
return conf | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read CSU information and slits from header and set position in model | How would you explain what the following Python 3 function does
def set_state(self, hdr):
self.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in self.bars:
key = "CSUP{}".format(idx)
# UNIT is mm
# ... | You are a Python code generator, capable of creating scripts from specifications. |
Recreate the list of all the slits from header. | Given the following Python 3 function, write the documentation
def _update_slits(self, hdr):
# Slits.
# For the moment we will fuse only reference slits
# clean existing slits
self.slits = {}
mm = []
for idx in self.LBARS:
# References from header
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a recorded duration. | Here you have a function in Python 3, explain what it does
def update(self, duration):
if duration >= 0:
self.histogram.update(duration)
self.meter.mark() | As a Python code composer, you craft elegant and concise scripts. |
Build the g5k conf from the vmong5k conf. | Can you generate a brief explanation for the following Python 3 code
def _build_g5k_conf(vmong5k_conf):
clusters = [m.cluster for m in vmong5k_conf.machines]
sites = g5k_api_utils.get_clusters_sites(clusters)
site_names = set(sites.values())
if len(site_names) > 1:
raise Exception("Multisite dep... | As a Python code composer, you craft elegant and concise scripts. |
Copy Django model instance as a dictionary excluding auto - created and many - to - one reverse relation. | How would you explain what the following Python 3 function does
def copy_model_instance(obj):
meta = getattr(obj, '_meta') # make pycharm happy
# dictionary of model values excluding auto created and related fields
return {f.name: getattr(obj, f.name)
for f in meta.get_fields(include_parents=Fa... | You are a Python code architect, reviewing and designing scalable and efficient code |
Loads the data from the parameters and applies units to the cache. | Make a summary of the following Python 3 code
def load_data(self, *args, **kwargs):
# get positional argument names from parameters and apply them to args
# update data with additional kwargs
argpos = {
v['extras']['argpos']: k for k, v in self.parameters.iteritems()
if '... | As a python code expert, you are 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.