output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def run_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and let caller deal with results"
if env is None:
env = os.environ
p_args = OCRMYPDF + list(args) + [input_file, output_file]
p = Popen(
p_args, close_fds=True, stdout=PIPE, stderr=PIPE,
universal_newline... | Can you create a Python 3 function that
runs ocrmypdf and let caller deal with results | You are a Python code generator, capable of creating scripts from specifications. |
pretty - fine the name for pysc2 map lookup | Explain what the following Python 3 code does
def standardizeMapName(mapName):
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basename(mapName)
newName = newName.split(".")... | As a python code expert, you are capable of creating scripts from specifications. |
def env_info():
'''
Returns a string that contains the Python version and runtime path.
'''
v = sys.version_info
pyver = f'Python {v.major}.{v.minor}.{v.micro}'
if v.releaselevel == 'alpha':
pyver += 'a'
if v.releaselevel == 'beta':
pyver += 'b'
if v.releaselevel == 'cand... | Implement a Python 3 function for
returning a string that contains the Python version and runtime path. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Serializes a dict - like object into a generator of the flatten list of key - value pairs. | Here you have a function in Python 3, explain what it does
def dict2kvlist(o):
'''
Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
A short - hand for retrieving a value from nested mappings
. | Can you generate the documentation for the following Python 3 function
def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True):
'''
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given ... | You are a Python code generator, capable of creating scripts from specifications. |
def patch_init_py(base_dir, name, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir, name)
if not os.path.isdir(package_dir):
os.makedirs(package_... | How would you code a function in Python 3 to
patch __init__. py to remove version check and append hard - coded version. | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_(self, state):
"""Check if machine is in given state."""
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state | Write a Python 3 function for
checking if machine is in given state. | As a python code expert, you are capable of creating scripts from specifications. |
def can_be_(self, state):
"""Check if machine can transit to given state."""
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
transitions = self._meta['transitions'][self.... | Write a Python 3 script for
checking if machine can transit to given state. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set new state without checking if transition is allowed. | Given the following Python 3 function, write the documentation
def force_set(self, state):
translator = self._meta['translator']
state = translator.translate(state)
attr = self._meta['state_attribute_name']
setattr(self, attr, state) | You are a Python code generator, capable of creating scripts from specifications. |
Set new state for the current machine. | Here you have a function in Python 3, explain what it does
def set_(self, state):
if not self.can_be_(state):
state = self._meta['translator'].translate(state)
raise TransitionError(
"Cannot transit from '{actual_value}' to '{value}'."
.format(actual_value=self.actual_state.v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate getter for given value. | Explain what the following Python 3 code does
def generate_getter(value):
@property
@wraps(is_)
def getter(self):
return self.is_(value)
return getter | You are a Python code architect, reviewing and designing scalable and efficient code |
def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | Create a Python 3 function to
generate state checker for given value. | You are a Python code architect, reviewing and designing scalable and efficient code |
def generate_setter(value):
"""Generate setter for given value."""
@wraps(set_)
def setter(self):
self.set_(value)
return setter | Implement a Python 3 function for
generating setter for given value. | As a Python code analyst, you investigate and solve complex coding mysteries |
Translate value to enum instance. | Can you tell what is the following Python 3 function doing
def translate(self, value):
if self._check_if_already_proper(value):
return value
try:
return self.search_table[value]
except KeyError:
raise ValueError("Value {value} doesn't match any state.".format... | As a python code expert, you are capable of creating scripts from specifications. |
Query the API for the specified natural language text and returns information as JSON. | Can you generate the documentation for the following Python 3 function
def _query(self, text):
params = (
('v', self.api_version),
('query', text),
('lang', self.language),
('sessionId', self.session_id),
('timezone', self.timezone),
)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_venv():
"""Check whether if this workspace is a virtualenv.
"""
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Linux"]:
executable_list = ["activate", "pip"... | Create a Python 3 function to
check whether this workspace is a virtualenv. | You are a Python code analyst, evaluating scripts for potential improvements. |
Find the python version used in this virtualenv. | Explain what the following Python 3 code does
def find_linux_venv_py_version():
available_python_version = [
"python2.6",
"python2.7",
"python3.3",
"python3.4",
"python3.5",
"python3.6",
]
dir_path = os.path.dirname(SRC)
for basename in os.listdir(os.path.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_venv_DST():
"""Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
"""
dir_path = os.path.dirname(SRC)
if SYS_NAME == "Windows":
DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
... | Write a Python 3 function for
finding where this package should be installed to in this virtualenv. | As a Python code analyst, you investigate and solve complex coding mysteries |
Find where this package should be installed to. | Can you tell what is the following Python 3 function doing
def find_DST():
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], PKG_NAME) | You are a Python code analyst, evaluating scripts for potential improvements. |
def md5_of_file(abspath):
"""Md5 value of a file.
"""
chunk_size = 1024 * 1024
m = hashlib.md5()
with open(abspath, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
m.update(data)
return m.hexdigest() | Can you write a function in Python 3 where it
returns md5 value of a file. | As a Python code composer, you craft elegant and concise scripts. |
Check if installed package are exactly the same to this one. | Here you have a function in Python 3, explain what it does
def check_need_install():
need_install_flag = False
for root, _, basename_list in os.walk(SRC):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
src = os.path.join(root, basename)
... | You are a Python code generator, capable of creating scripts from specifications. |
Manual install main script. | How would you explain what the following Python 3 function does
def install():
# check installed package
print("Compare to '%s' ..." % DST)
need_install_flag = check_need_install()
if not need_install_flag:
print(" package is up-to-date, no need to install.")
return
print("Differe... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Login to the given docker registry using the given credentials and token scope. | Can you tell what is the following Python 3 function doing
async def login(
sess: aiohttp.ClientSession,
registry_url: yarl.URL,
credentials: dict,
scope: str) -> dict:
'''
Authorize to the docker registry using the given credentials and token scope, and returns a set
of requ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_git(path):
"""Return True if this is a git repo."""
try:
repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
return True if repo_dir else False
except (OSError, RuntimeError):
return False | Implement a Python 3 function for
returning True if this is a git repo. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def date_version(scm=None):
"""Generate a version string based on the SCM type and the date."""
dt = str(time.strftime('%Y%m%d%H%M'))
if scm:
version = "0.0+unknown.{0}.{1}".format(scm, dt)
else:
version = "0.0+unknown." + dt
return version | Write a Python 3 function for
generating a version string based on the SCM type and the date. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the git branch name of the current HEAD in path. | Can you generate the documentation for the following Python 3 function
def get_git_cleaned_branch_name(path):
# Get name of current branch (or 'HEAD' for a detached HEAD)
branch_name = run_cmd(path, 'git', 'rev-parse', '--abbrev-ref', 'HEAD')
branch_name = re.sub(r"[^A-Za-z0-9]+", ".", branch_name.strip())
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_git_version(path):
"""Get the GIT version."""
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods else ''
# Get a lis... | Can you write a function in Python 3 where it
gets the GIT version of the working copy. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_version_from_scm(path=None):
"""Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this pac... | Can you create a Python 3 function that
gets the current version string of this package using SCM tool. | You are a Python code architect, reviewing and designing scalable and efficient code |
Use pkg_resources to get version of installed module by name. | Explain what the following Python 3 code does
def get_version_from_module(module):
if module is not None:
# Setup.py will not pass in a module, but creating __version__ from
# __init__ will.
module = str(module).split('.', 1)[0]
try:
package = pkg_resources.get_distributi... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _must_decode(value):
"""Copied from pkginfo 1.4.1, _compat module."""
if type(value) is bytes:
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('latin1')
return value | Write a Python 3 function for
copying from pkginfo 1. 4. 1 _compat module. | As a python code expert, you are capable of creating scripts from specifications. |
Assume path points to unpacked source distribution and get version. | Here you have a function in Python 3, explain what it does
def get_version_from_unpacked_sdist(path):
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO')) as f:
data = f.read()
except IOError:
# Could not load path as ... | As a python code expert, you are capable of creating scripts from specifications. |
def get_version_from_file(path):
"""Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None
"""
filename = os.path.join(path, VERSION_FILE)
if not os.path.isfile(filename):
# Look in the parent directory of path instead.
filename = os.path.jo... | Can you create a Python 3 function that
finds the VERSION_FILE and return its contents. | As a python code expert, you are capable of creating scripts from specifications. |
def normalised(version):
"""Normalise a version string according to PEP 440, if possible."""
norm_version = pkg_resources.parse_version(version)
if not isinstance(norm_version, tuple):
# Let setuptools (>= 8) do the normalisation
return str(norm_version)
else:
# Homegrown normali... | Write a Python 3 function for
normalising a version string according to PEP 440 if possible. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the version string of the current version of the current version of the current version of the current version. | Given the following Python 3 function, write the documentation
def get_version(path=None, module=None):
# Check the module option first.
version = get_version_from_module(module)
if version:
return normalised(version)
# Turn path into a valid directory (default is current directory)
if path... | As a Python code composer, you craft elegant and concise scripts. |
Ensure the major and minor numbers are int. | Here you have a function in Python 3, explain what it does
def _sane_version_list(version):
v0 = str(version[0])
if v0:
# Test if the major is a number.
try:
v0 = v0.lstrip("v").lstrip("V")
# Handle the common case where tags have v before major.
v0 = int(v0)
... | As a python code expert, you are capable of creating scripts from specifications. |
Return the version information as a tuple. | Explain what the following Python 3 code does
def get_version_list(path=None, module=None):
major = 0
minor = 0
patch = '' # PEP440 calls this prerelease, postrelease or devrelease
ver = get_version(path, module)
if ver is not None:
ver_segments = _sane_version_list(ver.split(".", 2))
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def build_info(name, path=None, module=None):
"""Return the build info tuple."""
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) | Can you create a Python 3 function that
returns the build info tuple. | You are a Python code analyst, evaluating scripts for potential improvements. |
def find(self, groupid):
""" return all of the indices of particles of groupid """
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] | Create a Python 3 function for
finding all of the indices of particles of groupid | As a Python code analyst, you investigate and solve complex coding mysteries |
return the sum of weights of each object | How would you explain what the following Python 3 function does
def sum(self, weights=None):
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) | As a python code expert, you are capable of creating scripts from specifications. |
def center(self, weights=None):
""" return the center of each object """
if weights is None:
weights = self.data.weights
mass = utils.bincount(self.labels, weights, self.N)
cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8')
for d in range(self.data.pos.shape... | Can you create a Python 3 function that
returns the center of each object | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the rows of sampleDF that are associated to the parameter paramName. | Given the following Python 3 function, write the documentation
def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True):
if not paramName is None:
if not paramId is None:
if getParameterTypeNameFromID(paramId) != paramName:
raise ValueEr... | As a python code expert, you are capable of creating scripts from specifications. |
This method is called by the interpolation functions in the base class to interpolate the parameters of the independant variables. | Make a summary of the following Python 3 code
def interpolate(self, interpValues):
self.__operations.append(["interpolate", interpValues])
df = self.sampleDF
self.interpValues = interpValues
for interParamName, value in interpValues.items():
self.__report ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def loo_compare(psisloo1, psisloo2):
"""
Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2... | Create a Python 3 function for
comparing two Psisloo objects using pointwise approximate leave - one - out cross validation. | You are a Python code generator, capable of creating scripts from specifications. |
def plot(self):
""" Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis)
"""
seaborn.pointplot(
y = self.pointwise.pareto_k,
x = self.pointwise.index,
... | Write a Python 3 script to
plot the pointwise importance - sampling indices of the observation units. | As a Python code composer, you craft elegant and concise scripts. |
def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):
"""provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3)
"""
i... | Implement a Python 3 function for
adding a new layer to the stack | As a python code expert, you are capable of creating scripts from specifications. |
returns the list of isotopes for the element of the compound defined with their stoichiometric values | Can you tell what is the following Python 3 function doing
def get_isotopic_ratio(self, compound='', element=''):
_stack = self.stack
compound = str(compound)
if compound == '':
_list_compounds = _stack.keys()
list_all_dict = {}
for _compound in _list_compoun... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function updates the isotopic ratio of the current set of elements in the current set of elements. | Can you generate the documentation for the following Python 3 function
def set_isotopic_ratio(self, compound='', element='', list_ratio=[]):
_stack = self.stack
list_compounds = _stack.keys()
if compound not in _stack.keys():
list_compounds_joined = ', '.join(list_compounds)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns the list of isotopes for the element of the compound defined with their density | Can you tell what is the following Python 3 function doing
def get_density(self, compound='', element=''):
_stack = self.stack
if compound == '':
_list_compounds = _stack.keys()
list_all_dict = {}
for _compound in _list_compounds:
_list_element = _sta... | As a Python code composer, you craft elegant and concise scripts. |
This method is called by the module that is going to be run on the stack. | Can you generate the documentation for the following Python 3 function
def __math_on_stack(self, used_lock=False):
# populate stack_sigma (Sigma vs Energy for every element)
self.__get_sigmas()
# populate compound density (if none provided)
self.__update_layer_density()
# popu... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __lock_density_if_defined(self, stack: dict):
"""lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entir... | Implement a Python 3 function for
locking the density if the density has been defined during initialization. | As a Python code composer, you craft elegant and concise scripts. |
def __calculate_atoms_per_cm3(self, used_lock=False):
"""calculate for each element, the atoms per cm3"""
stack = self.stack
_density_lock = self.density_lock
for _name_of_compound in stack.keys():
if used_lock and _density_lock[_name_of_compound]:
continue
... | Can you write a function in Python 3 where it
calculates for each element the atoms per cm3 | As a python code expert, you are capable of creating scripts from specifications. |
update the stack with isotopes file names mass and atomic_ratio from each element in stack | How would you explain what the following Python 3 function does
def __update_stack_with_isotopes_infos(self, stack: dict):
for _key in stack:
_elements = stack[_key]['elements']
for _element in _elements:
_dict = _utilities.get_isotope_dicts(element=_element, database=sel... | As a Python code composer, you craft elegant and concise scripts. |
calculate or update the layer density | Can you tell what is the following Python 3 function doing
def __update_layer_density(self):
_stack = self.stack
_density_lock = self.density_lock
list_compound = _stack.keys()
for _key in list_compound:
if _density_lock[_key]:
continue
_list_rati... | You are a Python code analyst, evaluating scripts for potential improvements. |
Update the molar mass of the element given due to stoichiometric changes | Can you tell what is the following Python 3 function doing
def __update_molar_mass(self, compound='', element=''):
_molar_mass_element = 0
list_ratio = self.stack[compound][element]['isotopes']['isotopic_ratio']
list_mass = self.stack[compound][element]['isotopes']['mass']['value']
ratio... | As a Python code composer, you craft elegant and concise scripts. |
Plot the transmission or attenuation of the compound element and or isotope of the current language. | Given the following Python 3 function, write the documentation
def plot(self, y_axis='attenuation', x_axis='energy',
logx=False, logy=False,
mixed=True, all_layers=False, all_elements=False,
all_isotopes=False, items_to_plot=None,
time_unit='us', offset_us=0., source_... | As a Python code composer, you craft elegant and concise scripts. |
export x and y values to clipboard or. csv file | Can you generate a brief explanation for the following Python 3 code
def export(self, output_type='df', filename=None, x_axis='energy', y_axis='attenuation', mixed=True,
all_layers=False, all_elements=False, all_isotopes=False, items_to_export=None,
offset_us=0., source_to_detector_m=16.,
... | As a python code expert, you are capable of creating scripts from specifications. |
def main():
"""Builds a yaml file"""
parser = argparse.ArgumentParser(description='Compose a yaml file.')
parser.add_argument(
'root',
type=argparse.FileType('r'),
help='The root yaml file to compose.'
)
args = parser.parse_args()
result = yaml.load(args.root, Loader=Co... | Implement a Python 3 function for
building a yaml file | You are a Python code analyst, evaluating scripts for potential improvements. |
Parses the text into a date datetime or time depending on what information is available. | How would you explain what the following Python 3 function does
def _parse(self, text, mode):
if text is None or not text.strip():
return None
# first try to parse as an ISO8601 date, if it doesn't work we'll try other options
if len(text) >= 16:
try:
par... | As a python code expert, you are capable of creating scripts from specifications. |
Gets the possible component sequences in the given mode. | Given the following Python 3 function, write the documentation
def _get_possible_sequences(cls, mode, length, date_style):
sequences = []
date_sequences = cls.DATE_SEQUENCES_DAY_FIRST if date_style == DateStyle.DAY_FIRST else cls.DATE_SEQUENCES_MONTH_FIRST
if mode == Mode.DATE or mode == Mode.A... | You are a Python code architect, reviewing and designing scalable and efficient code |
Makes a date datetime or time object from a map of component values. | Explain what the following Python 3 code does
def _make_result(cls, values, now, timezone):
date = None
time = None
if Component.MONTH in values:
year = cls._year_from_2digits(values.get(Component.YEAR, now.year), now.year)
month = values[Component.MONTH]
day... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a relative 2 - digit year to an absolute 4 - digit year. | How would you explain what the following Python 3 function does
def _year_from_2digits(short_year, current_year):
if short_year < 100:
short_year += current_year - (current_year % 100)
if abs(short_year - current_year) >= 50:
if short_year < current_year:
... | You are a Python code generator, capable of creating scripts from specifications. |
def prepare_patchset(project, patchset, binaries, ips, urls):
""" Create black/white lists and default / project waivers
and iterates over patchset file """
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, fil... | Can you create a Python 3 function that
prepares the black list and white lists for a given project and patchset. | As a python code expert, you are capable of creating scripts from specifications. |
def scan_patch(project, patch_file, binaries, ips, urls, file_audit_list,
file_audit_project_list, flag_list, ignore_list, file_ignore,
ignore_directories, url_ignore, ip_ignore, apikey):
"""
Scan actions for each commited file in patch set
"""
global failure
split_pat... | Can you implement a function in Python 3 that
scans patch file for changes and return a list of successive items | You are a Python code analyst, evaluating scripts for potential improvements. |
def scan_binary(patch_file, project, sha256hash, apikey):
"""
Sends Binary (sha256hash) to Virus Total API
"""
v_api = virus_total.VirusTotal()
while True:
binary_report = v_api.binary_report(sha256hash, apikey)
response_code = binary_report['response_code']
# report does n... | Can you write a function in Python 3 where it
scans binary files for a given project and sha256hash. | You are a Python code analyst, evaluating scripts for potential improvements. |
Write negative binary report to log file. | Can you tell what is the following Python 3 function doing
def negative_report(binary_report, sha256hash, project, patch_file):
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.info('File scan date for %s shows a clean status on: %s', patch_file, scan_date)
logger.in... | As a python code expert, you are capable of creating scripts from specifications. |
Check if a Positive match is found and if so show a full report | Can you generate the documentation for the following Python 3 function
def positive_report(binary_report, sha256hash, project, patch_file):
failure = True
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.error("Virus Found!")
logger.info('File scan date for %s sh... | As a Python code analyst, you investigate and solve complex coding mysteries |
Scan VirusTotal API for a given IP Address. | Can you generate the documentation for the following Python 3 function
def scan_ipaddr(ipaddr, apikey):
logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr)
v_api = virus_total.VirusTotal()
scan_ip = v_api.send_ip(ipaddr, apikey)
response_code = scan_ip['response_code']
verbose_msg = ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def scan_url(url, apikey):
"""
If URL is found, scan it
"""
logger.info('Found what I believe is a URL: %s', url)
v_api = virus_total.VirusTotal()
while True:
url_report = v_api.url_report(url, apikey)
response_code = url_report['response_code']
# report does not exist, ... | Write a Python 3 script for
scanning a URL for VirusTotal reports. | As a Python code analyst, you investigate and solve complex coding mysteries |
Exit if a failure occurs. | Here you have a function in Python 3, explain what it does
def process_failure(project):
if failure:
lists = get_lists.GetLists()
report_url = lists.report_url(project)
if report_url:
print(report_url)
sys.exit(1) | As a python code expert, you are capable of creating scripts from specifications. |
def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2) | Can you write a function in Python 3 where it
computes average gradient norm of an image | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the RMS contrast norm of an image | Given the following Python 3 function, write the documentation
def contrast_rms(data, *kwargs):
av = np.average(data, *kwargs)
mal = 1 / (data.shape[0] * data.shape[1])
return np.sqrt(mal * np.sum(np.square(data - av))) | You are a Python code analyst, evaluating scripts for potential improvements. |
def spectral(data, lambd, *kwargs):
""" Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
... | Write a Python 3 function that can
compute spectral contrast of image | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_gzip_file(abspath):
"""Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
_, ext = os.path.splitext(abspath)
if ext in [".gz", ".zip"]:
is_gzip = True
else:
is_gzip = False
... | Can you implement a function in Python 3 that
parses file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file | You are a Python code analyst, evaluating scripts for potential improvements. |
def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "wb") as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding)))
else:
f.write(s.encode(encoding)) | Write a Python 3 function that can
write string to text file. | As a Python code composer, you craft elegant and concise scripts. |
Read string from text file. | Can you tell what is the following Python 3 function doing
def read(path, encoding="utf-8"):
is_gzip = is_gzip_file(path)
with open(path, "rb") as f:
if is_gzip:
return zlib.decompress(f.read()).decode(encoding)
else:
return f.read().decode(encoding) | As a python code expert, you are capable of creating scripts from specifications. |
Read text from file automatically detect encoding. Chardet is required. | How would you explain what the following Python 3 function does
def smartread(path):
with open(path, "rb") as f:
content = f.read()
result = chardet.detect(content)
return content.decode(result["encoding"]) | As a Python code composer, you craft elegant and concise scripts. |
Convert any text file to utf8 encoding. | Can you generate the documentation for the following Python 3 function
def to_utf8(path, output_path=None):
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path) | You are a Python code analyst, evaluating scripts for potential improvements. |
def readlines(path, encoding="utf-8", skiplines=None, nlines=None, strip='right'):
"""skip n lines and fetch the next n lines.
:param skiplines: default None, skip first n lines
:param nlines: default None, yield next n lines
:param strip: default None, available option 'left', 'right', 'both'
... | Write a Python 3 function that can
yield a generator of lines from file | As a python code expert, you are capable of creating scripts from specifications. |
def readchunks(path, encoding="utf-8", skiplines=None, chunksize=None, strip='right'):
"""skip n lines and fetch the next n lines as a chunk, and repeat fetching.
:param skiplines: default None, skip first n lines
:param chunksize: default None (size-1 chunk), lines chunk size
:param strip: default... | Implement a Python 3 function for
reading a file into chunks | As a Python code analyst, you investigate and solve complex coding mysteries |
Coerce the value to a supported data type. | Can you tell what is the following Python 3 function doing
def _coerce_to_supported_type(cls, value):
if value is None:
return "" # empty string rather than none
elif isinstance(value, dict):
if '*' in value:
return value['*']
elif '__default__' in va... | As a Python code analyst, you investigate and solve complex coding mysteries |
def evaluate_template(self, template, context, url_encode=False, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
:param template: the template string
:param context: the evaluation context
... | Write a Python 3 script to
evaluate a template string and returns a tuple of the evaluated template string and a list of evaluation errors | As a Python code translator, you convert algorithms and pseudocode into Python. |
Resolves an expression block found in the template e. g. @(\. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. \ d + \. | Given the following Python 3 function, write the documentation
def _resolve_expression_block(self, expression, context, url_encode, strategy, errors):
try:
body = expression[1:] # strip prefix
# if expression doesn't start with ( then check it's an allowed top level context reference
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def evaluate_expression(self, expression, context, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a single expression, e.g. "contact.reports * 2"
:param expression: the expression string
:param context: the evaluation context
:param strategy: the evaluation strategy
... | Create a Python 3 function to
evaluate a single expression and returns the value of the expression. | You are a Python code generator, capable of creating scripts from specifications. |
Resolves the available context references and returns a partially evaluated expression. | Can you tell what is the following Python 3 function doing
def _resolve_available(self, tokens, context):
from .gen.ExcellentParser import ExcellentParser
has_missing = False
output_components = []
for t in range(len(tokens.tokens) - 1): # we can ignore the final EOF token
... | As a Python code composer, you craft elegant and concise scripts. |
def visitFunctionCall(self, ctx):
"""
expression : fnname LPAREN parameters? RPAREN
"""
func_name = ctx.fnname().getText()
if ctx.parameters() is not None:
parameters = self.visit(ctx.parameters())
else:
parameters = []
return self._funct... | Implement a function in Python 3 to
return an expression that is the result of evaluating the function. | You are a Python code analyst, evaluating scripts for potential improvements. |
def visitNegation(self, ctx):
"""
expression: MINUS expression
"""
return -conversions.to_decimal(self.visit(ctx.expression()), self._eval_context) | Can you create a Python 3 function that
returns a negative integer representation of the expression. | As a python code expert, you are capable of creating scripts from specifications. |
def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context)
return conversions.... | Can you write a function in Python 3 where it
returns the value of the expression EXPONENT expression as a decimal number. | As a Python code analyst, you investigate and solve complex coding mysteries |
Multiplication or division expression | Explain what the following Python 3 code does
def visitMultiplicationOrDivisionExpression(self, ctx):
is_mul = ctx.TIMES() is not None
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context... | You are a Python code generator, capable of creating scripts from specifications. |
def visitAdditionOrSubtractionExpression(self, ctx):
"""
expression: expression (PLUS | MINUS) expression
"""
is_add = ctx.PLUS() is not None
arg1 = self.visit(ctx.expression(0))
arg2 = self.visit(ctx.expression(1))
# first try as decimals
try:
... | Write a Python 3 function that can
return the value of the addition or subtraction expression as a number. | As a python code expert, you are capable of creating scripts from specifications. |
def visitComparisonExpression(self, ctx):
"""
expression: expression (LTE | LT | GTE | GT) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
# string comparison ... | How would you code a function in Python 3 to
return a boolean indicating if the value of a comparison expression is greater than or equal to a value of a key. | As a Python code composer, you craft elegant and concise scripts. |
return an expression AMPERSAND expression | Can you tell what is the following Python 3 function doing
def visitConcatenation(self, ctx):
arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._eval_context)
return arg1 + arg2 | You are a Python code architect, reviewing and designing scalable and efficient code |
def visitContextReference(self, ctx):
"""
expression: NAME
"""
identifier = ctx.NAME().getText()
return self._eval_context.resolve_variable(identifier) | Write a Python 3 script for
returning the value of the variable referenced by the given context identifier. | As a Python code composer, you craft elegant and concise scripts. |
Load the cached Zotero data. | Make a summary of the following Python 3 code
def load_cache(self):
with open(self.cache_path, "rb") as f:
print("Loading cached Zotero data...")
cache = pickle.load(f)
self._references = cache[self.CACHE_REFERENCE_LIST]
self.reference_types = cache[self.CACHE_REF... | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_distant(self):
"""Load the distant Zotero data."""
print("Loading distant Zotero data...")
self._references = self.get_references()
self.reference_types = self.get_reference_types()
self.reference_templates = self.get_reference_templates(self.reference_types)
pri... | Create a Python 3 function to
load the distant Zotero data. | As a Python code analyst, you investigate and solve complex coding mysteries |
Cache the Zotero data. | Make a summary of the following Python 3 code
def cache(self):
with open(self.cache_path, "wb") as f:
cache = {self.CACHE_REFERENCE_LIST: self._references,
self.CACHE_REFERENCE_TYPES: self.reference_types,
self.CACHE_REFERENCE_TEMPLATES: self.reference_templ... | You are a Python code generator, capable of creating scripts from specifications. |
def create_distant_reference(self, ref_data):
"""Validate and create the reference in Zotero and return the created item."""
self.validate_reference_data(ref_data)
creation_status = self._zotero_lib.create_items([ref_data])
try:
created_item = creation_status["successful"]["0... | Write a Python 3 function that can
validate and create the reference in Zotero and return the created item. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_local_reference(self, index, ref):
"""Replace the reference in the reference list and cache it."""
self._references[index] = ref
self.cache() | Create a Python 3 function to
replace the reference in the reference list with the reference ref. | You are a Python code generator, capable of creating scripts from specifications. |
def update_distant_reference(self, ref):
"""Validate and update the reference in Zotero.
Existing fields not present will be left unmodified.
"""
self.validate_reference_data(ref["data"])
self._zotero_lib.update_item(ref) | Write a Python 3 script to
validate and update the distant reference in Zotero. | You are a Python code architect, reviewing and designing scalable and efficient code |
def validate_reference_data(self, ref_data):
"""Validate the reference data.
Zotero.check_items() caches data after the first API call.
"""
try:
self._zotero_lib.check_items([ref_data])
except InvalidItemFields as e:
raise InvalidZoteroItemError from e | Can you write a function in Python 3 where it
validates the reference data. | As a python code expert, you are capable of creating scripts from specifications. |
Return the reference types. | How would you explain what the following Python 3 function does
def get_reference_types(self):
item_types = self._zotero_lib.item_types()
return sorted([x["itemType"] for x in item_types]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.