output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def update_stats(self, file_result):
"""
Reads the data from a FileResult and updates overall statistics
:param file_result: A FileResult instance
"""
for code, count in file_result.violations.items():
if code not in self.violations:
self.violations[c... | Create a Python 3 function for
reading the data from a FileResult and updates the overall statistics with the sum of the error and warning counts. | You are a Python code analyst, evaluating scripts for potential improvements. |
def report_build_messages(self):
"""
Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity
and performs the adequate actions to report statistics.
Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout.
Curre... | Implement a function in Python 3 to
report the build messages for a specific build agent. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function returns a phase transformation theta_i. | Can you generate the documentation for the following Python 3 function
def phase_transformation(Ne, Nl, rm, xi, return_equations=False):
# We first define the needed variables
E0, omega_laser = define_laser_variables(Nl)
theta = [Symbol('theta'+str(i+1)) for i in range(Ne)]
# We check for the case of x... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a simplifying function its inverse and simplified frequencies. | Can you generate a brief explanation for the following Python 3 code
def define_simplification(omega_level, xi, Nl):
try:
Ne = len(omega_level)
except:
Ne = omega_level.shape[0]
#####################################
# 1 We calculate the symplifying functions.
om = omega_level[0]
... | As a Python code composer, you craft elegant and concise scripts. |
r Find the smallest transition frequency for each field. | Given the following Python 3 function, write the documentation
def find_omega_min(omega_levelu, Neu, Nl, xiu):
omega_min = []; iu0 = []; ju0 = []
for l in range(Nl):
omegasl = []
for iu in range(Neu):
for ju in range(iu):
if xiu[l, iu, ju] == 1:
om... | As a python code expert, you are capable of creating scripts from specifications. |
r Get the indices of the transitions of all fields. | Can you generate the documentation for the following Python 3 function
def detunings_indices(Neu, Nl, xiu):
pairs = []
for l in range(Nl):
ind = []
for iu in range(Neu):
for ju in range(iu):
if xiu[l, iu, ju] == 1:
ind += [(iu, ju)]
pairs +... | As a Python code composer, you craft elegant and concise scripts. |
r Get the code to calculate the simplified detunings. | Can you generate a brief explanation for the following Python 3 code
def detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0):
code_det = ""
for l in range(Nl):
for pair in pairs[l]:
iu, ju = pair
code_det += " delta"+str(l+1)
code_det += "_"+str(iu+1)
... | As a python code expert, you are capable of creating scripts from specifications. |
r Rewrites a symbolic expression in terms of allowed transition detunings. | Can you tell what is the following Python 3 function doing
def detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu,
omega_levelu, iu0, ju0):
r"""Rewrite a symbolic expression in terms of allowed transition detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 1... | You are a Python code architect, reviewing and designing scalable and efficient code |
r Returns a fast function that returns a Hamiltonian. | Given the following Python 3 function, write the documentation
def fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, xi, theta,
file_name=None):
r"""Return a fast function that returns a Hamiltonian as an array.
INPUT:
- ``Ep`` - A list with the electric field amplitudes... | As a Python code analyst, you investigate and solve complex coding mysteries |
r This function calculates the coefficients for a linear term. | How would you explain what the following Python 3 function does
def linear_get_coefficients(coef, rhouv, s, i, j, k, u, v,
unfolding, matrix_form):
r"""Get the indices mu, nu, and term coefficients for linear terms.
We determine mu and nu, the indices labeling the density matrix com... | As a python code expert, you are capable of creating scripts from specifications. |
def fast_lindblad_terms(gamma, unfolding, matrix_form=False, file_name=None,
return_code=False):
r"""Return a fast function that returns the Lindblad terms.
We test a basic two-level system.
>>> import numpy as np
>>> Ne = 2
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.arra... | Can you write a function in Python 3 where it
returns a fast function that returns the Lindblad terms. | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Returns an observable ammount. | Explain what the following Python 3 code does
def observable(operator, rho, unfolding, complex=False):
if len(rho.shape) == 2:
return np.array([observable(operator, i, unfolding) for i in rho])
Ne = unfolding.Ne
Mu = unfolding.Mu
obs = 0
if unfolding.normalized:
rho11 = 1 - sum([rh... | As a Python code composer, you craft elegant and concise scripts. |
r Returns the electric succeptibility for a given field. | Make a summary of the following Python 3 code
def electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, part=0):
epsilonm = epsilonp.conjugate()
rp = np.array([rm[i].transpose().conjugate() for i in range(3)])
if part == 1:
op = cartesian_dot_product(rp, epsilonm[0])
op += cartesia... | You are a Python code analyst, evaluating scripts for potential improvements. |
r Folds a vector into a matrix. | Can you tell what is the following Python 3 function doing
def inverse(self, rhov, time_derivative=False):
Ne = self.Ne
Nrho = self.Nrho
IJ = self.IJ
if isinstance(rhov, np.ndarray):
rho = np.zeros((Ne, Ne), complex)
numeric = True
elif isinstance(rhov, s... | As a Python code composer, you craft elegant and concise scripts. |
This function is used to plot the BZ in order to get the order of the objects in the order they are in. | Can you tell what is the following Python 3 function doing
def bdplotter(task, **kwargs):
'''
bdplotter is based on the fact that phonon DOS/bands and
electron DOS/bands are the objects of the same kind.
1) DOS is formatted precomputed / smeared according to a normal distribution
2) bands are format... | As a Python code translator, you convert algorithms and pseudocode into Python. |
eplotter is like bdplotter but less complicated | Given the following Python 3 function, write the documentation
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
'''
eplotter is like bdplotter but less complicated
'''
results, color, fdata = [], None, []
if task == 'optstory':
color = '#CC0000'
clickable = True
for n, i ... | As a python code expert, you are capable of creating scripts from specifications. |
def assign_parser(self, name):
'''
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
'''
for n, p in list(self.Parsers.items()):
if n != name:
del self.Parsers[n]
if len(self.Parse... | Create a Python 3 function to
assign a parser to the current parser. | You are a Python code architect, reviewing and designing scalable and efficient code |
def formula(self, atom_sequence):
'''
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
'''
labels = {}
types = []
y = 0
for k, atomi in enumerate(atom_sequence):
lbl = re.sub("[0-9]+", "", atom... | Implement a Python 3 function for
constructing a standardized chemical formula for the given atom sequence. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method will take a string and return a list of filenames that can be processed. | Given the following Python 3 function, write the documentation
def savvyize(self, input_string, recursive=False, stemma=False):
'''
Determines which files should be processed
NB: this is the PUBLIC method
@returns filenames_list
'''
input_string = os.path.abspath(input_st... | As a Python code composer, you craft elegant and concise scripts. |
Parse a set of items from a parsable object. | Make a summary of the following Python 3 code
def _parse(self, parsable, parser_name):
'''
Low-level parsing
NB: this is the PRIVATE method
@returns tilde_obj, error
'''
calc, error = None, None
try:
for calc in self.Parsers[parser_name].iparse(parsabl... | As a Python code translator, you convert algorithms and pseudocode into Python. |
High - level parsing for the tilde object. | Can you generate the documentation for the following Python 3 function
def parse(self, parsable):
'''
High-level parsing:
determines the data format
and combines parent-children outputs
NB: this is the PUBLIC method
@returns tilde_obj, error
'''
calc, erro... | As a python code expert, you are capable of creating scripts from specifications. |
def classify(self, calc, symprec=None):
'''
Reasons on normalization, invokes hierarchy API and prepares calc for saving
NB: this is the PUBLIC method
@returns tilde_obj, error
'''
error = None
symbols = calc.structures[-1].get_chemical_symbols()
calc.info... | Create a Python 3 function to
classify the current structure using the hierarchy API and returns the tilde_obj and the error message | As a python code expert, you are capable of creating scripts from specifications. |
def postprocess(self, calc, with_module=None, dry_run=None):
'''
Invokes module(s) API
NB: this is the PUBLIC method
@returns apps_dict
'''
for appname, appclass in self.Apps.items():
if with_module and with_module != appname: continue
run_permitt... | Write a Python 3 function that can
invoke module(s) API NB: this is the PUBLIC method @returns apps_dict | As a Python code composer, you craft elegant and concise scripts. |
Saves the tilde_obj into the database. | Here you have a function in Python 3, explain what it does
def save(self, calc, session):
'''
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
'''
checksum = calc.get_checksum()
try:
existing_calc = session.quer... | You are a Python code generator, capable of creating scripts from specifications. |
def purge(self, session, checksum):
'''
Deletes calc entry by checksum entirely from the database
NB source files on disk are not deleted
NB: this is the PUBLIC method
@returns error
'''
C = session.query(model.Calculation).get(checksum)
if not C:
... | Write a Python 3 script for
deleting calc entry by checksum entirely from the database. | As a Python code composer, you craft elegant and concise scripts. |
def merge(self, session, checksums, title):
'''
Merges calcs into a new calc called DATASET
NB: this is the PUBLIC method
@returns DATASET, error
'''
calc = Output(calcset=checksums)
cur_depth = 0
for nested_depth, grid_item, download_size in session.que... | Can you implement a function in Python 3 that
merges the given checksums into a new calc called DATASET | As a Python code analyst, you investigate and solve complex coding mysteries |
def augment(self, session, parent, addendum):
'''
Augments a DATASET with some calcs
NB: this is the PUBLIC method
@returns error
'''
parent_calc = session.query(model.Calculation).get(parent)
if not parent_calc or not parent_calc.siblings_count:
retur... | Implement a function in Python 3 to
augment a DATASET with some calcs with some addendum. | As a python code expert, you are capable of creating scripts from specifications. |
def isCLIExecutable(filePath):
"""Test whether given `filePath` is an executable. Does not really
check whether the executable is a CLI (e.g. whether it supports
--xml), but can be used to filter out non-executables within a
directory with CLI modules.
"""
# see qSlicerUtils::isCLIExecutable
... | Write a Python 3 script to
test whether given filePath is an executable. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return list of paths to valid CLI executables within baseDir. This calls isCLIExecutable on all files within baseDir. | Can you generate the documentation for the following Python 3 function
def listCLIExecutables(baseDir):
return [path for path in glob.glob(os.path.join(os.path.normpath(baseDir), '*'))
if isCLIExecutable(path)] | You are a Python code generator, capable of creating scripts from specifications. |
Wrapper around subprocess. Popen that tries to detect Slicer CLI modules and launches them through the Slicer launcher. | Can you generate a brief explanation for the following Python 3 code
def popenCLIExecutable(command, **kwargs):
cliExecutable = command[0]
# hack (at least, this does not scale to other module sources):
# detect Slicer modules and run through wrapper script setting up
# appropriate runtime environment... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getXMLDescription(cliExecutable, **kwargs):
"""Call given cliExecutable with --xml and return xml ElementTree
representation of standard output.
Any kwargs are passed on to subprocess.Popen() (via popenCLIExecutable())."""
command = [cliExecutable, '--xml']
stdout, stdoutFilename = tempfi... | Write a Python 3 function that can
call given cliExecutable with -- xml and return xml ElementTree representation of standard output. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _candidate_filenames():
"""Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames.
"""
while True:
random_stub = ''.join([
random.choice(string.ascii_letters + string.digits)
... | Write a Python 3 function that can
generate filenames of the form specktre_123AB. png. | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a coordinate generator and a filename draw those coordinates in
a new image and save them to the file. | Can you tell what is the following Python 3 function doing
def draw_tiling(coord_generator, filename):
im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT))
for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT):
ImageDraw.Draw(im).polygon(shape, outline='white')
im.save(filename) | As a Python code composer, you craft elegant and concise scripts. |
def trace(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'TRACE'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.trace("Houston, we have a %s", "thorny problem", exc_info=1)
"""
if self.isEnabledFor(TRACE):
self._log... | Can you create a Python 3 function that
logs msg % args with severity TRACE. | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_error(self, code, line, char, description):
"""
Registers an error for this container with code on line at char.
:param code: The PEP 8 error code
:param line: The line number of the reported error
:param char: Line location of first offending character
:param des... | Implement a function in Python 3 to
add an error to the internal list of errors that occurred at the specified line. | As a python code expert, you are capable of creating scripts from specifications. |
def resolve_setting(default, arg_value=None, env_var=None, config_value=None):
"""
Resolves a setting for a configuration option. The winning value is chosen
from multiple methods of configuration, in the following order of priority
(top first):
- Explicitly passed argument
- Environment variab... | Can you implement a function in Python 3 that
resolves a setting for a configuration option. | You are a Python code generator, capable of creating scripts from specifications. |
def get_state(cls, clz):
"""
Retrieve the state of a given Class.
:param clz: types.ClassType
:return: Class state.
:rtype: dict
"""
if clz not in cls.__shared_state:
cls.__shared_state[clz] = (
clz.init_state() if hasattr(clz, "init_s... | How would you implement a function in Python 3 that
retrieves the state of a given Class. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _unique(session, cls, queryfunc, constructor, arg, kw):
'''
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject
Checks if ORM entity exists according to criteria,
if yes, returns it, if no, creates
'''
with session.no_autoflush:
q = session.query(cls)
q = q... | Implement a function in Python 3 to
return the first object in the database if it does not exist creates it if no | As a Python code analyst, you investigate and solve complex coding mysteries |
def _unique_todict(session, cls, queryfunc, arg, kw):
'''
Checks if ORM entity exists according to criteria,
if yes, returns it, if no, returns dict representation
(required for further DB replication and syncing)
'''
q = session.query(cls)
q = queryfunc(q, *arg, **kw)
obj = q.first()
... | How would you code a function in Python 3 to
return dict representation of the object that is unique to the ORM entity. | As a Python code translator, you convert algorithms and pseudocode into Python. |
r A function that returns a symbolic density matrix. | Make a summary of the following Python 3 code
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False,
variables=None):
r"""Return a symbolic density matrix.
The arguments are
Ne (integer):
The number of atomic states.
explicitly_hermitian (boolean)... | As a Python code analyst, you investigate and solve complex coding mysteries |
r Returns a unitary vector describing the polarization of the waves. | Can you tell what is the following Python 3 function doing
def polarization_vector(phi, theta, alpha, beta, p):
epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0])
R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0],
[sin(2*alpha), cos(2*alpha), 0],
[0, 0, 1]])
R2 = Matrix([[cos(... | You are a Python code analyst, evaluating scripts for potential improvements. |
def mass_mailing_recipients():
"""
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
T... | Can you create a Python 3 function that
returns iterable of all mass email recipients. | As a Python code analyst, you investigate and solve complex coding mysteries |
r A function to plot complex matrices. | Here you have a function in Python 3, explain what it does
def complex_matrix_plot(A, logA=False, normalize=False, plot=True, **kwds):
N = len(A[0])
if logA:
Anew = []
for i in range(N):
row = []
for j in range(N):
if A[i][j] != 0:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def bar_chart_mf(data, path_name):
"""Make a bar chart for data on MF quantities."""
N = len(data)
ind = np.arange(N) # the x locations for the groups
width = 0.8 # the width of the bars
fig, ax = pyplot.subplots()
rects1 = ax.bar(ind, data, width, color='g')
# add some t... | Can you create a Python 3 function that
makes a bar chart for data on MF quantities. | You are a Python code generator, capable of creating scripts from specifications. |
def draw_plane_wave_3d(ax, beam, dist_to_center=0):
"""Draw the polarization of a plane wave."""
Ex = []; Ey = []; Ez = []
k = [cos(beam.phi)*sin(beam.theta),
sin(beam.phi)*sin(beam.theta),
cos(beam.theta)]
kx, ky, kz = k
Nt = 1000
tstep = 7*pi/4/(Nt-1)
alpha... | How would you implement a function in Python 3 that
draws the polarization of a plane wave. | You are a Python code generator, capable of creating scripts from specifications. |
Draw MOT lasers in 3d. | Can you generate a brief explanation for the following Python 3 code
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None):
if distances is None: distances = [1.0 for i in range(len(lasers))]
for i in range(len(lasers)):
if type(lasers[i]) == PlaneWave:
draw_plane_wave_3d(a... | As a Python code composer, you craft elegant and concise scripts. |
r Plot the populations of a density matrix. | Here you have a function in Python 3, explain what it does
def plot_populations(path, name, Ne, states=None, filename='a.png',
fontsize=12, absolute_frequency=True,
save_path='', use_netcdf=True):
r"""Plot the populations of a density matrix."""
pyplot.close("all")
... | As a Python code analyst, you investigate and solve complex coding mysteries |
r Draw a beam splitter. | Can you tell what is the following Python 3 function doing
def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds):
if format is None: format = 'k-'
a = size/2
x0 = [a, -a, -a, a, a, -a]
y0 = [a, a, -a, -a, a, -a]
cur_list = [(x0, y0)]
cur_list = rotate_and_traslate(cur_list, ... | As a Python code composer, you craft elegant and concise scripts. |
r Draw a laser beam. | Make a summary of the following Python 3 code
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None,
format=None, **kwds):
r"""Draw a laser beam."""
if format is None: format = 'k-'
if width == 0:
x0 = [p1[0], p2[0]]
y0 = [p1[1], p2[1]]
ax.plot(x0, y0, form... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Draw a simple beam splitter. | Here you have a function in Python 3, explain what it does
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0,
format=None, **kwds):
r"""Draw a simple beam splitter."""
if format is None: format = 'k-'
a = size/2
b = width/2
x0 = [a, -a, -a, a, a]
y0 =... | As a python code expert, you are capable of creating scripts from specifications. |
r Draw an arithmetic operator. | Can you generate the documentation for the following Python 3 function
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None,
fontsize=10, **kwds):
r"""Draw an arithmetic operator."""
if format is None: format = 'k-'
a = size/2.0
x0 = [0, 2.5*a, 0, 0]
y0 = [a, 0, -a, a... | As a python code expert, you are capable of creating scripts from specifications. |
Like os. dup2 but retry on EBUSY | How would you explain what the following Python 3 function does
def dup2(a, b, timeout=3):
dup_err = None
# give FDs 3 seconds to not be busy anymore
for i in range(int(10 * timeout)):
try:
return os.dup2(a, b)
except OSError as e:
dup_err = e
if e.errno =... | As a python code expert, you are capable of creating scripts from specifications. |
def pipes(stdout=PIPE, stderr=PIPE, encoding=_default_encoding):
"""Capture C-level stdout/stderr in a context manager.
The return value for the context manager is (stdout, stderr).
Examples
--------
>>> with capture() as (stdout, stderr):
... printf("C-level stdout")
... output = std... | Can you create a Python 3 function that
captures C-level stdout/stderr in a context manager. The return value for the context manager is (stdout, stderr). Examples -------- >>> with capture() as (stdout, stderr): ... printf("C-level stdout") ... output = stdout.read() | You are a Python code analyst, evaluating scripts for potential improvements. |
Redirect sys. stdout and sys. stderr to sys. stdout and sys. stderr. | Can you tell what is the following Python 3 function doing
def sys_pipes(encoding=_default_encoding):
return pipes(sys.stdout, sys.stderr, encoding=encoding) | You are a Python code analyst, evaluating scripts for potential improvements. |
def sys_pipes_forever(encoding=_default_encoding):
"""Redirect all C output to sys.stdout/err
This is not a context manager; it turns on C-forwarding permanently.
"""
global _mighty_wurlitzer
if _mighty_wurlitzer is None:
_mighty_wurlitzer = sys_pipes(encoding)
_mighty_wurlitzer.__e... | Write a Python 3 script for
redirecting all C output to sys. stdout and err This is not a context manager. | You are a Python code generator, capable of creating scripts from specifications. |
Register me as an IPython extension | How would you explain what the following Python 3 function does
def load_ipython_extension(ip):
if not getattr(ip, 'kernel'):
warnings.warn(
"wurlitzer extension doesn't do anything in terminal IPython"
)
return
ip.events.register('pre_execute', sys_pipes_forever)
ip.even... | You are a Python code architect, reviewing and designing scalable and efficient code |
Unload me as an IPython extension
| Here you have a function in Python 3, explain what it does
def unload_ipython_extension(ip):
if not getattr(ip, 'kernel'):
return
ip.events.unregister('pre_execute', sys_pipes_forever)
ip.events.unregister('post_execute', stop_sys_pipes) | As a python code expert, you are capable of creating scripts from specifications. |
def _decode(self, data):
"""Decode data, if any
Called before passing to stdout/stderr streams
"""
if self.encoding:
data = data.decode(self.encoding, 'replace')
return data | Can you write a function in Python 3 where it
decodes data if any Called before passing to stdout streams | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a filter to the tokenizer chain. | Can you tell what is the following Python 3 function doing
def push_filters(self, new_filters):
t = self.tokenizer
for f in new_filters:
t = f(t)
self.tokenizer = t | You are a Python code architect, reviewing and designing scalable and efficient code |
Yields bad words and suggested alternate spellings. | Can you generate a brief explanation for the following Python 3 code
def check(self, text):
for word, pos in self.tokenizer(text):
correct = self.dictionary.check(word)
if correct:
continue
yield word, self.dictionary.suggest(word) if self.suggest else []
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_service_from_port(port, all_services=None):
"""Gets the name of the service from the port
all_services allows you to feed in the services to look through, pass
in a dict of service names to service information eg.
{
'service_name': {
'port': port_number
}
}
... | Can you write a function in Python 3 where it
gets the name of the service from the given port | As a Python code composer, you craft elegant and concise scripts. |
def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False):
"""If run_only, returns only the services that are in the runs_on list.
If deploy_to_only, returns only the services in the deployed_to list.
If neither, both are returned, duplicates stripped.
Results... | Write a Python 3 function that can
return a list of all nodes that receive a given service. | You are a Python code analyst, evaluating scripts for potential improvements. |
def all_nodes_that_run_in_env(service, env, service_configuration=None):
""" Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to no... | Write a Python 3 script to
return all nodes that run in a certain environment | As a Python code composer, you craft elegant and concise scripts. |
def precision_and_scale(x):
"""
From a float, decide what precision and scale are needed to represent it.
>>> precision_and_scale(54.2)
(3, 1)
>>> precision_and_scale(9)
(1, 0)
Thanks to Mark Ransom,
http://stackoverflow.com/questions/3018758/determine-precision-and-scale-of-particular... | Implement a Python 3 function for
converting a float to a precision and scale tuple. | As a python code expert, you are capable of creating scripts from specifications. |
Coerce a datum to the most specific data type. | Can you generate the documentation for the following Python 3 function
def coerce_to_specific(datum):
if datum is None:
return None
try:
result = dateutil.parser.parse(datum)
# but even if this does not raise an exception, may
# not be a date -- dateutil's parser is very aggress... | As a python code expert, you are capable of creating scripts from specifications. |
def _places_b4_and_after_decimal(d):
"""
>>> _places_b4_and_after_decimal(Decimal('54.212'))
(2, 3)
"""
tup = d.as_tuple()
return (len(tup.digits) + tup.exponent, max(-1*tup.exponent, 0)) | Create a Python 3 function for
returning the number of digits and exponent of a decimal number. | You are a Python code generator, capable of creating scripts from specifications. |
def worst_decimal(d1, d2):
"""
Given two Decimals, return a 9-filled decimal representing both enough > 0 digits
and enough < 0 digits (scale) to accomodate numbers like either.
>>> worst_decimal(Decimal('762.1'), Decimal('-1.983'))
Decimal('999.999')
"""
(d1b4, d1after) = _places_b4_and_af... | Implement a Python 3 function for
giving two Decimals return a 9 - filled decimal representing both enough > 0 digits and enough < 0 digits. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the original taxonomy to new_worst. | Can you generate a brief explanation for the following Python 3 code
def set_worst(old_worst, new_worst):
if isinstance(new_worst, bool):
return new_worst
# Negative numbers confuse the length calculation.
negative = ( (hasattr(old_worst, '__neg__') and old_worst < 0) or
(hasa... | As a python code expert, you are capable of creating scripts from specifications. |
def best_representative(d1, d2):
"""
Given two objects each coerced to the most specific type possible, return the one
of the least restrictive type.
>>> best_representative(Decimal('-37.5'), Decimal('0.9999'))
Decimal('-99.9999')
>>> best_representative(None, Decimal('6.1'))
Decimal('6.1')... | Can you write a function in Python 3 where it
gives two objects d1 and d2 return the one of the most restrictive type possible. | You are a Python code analyst, evaluating scripts for potential improvements. |
Given an iterable of scalar data returns the datum representing the most specific
data type. | Here you have a function in Python 3, explain what it does
def best_coercable(data):
preference = (datetime.datetime, bool, int, Decimal, float, str)
worst_pref = 0
worst = ''
for datum in data:
coerced = coerce_to_specific(datum)
pref = preference.index(type(coerced))
if pref > ... | You are a Python code generator, capable of creating scripts from specifications. |
def sqla_datatype_for(datum):
"""
Given a scalar Python value, picks an appropriate SQLAlchemy data type.
>>> sqla_datatype_for(7.2)
DECIMAL(precision=2, scale=1)
>>> sqla_datatype_for("Jan 17 2012")
<class 'sqlalchemy.sql.sqltypes.DATETIME'>
>>> sqla_datatype_for("something else")
Unic... | Implement a function in Python 3 to
give a scalar Python value picks an appropriate SQLAlchemy data type. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate a single table. | Can you tell what is the following Python 3 function doing
def generate_one(tbl, args, table_name=None, file=None):
table = Table(tbl, table_name=table_name, varying_length_text=args.text, uniques=args.uniques,
pk_name = args.key, force_pk=args.force_key, reorder=args.reorder, data_size_cushion=ar... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates DDL from data sources named in args. | Here you have a function in Python 3, explain what it does
def generate(args=None, namespace=None, file=None):
if hasattr(args, 'split'):
args = args.split()
args = parser.parse_args(args, namespace)
set_logging(args)
logging.info(str(args))
if args.dialect in ('pg', 'pgsql', 'postgres'):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Set database sequence objects to match the source db
ATTRI. Relevant only when generated from SQLAlchemy connection. | Here you have a function in Python 3, explain what it does
def emit_db_sequence_updates(engine):
if engine and engine.name == 'postgresql':
# not implemented for other RDBMS; necessity unknown
conn = engine.connect()
qry = """SELECT 'SELECT last_value FROM ' || n.nspname ||
... | As a python code expert, you are capable of creating scripts from specifications. |
def ddl(self, dialect=None, creates=True, drops=True):
"""
Returns SQL to define the table.
"""
dialect = self._dialect(dialect)
creator = CreateTable(self.table).compile(mock_engines[dialect])
creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remov... | Can you implement a function in Python 3 that
returns the SQL to define the table. | As a python code expert, you are capable of creating scripts from specifications. |
def sqlalchemy(self, is_top=True):
"""Dumps Python code to set up the table's SQLAlchemy model"""
table_def = self.table_backref_remover.sub('', self.table.__repr__())
# inject UNIQUE constraints into table definition
constraint_defs = []
for constraint in self.table.constraint... | Write a Python 3 script for
dumping Python code to set up the table s SQLAlchemy model | You are a Python code generator, capable of creating scripts from specifications. |
Puts a value in proper format for a SQL string | Can you generate the documentation for the following Python 3 function
def _prep_datum(self, datum, dialect, col, needs_conversion):
if datum is None or (needs_conversion and not str(datum).strip()):
return 'NULL'
pytype = self.columns[col]['pytype']
if needs_conversion:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def emit_db_sequence_updates(self):
"""Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection.
Needed to avoid subsequent unique key violations after DB build."""
if self.source.db_engine and self.source.db_engine.name != 'pos... | Create a Python 3 function to
set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. | As a Python code analyst, you investigate and solve complex coding mysteries |
def sql(self, dialect=None, inserts=False, creates=True,
drops=True, metadata_source=None):
"""
Combined results of ``.ddl(dialect)`` and, if ``inserts==True``,
``.inserts(dialect)``.
"""
result = [self.ddl(dialect, creates=creates, drops=drops)]
if inserts:
... | Create a Python 3 function for
returning a SQL string that can be used to create or update a record set. | As a Python code composer, you craft elegant and concise scripts. |
Cleans a key name for use in SQL table and column names. | Can you tell what is the following Python 3 function doing
def clean_key_name(key):
result = _illegal_in_column_name.sub("_", key.strip())
if result[0].isdigit():
result = '_%s' % result
if result.upper() in sql_reserved_words:
result = '_%s' % key
return result.lower() | You are a Python code analyst, evaluating scripts for potential improvements. |
Find the field name from a dict likeliest to be its unique ID
| Can you generate a brief explanation for the following Python 3 code
def _id_fieldname(fieldnames, table_name = ''):
templates = ['%s_%%s' % table_name, '%s', '_%s']
for stub in ['id', 'num', 'no', 'number']:
for t in templates:
if t % stub in fieldnames:
return t % stub | As a Python code translator, you convert algorithms and pseudocode into Python. |
Unnest a child dictionary. | Can you tell what is the following Python 3 function doing
def unnest_child_dict(parent, key, parent_name=''):
val = parent[key]
name = "%s['%s']" % (parent_name, key)
logging.debug("Unnesting dict %s" % name)
id = _id_fieldname(val, parent_name)
if id:
logging.debug("%s is %s's ID" % (id, k... | As a Python code composer, you craft elegant and concise scripts. |
def suitability_as_key(self, key_name):
"""
Returns: (result, key_type)
``result`` is True, False, or 'absent' or 'partial' (both still usable)
``key_type`` is ``int`` for integer keys or ``str`` for hash keys
"""
pk_values = all_values_for(self, key_name)
if not... | Can you write a function in Python 3 where it
returns a tuple of result and key_type for the given key name. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format
tgt_rep tpkt_rep tpkpkt_rep tpkt in EncryptionKey native format
t | Can you generate a brief explanation for the following Python 3 code
def to_tgt(self):
enc_part = EncryptedData({'etype': 1, 'cipher': b''})
tgt_rep = {}
tgt_rep['pvno'] = krb5_pvno
tgt_rep['msg-type'] = MESSAGE_TYPE.KRB_AS_REP.value
tgt_rep['crealm'] = self.server.realm.to_string()
tgt_rep['cname'] = se... | As a python code expert, you are capable of creating scripts from specifications. |
This function adds a credential object from the TGT and adds it to the ccache file. | Can you tell what is the following Python 3 function doing
def add_tgt(self, as_rep, enc_as_rep_part, override_pp = True): #from AS_REP
c = Credential()
c.client = CCACHEPrincipal.from_asn1(as_rep['cname'], as_rep['crealm'])
if override_pp == True:
self.primary_principal = c.client
c.server = CCACHEPrincipal... | As a Python code composer, you craft elegant and concise scripts. |
This function adds a credential object from the TGS_REP data and adds it to the ccache file. | Given the following Python 3 function, write the documentation
def add_tgs(self, tgs_rep, enc_tgs_rep_part, override_pp = False): #from AS_REP
c = Credential()
c.client = CCACHEPrincipal.from_asn1(tgs_rep['cname'], tgs_rep['crealm'])
if override_pp == True:
self.primary_principal = c.client
c.server = CCACHE... | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a Kirbi credential to the cache. | Can you tell what is the following Python 3 function doing
def add_kirbi(self, krbcred, override_pp = True, include_expired = False):
c = Credential()
enc_credinfo = EncKrbCredPart.load(krbcred['enc-part']['cipher']).native
ticket_info = enc_credinfo['ticket-info'][0]
"""
if ticket_info['endtime'] < dateti... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_hashes(self, all_hashes = False):
"""
Returns a list of hashes in hashcat-firendly format for tickets with encryption type 23 (which is RC4)
all_hashes: overrides the encryption type filtering and returns hash for all tickets
"""
hashes = []
for cred in self.credentials:
res = Ticket.load(cred.t... | Implement a function in Python 3 to
return a list of hashes in hashcat - firendly format for tickets with encryption type 23 which is RC4 | You are a Python code generator, capable of creating scripts from specifications. |
Reads all. kirbi files in a given directory and converts all of them into one CCACHE object and returns it | Explain what the following Python 3 code does
def from_kirbidir(directory_path):
cc = CCACHE()
dir_path = os.path.join(os.path.abspath(directory_path), '*.kirbi')
for filename in glob.glob(dir_path):
with open(filename, 'rb') as f:
kirbidata = f.read()
kirbi = KRBCRED.load(kirbidata).native
cc.add_... | As a python code expert, you are capable of creating scripts from specifications. |
def to_kirbidir(self, directory_path):
"""
Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz.
The kirbi file format supports one credential per file, so prepare for a lot of files being generated.
directory_path: str the directory to write the kirbi files to
"""
... | Write a Python 3 script for
converting all credential objects in the CCACHE object to the kirbi file format used by mimikatz. | You are a Python code generator, capable of creating scripts from specifications. |
Writes the contents of the CCACHE object to a file | Can you generate a brief explanation for the following Python 3 code
def to_file(self, filename):
with open(filename, 'wb') as f:
f.write(self.to_bytes()) | As a Python code composer, you craft elegant and concise scripts. |
def print_table(lines, separate_head=True):
"""Prints a formatted table given a 2 dimensional array"""
#Count the column width
widths = []
for line in lines:
for i,size in enumerate([len(x) for x in line]):
while i >= len(widths):
widths.append(0)
if size > widths[i]:
widths[i] = size
... | Write a Python 3 function for
printing a formatted table given a 2 dimensional array | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the encryption key bytes for the enctryption type. | Explain what the following Python 3 code does
def get_key_for_enctype(self, etype):
if etype == EncryptionType.AES256_CTS_HMAC_SHA1_96:
if self.kerberos_key_aes_256:
return bytes.fromhex(self.kerberos_key_aes_256)
if self.password is not None:
salt = (self.domain.upper() + self.username).encode()
re... | As a Python code composer, you craft elegant and concise scripts. |
def from_connection_string(s):
"""
Credential input format:
<domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname>
"""
cred = KerberosCredential()
cred.domain, t = s.split('/', 1)
cred.username, t = t.split('/', 1)
secret_type, t = t.split(':', 1)
secret, target = t.rsplit('@', 1)
st =... | Implement a function in Python 3 to
create a KerberosCredential object from a connection string. | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is used to send a TGT request to the Kerberos server. | Can you generate the documentation for the following Python 3 function
def run(self, realm, users):
existing_users = []
for user in users:
logging.debug('Probing user %s' % user)
req = KerberosUserEnum.construct_tgt_req(realm, user)
rep = self.ksoc.sendrecv(req.dump(), throw = False)
if rep.name != ... | As a Python code composer, you craft elegant and concise scripts. |
This method is called by the client to request the TGT tickets for all users specified in the targets. | Given the following Python 3 function, write the documentation
def run(self, creds, override_etype = [23]):
tgts = []
for cred in creds:
try:
kcomm = KerbrosComm(cred, self.ksoc)
kcomm.get_TGT(override_etype = override_etype, decrypt_tgt = False)
tgts.append(kcomm.kerberos_TGT)
except Exception as... | You are a Python code architect, reviewing and designing scalable and efficient code |
def run(self, targets, override_etype = [2, 3, 16, 23, 17, 18]):
"""
Requests TGS tickets for all service users specified in the targets list
targets: list : the SPN users to request the TGS tickets for
allhash: bool : Return all enctype tickets, ot just 23
"""
if not self.kcomm:
try:
self.kcomm = Ke... | How would you implement a function in Python 3 that
requests TGS tickets for all service users specified in the targets list targets: list : the SPN users to request the TGS tickets for allhash: bool : Return all enctype tickets, ot just 23 | You are a Python code analyst, evaluating scripts for potential improvements. |
Run the PBKDF2 algorithm
and return the derived key. | Can you generate the documentation for the following Python 3 function
def pbkdf2(password, salt, iters, keylen, digestmod = hashlib.sha1):
h = hmac.new(password, digestmod=digestmod)
def prf(data):
hm = h.copy()
hm.update(data)
return bytearray(hm.digest())
key = bytearray()
i = 1
while len(key) < keylen:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_connection_string(s, soc_type = KerberosSocketType.TCP):
"""
<credentials>@<ip_or_hostname>:<port>
"""
ip = None
port = 88
t, addr = s.rsplit('@')
if addr.find(':') == -1:
ip = addr
else:
ip, port = addr.split(':')
return KerberosSocket(ip, port = int(port), soc_type = soc_type) | Can you implement a function in Python 3 that
creates a KerberosSocket object from a connection string. | You are a Python code generator, capable of creating scripts from specifications. |
def from_tgt(ksoc, tgt, key):
"""
Sets up the kerberos object from tgt and the session key.
Use this function when pulling the TGT from ccache file.
"""
kc = KerbrosComm(None, ksoc)
kc.kerberos_TGT = tgt
kc.kerberos_cipher_type = key['keytype']
kc.kerberos_session_key = Key(kc.kerberos_cipher_type, k... | Implement a function in Python 3 to
set up the kerberos object from tgt and the session key. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.