output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Parse a subscription list and return a dict containing the results. | Make a summary of the following Python 3 code
def parse(parse_obj, agent=None, etag=None, modified=None, inject=False):
guarantees = common.SuperDict({
'bozo': 0,
'feeds': [],
'lists': [],
'opportunities': [],
'meta': common.SuperDict(),
'version': '',
})
fil... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a new object for all image and category combinations in a fixmat. | Here you have a function in Python 3, explain what it does
def FixmatStimuliFactory(fm, loader):
# Find all feature names
features = []
if loader.ftrpath:
assert os.access(loader.ftrpath, os.R_OK)
features = os.listdir(os.path.join(loader.ftrpath, str(fm.category[0])))
# Find all ima... | As a Python code composer, you craft elegant and concise scripts. |
This function creates a directory - independent structure for the given folder - and image - files. | Can you tell what is the following Python 3 function doing
def DirectoryStimuliFactory(loader):
impath = loader.impath
ftrpath = loader.ftrpath
# checks whether user has reading permission for the path
assert os.access(impath, os.R_OK)
assert os.access(ftrpath, os.R_OK)
# EXTRACTING IMAGE N... | You are a Python code architect, reviewing and designing scalable and efficient code |
Filter the fixmat such that it only contains fixations on images
in categories that are also in the categories object. | Can you tell what is the following Python 3 function doing
def fixations(self):
''' Filter the fixmat such that it only contains fixations on images
in categories that are also in the categories object'''
if not self._fixations:
raise RuntimeError('This Images object does not have'
... | As a python code expert, you are capable of creating scripts from specifications. |
Saves a new image to disk | Make a summary of the following Python 3 code
def data(self, value):
self.loader.save_image(self.category, self.image, value) | As a python code expert, you are capable of creating scripts from specifications. |
def fixations(self):
"""
Returns all fixations that are on this image.
A precondition for this to work is that a fixmat
is associated with this Image object.
"""
if not self._fixations:
raise RuntimeError('This Images object does not have'
+' ... | Write a Python 3 function for
returning a list of fixations that are associated with this image. | As a Python code analyst, you investigate and solve complex coding mysteries |
def prepare_data(fm, max_back, dur_cap=700):
'''
Computes angle and length differences up to given order and deletes
suspiciously long fixations.
Input
fm: Fixmat
Fixmat for which to comput angle and length differences
max_back: Int
Computes delta angle and ampli... | Write a Python 3 function for
preparing data for a single set of fixmat objects. | You are a Python code generator, capable of creating scripts from specifications. |
def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""
durations_per_da = np.nan * np.ones((len(e_angle) - 1,))
for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])):
idx... | Write a Python 3 function that can
compute the mean fixation duration at forward angles. | As a Python code composer, you craft elegant and concise scripts. |
def ior_effect(durations, angle_diffs, length_diffs,
summary_stat=np.mean, parallel=True, min_samples=20):
"""
Computes a measure of fixation durations at delta angle and delta
length combinations.
"""
raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object)
for a, (a_... | Can you write a function in Python 3 where it
computes a measure of fixation durations at delta angle and delta length combinations. | You are a Python code generator, capable of creating scripts from specifications. |
Predicts fixtaion durations for a fixmat. | Explain what the following Python 3 code does
def predict_fixation_duration(
durations, angles, length_diffs, dataset=None, params=None):
"""
Fits a non-linear piecewise regression to fixtaion durations for a fixmat.
Returns corrected fixation durations.
"""
if dataset is None:
data... | As a Python code analyst, you investigate and solve complex coding mysteries |
def subject_predictions(fm, field='SUBJECTINDEX',
method=predict_fixation_duration, data=None):
'''
Calculates the saccadic momentum effect for individual subjects.
Removes any effect of amplitude differences.
The parameters are fitted on unbinned data. The effects are
comp... | Can you implement a function in Python 3 that
calculates the saccadic momentum effect for individual subjects. | You are a Python code architect, reviewing and designing scalable and efficient code |
This function calculates the fixation density map from a set of subjects on a set of images and predicting the set of subjects on a set of images. | How would you explain what the following Python 3 function does
def intersubject_scores(fm, category, predicting_filenumbers,
predicting_subjects, predicted_filenumbers,
predicted_subjects, controls = True, scale_factor = 1):
"""
Calculates how well the fixations ... | As a Python code composer, you craft elegant and concise scripts. |
def intersubject_scores_random_subjects(fm, category, filenumber, n_train,
n_predict, controls=True,
scale_factor = 1):
"""
Calculates how well the fixations of n random subjects on one image can
be predicted with the fixations ... | Create a Python 3 function for
functioning that uses intersubject_auc to compute the scores of random subjects on one image can be predicted with the fixations of m other random subjects. | As a Python code composer, you craft elegant and concise scripts. |
def upper_bound(fm, nr_subs = None, scale_factor = 1):
"""
compute the inter-subject consistency upper bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1... | Write a Python 3 function that can
compute the inter - subject consistency upper bound for a fixmat instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def lower_bound(fm, nr_subs = None, nr_imgs = None, scale_factor = 1):
"""
Compute the spatial bias lower bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minu... | Implement a function in Python 3 to
compute the spatial bias lower bound for a fixmat instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates subscripts for indices into regularly spaced matrixes. | Make a summary of the following Python 3 code
def ind2sub(ind, dimensions):
# check that the index is within range
if ind >= np.prod(dimensions):
raise RuntimeError("ind2sub: index exceeds array size")
cum_dims = list(dimensions)
cum_dims.reverse()
m = 1
mult = []
for d in cum_dims:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
A sub2ind implementation to create randomization
scripts. This function calculates indices from subscripts into regularly spaced
matrixes. | Can you generate a brief explanation for the following Python 3 code
def sub2ind(indices, dimensions):
# check that none of the indices exceeds the size of the array
if any([i > j for i, j in zip(indices, dimensions)]):
raise RuntimeError("sub2ind:an index exceeds its dimension's size")
dims = list(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Restores a task store from file. | How would you explain what the following Python 3 function does
def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file):
intm_results = np.load(restore_file)
intm = intm_results[intm_results.files[0]]
idx = np.isnan(intm).flatten().nonzero()[0]
partitions = math.ceil(len(idx) / flo... | As a python code expert, you are capable of creating scripts from specifications. |
Reschedule all running tasks. | Explain what the following Python 3 code does
def xmlrpc_reschedule(self):
if not len(self.scheduled_tasks) == 0:
self.reschedule = list(self.scheduled_tasks.items())
self.scheduled_tasks = {}
return True | As a Python code analyst, you investigate and solve complex coding mysteries |
def xmlrpc_get_task(self):
"""
Return a new task description: ID and necessary parameters,
all are given in a dictionary
"""
try:
if len(self.reschedule) == 0:
(task_id, cur_task) = next(self.task_iterator)
else:
(task_id, ... | Implement a function in Python 3 to
return a new task description | You are a Python code generator, capable of creating scripts from specifications. |
def xmlrpc_task_done(self, result):
"""
Take the results of a computation and put it into the results list.
"""
(task_id, task_results) = result
del self.scheduled_tasks[task_id]
self.task_store.update_results(task_id, task_results)
self.results += 1
retur... | Can you implement a function in Python 3 that
calls when the task is done. | As a python code expert, you are capable of creating scripts from specifications. |
Return a status message for the current process | Can you generate the documentation for the following Python 3 function
def xmlrpc_status(self):
return ("""
%i Jobs are still wating for execution
%i Jobs are being processed
%i Jobs are done
""" %(self.task_store.partitions -
self.results -
len(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Save results and own state into file. | Can you generate a brief explanation for the following Python 3 code
def xmlrpc_save2file(self, filename):
savefile = open(filename,'wb')
try:
pickle.dump({'scheduled':self.scheduled_tasks,
'reschedule':self.reschedule},savefile)
except pickle.PicklingError:... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is called to start the computation. | Can you generate a brief explanation for the following Python 3 code
def run(self):
(task_id, tasks) = self.server.get_task()
self.task_store.from_dict(tasks)
for (index, task) in self.task_store:
result = self.compute(index, task)
self.results.append(result)
self... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Configures the task store to be the task_store described
in description | Given the following Python 3 function, write the documentation
def from_dict(self, description):
assert(self.ident == description['ident'])
self.partitions = description['partitions']
self.indices = description['indices'] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fit3d(samples, e_x, e_y, e_z, remove_zeros = False, **kw):
"""Fits a 3D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e_x: Array
Edges that define the events in the probability
distribution along the x ... | Create a Python 3 function for
fitting a 3D distribution with splines. | You are a Python code architect, reviewing and designing scalable and efficient code |
Fits a 2D distribution with splines. | Can you generate the documentation for the following Python 3 function
def fit2d(samples,e_x, e_y, remove_zeros = False, p_est = None, **kw):
if p_est is None:
height = len(e_y)-1
width = len(e_x)-1
(p_est, _) = np.histogramdd(samples, (e_x, e_y))
else:
p_est = p_est.T
... | As a Python code composer, you craft elegant and concise scripts. |
def fit1d(samples, e, remove_zeros = False, **kw):
"""Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= ... | Can you write a function in Python 3 where it
fits a 1D distribution with splines. | You are a Python code analyst, evaluating scripts for potential improvements. |
This function calculates the knot placement based on a marginal distribution. | Explain what the following Python 3 code does
def knots_from_marginal(marginal, nr_knots, spline_order):
cumsum = np.cumsum(marginal)
cumsum = cumsum/cumsum.max()
borders = np.linspace(0,1,nr_knots)
knot_placement = [0] + np.unique([np.where(cumsum>=b)[0][0] for b in borders[1:-1]]).tolist() +[len(margi... | As a Python code analyst, you investigate and solve complex coding mysteries |
def spline_base1d(length, nr_knots = 20, spline_order = 5, marginal = None):
"""Computes a 1D spline basis
Input:
length: int
length of each basis
nr_knots: int
Number of knots, i.e. number of basis functions.
spline_order: int
Order of the splin... | How would you implement a function in Python 3 that
computes a 1D spline base for each entry in the list of knots. | As a Python code analyst, you investigate and solve complex coding mysteries |
Computes a set of 2D spline functions that cover the entire space in width and height. | How would you explain what the following Python 3 function does
def spline_base2d(width, height, nr_knots_x = 20.0, nr_knots_y = 20.0,
spline_order = 5, marginal_x = None, marginal_y = None):
"""Computes a set of 2D spline basis functions.
The basis functions cover the entire space in height*widt... | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes a set of 3D spline functions. | Given the following Python 3 function, write the documentation
def spline_base3d( width, height, depth, nr_knots_x = 10.0, nr_knots_y = 10.0,
nr_knots_z=10, spline_order = 3, marginal_x = None, marginal_y = None,
marginal_z = None):
"""Computes a set of 3D spline basis functions.
For a de... | You are a Python code generator, capable of creating scripts from specifications. |
def spline(x,knots,p,i=0.0):
"""Evaluates the ith spline basis given by knots on points in x"""
assert(p+1<len(knots))
return np.array([N(float(u),float(i),float(p),knots) for u in x]) | How would you code a function in Python 3 to
evaluate the ith spline basis given by knots on points in x | You are a Python code architect, reviewing and designing scalable and efficient code |
Computes the spline colocation matrix for knots in x. | Make a summary of the following Python 3 code
def spcol(x,knots,spline_order):
colmat = np.nan*np.ones((len(x),len(knots) - spline_order-1))
for i in range(0,len(knots) - spline_order -1):
colmat[:,i] = spline(x,knots,spline_order,i)
return colmat | You are a Python code analyst, evaluating scripts for potential improvements. |
Augment knot sequence such that some boundary conditions
are met. | Can you generate a brief explanation for the following Python 3 code
def augknt(knots,order):
a = []
[a.append(knots[0]) for t in range(0,order)]
[a.append(k) for k in knots]
[a.append(knots[-1]) for t in range(0,order)]
return np.array(a) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def N(u,i,p,knots):
"""Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[i] < u and u <=knots[i+1]:
return 1.0
else:
return 0.0
else:
try:
k = (( float((u-kn... | Implement a Python 3 function for
computing the spline basis of order p at knot i and point u. | As a python code expert, you are capable of creating scripts from specifications. |
Evaluates a prediction against a fixmat with different measures. | How would you explain what the following Python 3 function does
def prediction_scores(prediction, fm, **kw):
if prediction == None:
return [np.NaN for measure in scores]
results = []
for measure in scores:
(args, _, _, _) = inspect.getargspec(measure)
if len(args)>2:
# Fi... | As a python code expert, you are capable of creating scripts from specifications. |
def kldiv_model(prediction, fm):
"""
wraps kldiv functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Should be filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, ... | Create a Python 3 function for
evaluating the kldiv function for model evaluation | As a python code expert, you are capable of creating scripts from specifications. |
Computes the Kullback - Leibler divergence between two distributions. | Explain what the following Python 3 code does
def kldiv(p, q, distp = None, distq = None, scale_factor = 1):
assert q != None or distq != None, "Either q or distq have to be given"
assert p != None or distp != None, "Either p or distp have to be given"
try:
if p == None:
p = compute_fdm... | As a Python code composer, you craft elegant and concise scripts. |
def kldiv_cs_model(prediction, fm):
"""
Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object
"""
# compute histogram of fixations needed for Cha... | How would you implement a function in Python 3 that
computes Chao - Shen corrected KL - divergence between prediction and fdm made from fixations in fm. | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes some terms needed for Chao - Shen KL correction. | Can you generate a brief explanation for the following Python 3 code
def chao_shen(q):
yx = q[q > 0] # remove bins with zero counts
n = np.sum(yx)
p = yx.astype(float)/n
f1 = np.sum(yx == 1) # number of singletons in the sample
if f1 == n: # avoid C == 0
f1 -= 1
C = 1 - (f1/n) # estimate... | As a Python code composer, you craft elegant and concise scripts. |
computes the FDM and correlation model for a 2D Matrix
| Here you have a function in Python 3, explain what it does
def correlation_model(prediction, fm):
(_, r_x) = calc_resize_factor(prediction, fm.image_size)
fdm = compute_fdm(fm, scale_factor = r_x)
return np.corrcoef(fdm.flatten(), prediction.flatten())[0,1] | You are a Python code generator, capable of creating scripts from specifications. |
def nss_model(prediction, fm):
"""
wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals
"""
(r_y, r_x) = calc_resize_factor(prediction, fm.image_size)
fix = ((np.arr... | Can you create a Python 3 function that
wraps nss functionality for model evaluation input : 2D matrix the model salience map the model salience map the model salience map the fixmat | You are a Python code analyst, evaluating scripts for potential improvements. |
def nss(prediction, fix):
"""
Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x
"""
prediction = prediction - np.mean(prediction)
prediction = prediction / np.std(prediction)
return np.mean(prediction[fix[0], fix[1]]) | Can you write a function in Python 3 where it
computes the normalized scanpath salience input : list of y - values | You are a Python code generator, capable of creating scripts from specifications. |
def roc_model(prediction, fm, ctr_loc = None, ctr_size = None):
"""
wraps roc functionality for model evaluation
Parameters:
prediction: 2D array
the model salience map
fm : fixmat
Fixations that define locations of the actuals
ctr_loc : tuple of (y.x) coordi... | Write a Python 3 function that can
wrap roc functionality for model evaluation Parameters: prediction: 2D array the model salience map fm : fixmat Fixations that define locations of the actuals ctr_loc : tuple of (y.x) coordinates, optional Allows to specify control points for spatial bias correction ctr_size : two ele... | You are a Python code architect, reviewing and designing scalable and efficient code |
def fast_roc(actuals, controls):
"""
approximates the area under the roc curve for sets of actuals and controls.
Uses all values appearing in actuals as thresholds and lower sum
interpolation. Also returns arrays of the true positive rate and the false
positive rate that can be used for plotting the... | Can you write a function in Python 3 where it
calculates the area under the roc curve for a set of actuals and controls. | As a Python code analyst, you investigate and solve complex coding mysteries |
This method is used to compute the AUC unde ROC curve. | Given the following Python 3 function, write the documentation
def faster_roc(actuals, controls):
assert(type(actuals) is np.ndarray)
assert(type(controls) is np.ndarray)
if len(actuals)<500:
raise RuntimeError('This method might be incorrect when '+
'not enough actuals are present.... | As a Python code composer, you craft elegant and concise scripts. |
def emd_model(prediction, fm):
"""
wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, fm... | Write a Python 3 script to
return an emd model for the given model salience map | As a python code expert, you are capable of creating scripts from specifications. |
def emd(prediction, ground_truth):
"""
Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. Th... | How would you code a function in Python 3 to
compute the Eart Movers Distance between prediction and model. | As a Python code composer, you craft elegant and concise scripts. |
Parse a date string into a sequence of time and timezone names. | Can you generate a brief explanation for the following Python 3 code
def _rfc822(date):
daynames = set(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])
months = {
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
}
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
_to_rfc822 - Convert a datetime. datetime object to a RFC822 - formatted string. | Given the following Python 3 function, write the documentation
def _to_rfc822(date):
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
fmt = '{day}, {d:02} {month} {y:04} {h:02}:{m:02}:{s:02} G... | As a Python code analyst, you investigate and solve complex coding mysteries |
def format(self, sql, params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values ... | Can you create a Python 3 function that
formats the SQL query to use named parameters instead of ordinal parameters. | You are a Python code architect, reviewing and designing scalable and efficient code |
Formats the given SQL query with the given parameters. | Can you generate a brief explanation for the following Python 3 code
def formatmany(self, sql, many_params):
if isinstance(sql, unicode):
string_type = unicode
elif isinstance(sql, bytes):
string_type = bytes
sql = sql.decode(_BYTES_ENCODING)
else:
raise TypeError("sql:{!r} is not a unicode or byte st... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_parser(f):
"""
Gets the parser for the command f, if it not exists it creates a new one
"""
_COMMAND_GROUPS[f.__module__].load()
if f.__name__ not in _COMMAND_GROUPS[f.__module__].parsers:
parser = _COMMAND_GROUPS[f.__module__].parser_generator.add_parser(f.__name__, help=f.__doc__... | Can you create a Python 3 function that
gets the parser for the command f creates a new one if it does not exist | As a Python code translator, you convert algorithms and pseudocode into Python. |
def findMentions(sourceURL, targetURL=None, exclude_domains=[], content=None, test_urls=True, headers={}, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If an... | Write a Python 3 function that can
find all mentions in a given HTML page. | As a Python code composer, you craft elegant and concise scripts. |
def findEndpoint(html):
"""Search the given html content for all <link /> elements
and return any discovered WebMention URL.
:param html: html content
:rtype: WebMention URL
"""
poss_rels = ['webmention', 'http://webmention.org', 'http://webmention.org/', 'https://webmention.org', 'https://webm... | How would you implement a function in Python 3 that
searches the given html content for all links and return any discovered WebMention URL. | As a Python code composer, you craft elegant and concise scripts. |
def discoverEndpoint(url, test_urls=True, headers={}, timeout=None, request=None, debug=False):
"""Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with... | How would you code a function in Python 3 to
discover any endpoint for a given URL. | You are a Python code generator, capable of creating scripts from specifications. |
Send a WebMention to the targetURL. | Can you tell what is the following Python 3 function doing
def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None,
headers={}, timeout=None, debug=False):
"""Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_link_header(link):
"""takes the link header as a string and returns a dictionary with rel values as keys and urls as values
:param link: link header as a string
:rtype: dictionary {rel_name: rel_value}
"""
rel_dict = {}
for rels in link.split(','):
rel_break = quoted_split(rels... | Implement a Python 3 function for
taking the link header as a string and returns a dictionary with rel names as keys and urls as values | You are a Python code architect, reviewing and designing scalable and efficient code |
def findRelMe(sourceURL):
"""Find all <a /> elements in the given html for a post.
If any have an href attribute that is rel="me" then include
it in the result.
:param sourceURL: the URL for the post we are scanning
:rtype: dictionary of RelMe references
"""
r = requests.get(sourceURL)
... | Can you write a function in Python 3 where it
finds all links that are rel = me and include them in the result. | You are a Python code analyst, evaluating scripts for potential improvements. |
def confirmRelMe(profileURL, resourceURL, profileRelMes=None, resourceRelMes=None):
"""Determine if a given :resourceURL: is authoritative for the :profileURL:
TODO add https/http filtering for those who wish to limit/restrict urls to match fully
TODO add code to ensure that each item in the redirect chain... | Write a Python 3 function that can
check if a given resource URL is authoritative for the given profile URL. | You are a Python code generator, capable of creating scripts from specifications. |
Indent every line of text in a newline - delimited string | Can you generate the documentation for the following Python 3 function
def indent_text(string, indent_level=2):
indented_lines = []
indent_spaces = ' ' * indent_level
for line in string.split('\n'):
indented_lines.append(indent_spaces + line)
return '\n'.join(indented_lines) | You are a Python code architect, reviewing and designing scalable and efficient code |
def download(url, target, headers=None, trackers=()):
"""Download a file using requests.
This is like urllib.request.urlretrieve, but:
- requests validates SSL certificates by default
- you can pass tracker objects to e.g. display a progress bar or calculate
a file hash.
"""
if headers i... | Can you implement a function in Python 3 that
downloads a file using requests. | As a Python code composer, you craft elegant and concise scripts. |
def write(parsed_obj, spec=None, filename=None):
"""Writes an object created by `parse` to either a file or a bytearray.
If the object doesn't end on a byte boundary, zeroes are appended to it
until it does.
"""
if not isinstance(parsed_obj, BreadStruct):
raise ValueError(
'Obje... | Can you create a Python 3 function that
writes an object created by parse to either a file or a bytearray. | As a python code expert, you are capable of creating scripts from specifications. |
Uploads a file to an S3 bucket as a public file. | Can you generate a brief explanation for the following Python 3 code
def deploy_file(file_path, bucket):
# Paths look like:
# index.html
# css/bootstrap.min.css
logger.info("Deploying {0}".format(file_path))
# Upload the actual file to file_path
k = Key(bucket)
k.key = file_path
try... | As a Python code analyst, you investigate and solve complex coding mysteries |
Deploy all files in www_dir to the configured S3 bucket. | Given the following Python 3 function, write the documentation
def deploy(www_dir, bucket_name):
# Set up the connection to an S3 bucket.
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
# Deploy each changed file in www_dir
os.chdir(www_dir)
for root, dirs, files in os.walk('.')... | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks if a file has changed since the last time it was deployed. | Can you generate the documentation for the following Python 3 function
def has_changed_since_last_deploy(file_path, bucket):
msg = "Checking if {0} has changed since last deploy.".format(file_path)
logger.debug(msg)
with open(file_path) as f:
data = f.read()
file_md5 = hashlib.md5(data.enco... | As a python code expert, you are capable of creating scripts from specifications. |
Entry point for the package. | Can you generate the documentation for the following Python 3 function
def main():
# Log info and above to console
logging.basicConfig(
format='%(levelname)s: %(message)s', level=logging.INFO)
# Get command line input/output arguments
msg = 'Instantly deploy static HTML sites to S3 at the comm... | You are a Python code analyst, evaluating scripts for potential improvements. |
def start_sikuli_process(self, port=None):
"""
This keyword is used to start sikuli java process.
If library is inited with mode "OLD", sikuli java process is started automatically.
If library is inited with mode "NEW", this keyword should be used.
:param port: port of sikuli ja... | Create a Python 3 function to
start sikuli java process. | As a Python code analyst, you investigate and solve complex coding mysteries |
def post(self, request):
"""Respond to POSTed username/password with token."""
serializer = AuthTokenSerializer(data=request.data)
if serializer.is_valid():
token, _ = ExpiringToken.objects.get_or_create(
user=serializer.validated_data['user']
)
... | Write a Python 3 script to
respond to POSTed username / password with token. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the allowed lifespan of a token as a TimeDelta object. Defaults to 30 days. | How would you explain what the following Python 3 function does
def EXPIRING_TOKEN_LIFESPAN(self):
try:
val = settings.EXPIRING_TOKEN_LIFESPAN
except AttributeError:
val = timedelta(days=30)
return val | As a python code expert, you are capable of creating scripts from specifications. |
Return boolean indicating token expiration. | Can you generate the documentation for the following Python 3 function
def expired(self):
now = timezone.now()
if self.created < now - token_settings.EXPIRING_TOKEN_LIFESPAN:
return True
return False | As a Python code analyst, you investigate and solve complex coding mysteries |
Test if a string is entirely of punctuation. | Can you generate a brief explanation for the following Python 3 code
def unicode_is_punctuation(text):
for char in str_func(text):
category = unicodedata.category(char)[0]
if category not in 'PSZMC':
return False
return True | As a Python code composer, you craft elegant and concise scripts. |
Returns the actual process of the current object. | Can you generate a brief explanation for the following Python 3 code
def process(self):
if hasattr(self, '_process'):
return self._process
else:
self._process = self._get_process()
return self._process | As a python code expert, you are capable of creating scripts from specifications. |
def _get_process(self):
"""
Create the process by running the specified command.
"""
command = self._get_command()
return subprocess.Popen(command, bufsize=-1, close_fds=True,
stdout=subprocess.PIPE,
stdin=subprocess... | How would you code a function in Python 3 to
create a process by running the specified command. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def tokenize_list(self, text):
"""
Split a text into separate words.
"""
return [self.get_record_token(record) for record in self.analyze(text)] | How would you implement a function in Python 3 that
splits a text into separate words. | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_stopword(self, text):
"""
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which word... | Implement a function in Python 3 to
determine whether a single word is a stopword. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a canonical list representation of text with words
separated and reduced to their base forms. | Can you generate the documentation for the following Python 3 function
def normalize_list(self, text, cache=None):
words = []
analysis = self.analyze(text)
for record in analysis:
if not self.is_stopword_record(record):
words.append(self.get_record_root(record))
... | You are a Python code generator, capable of creating scripts from specifications. |
def tag_and_stem(self, text, cache=None):
"""
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function wo... | Create a Python 3 function for
giving some text return a sequence of stem pos and text. | As a Python code composer, you craft elegant and concise scripts. |
Given some text extract phrases of up to 2 content words and phrase. | Explain what the following Python 3 code does
def extract_phrases(self, text):
analysis = self.analyze(text)
for pos1 in range(len(analysis)):
rec1 = analysis[pos1]
if not self.is_stopword_record(rec1):
yield self.get_record_root(rec1), rec1[0]
for... | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_kana(text):
"""
Use MeCab to turn any text into its phonetic spelling, as katakana
separated by spaces.
"""
records = MECAB.analyze(text)
kana = []
for record in records:
if record.pronunciation:
kana.append(record.pronunciation)
elif record.reading:
... | Can you implement a function in Python 3 that
converts a text into a katakana string. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_kana_info(char):
"""
Return two things about each character:
- Its transliterated value (in Roman characters, if it's a kana)
- A class of characters indicating how it affects the romanization
"""
try:
name = unicodedata.name(char)
except ValueError:
return char, NOT... | Can you create a Python 3 function that
returns two things about each character in the kana base. | You are a Python code architect, reviewing and designing scalable and efficient code |
Runs a line of text through MeCab and returns the results as a list of lists of MeCabRecord objects. | Can you generate a brief explanation for the following Python 3 code
def analyze(self, text):
try:
self.process # make sure things are loaded
text = render_safe(text).replace('\n', ' ').lower()
results = []
for chunk in string_pieces(text):
self.s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_stopword_record(self, record):
"""
Determine whether a single MeCab record represents a stopword.
This mostly determines words to strip based on their parts of speech.
If common_words is set to True (default), it will also strip common
verbs and nouns such as くる and よう. I... | Can you write a function in Python 3 where it
determines whether a MeCab record represents a stopword. | You are a Python code generator, capable of creating scripts from specifications. |
Given a record return the word s part of speech. | Here you have a function in Python 3, explain what it does
def get_record_pos(self, record):
if self.is_stopword_record(record):
return '~' + record.pos
else:
return record.pos | You are a Python code architect, reviewing and designing scalable and efficient code |
Run the external process and get a list of lists
s that contain the analysis of each word. | Here you have a function in Python 3, explain what it does
def analyze(self, text):
try:
text = render_safe(text).strip()
if not text:
return []
chunks = text.split('\n')
results = []
for chunk_text in chunks:
if chunk_t... | As a python code expert, you are capable of creating scripts from specifications. |
Untokenizes a text into a single tokenised list. | Given the following Python 3 function, write the documentation
def untokenize(words):
text = ' '.join(words)
step1 = text.replace("`` ", '"').replace(" ''", '"').replace('. . .', '...')
step2 = step1.replace(" ( ", " (").replace(" ) ", ") ")
step3 = re.sub(r' ([.,:;?!%]+)([ \'"`])', r"\1\2", step2)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Takes a unicode string and yields pieces of it. | Make a summary of the following Python 3 code
def string_pieces(s, maxlen=1024):
if not s:
return
i = 0
while True:
j = i + maxlen
if j >= len(s):
yield s[i:]
return
# Using "j - 1" keeps boundary characters with the left chunk
while unicodedat... | As a Python code composer, you craft elegant and concise scripts. |
def _word_badness(word):
"""
Assign a heuristic to possible outputs from Morphy. Minimizing this
heuristic avoids incorrect stems.
"""
if word.endswith('e'):
return len(word) - 2
elif word.endswith('ess'):
return len(word) - 10
elif word.endswith('ss'):
return len(wor... | Write a Python 3 function that can
assign a heuristic to possible outputs from Morphy. Minimizing this heuristic avoids incorrect stems. | You are a Python code generator, capable of creating scripts from specifications. |
def _morphy_best(word, pos=None):
"""
Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem().
"""
results = []
if pos is None:
pos = 'nvar'
for pos_item in pos:
results.extend(morphy(word, pos_item))
if not results:
... | Can you create a Python 3 function that
gets the most likely stem for a word using Morphy. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def morphy_stem(word, pos=None):
"""
Get the most likely stem for a word. If a part of speech is supplied,
the stem will be more accurate.
Valid parts of speech are:
- 'n' or 'NN' for nouns
- 'v' or 'VB' for verbs
- 'a' or 'JJ' for adjectives
- 'r' or 'RB' for adverbs
Any other pa... | How would you implement a function in Python 3 that
returns the most likely stem for a word. | You are a Python code architect, reviewing and designing scalable and efficient code |
def tag_and_stem(text):
"""
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
"""
tokens = tokenize(text)
tagged = nltk.pos_tag(tokens)
out = []
for token,... | Write a Python 3 script to
tag a text into words and return a list of triples that are tagged with the stem and the token. | As a python code expert, you are capable of creating scripts from specifications. |
Return a list of word stems that appear in the text. | Can you generate a brief explanation for the following Python 3 code
def normalize_list(text):
pieces = [morphy_stem(word) for word in tokenize(text)]
pieces = [piece for piece in pieces if good_lemma(piece)]
if not pieces:
return [text]
if pieces[0] == 'to':
pieces = pieces[1:]
retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Normalizes a Wikipedia topic. | Can you generate a brief explanation for the following Python 3 code
def normalize_topic(topic):
# find titles of the form Foo (bar)
topic = topic.replace('_', ' ')
match = re.match(r'([^(]+) \(([^)]+)\)', topic)
if not match:
return normalize(topic), None
else:
return normalize(matc... | You are a Python code architect, reviewing and designing scalable and efficient code |
def key2elements(key):
"""split key to elements"""
# words = key.split('.')
# if len(words) == 4:
# return words
# # there is a dot in object name
# fieldword = words.pop(-1)
# nameword = '.'.join(words[-2:])
# if nameword[-1] in ('"', "'"):
# # The object name is in quotes
... | Create a Python 3 function for
splitting key to elements | You are a Python code architect, reviewing and designing scalable and efficient code |
update idf using dct | Make a summary of the following Python 3 code
def updateidf(idf, dct):
for key in list(dct.keys()):
if key.startswith('idf.'):
idftag, objkey, objname, field = key2elements(key)
if objname == '':
try:
idfobj = idf.idfobjects[objkey.upper()][0]
... | As a python code expert, you are capable of creating scripts from specifications. |
def fan_bhp(fan_tot_eff, pascal, m3s):
"""return the fan power in bhp given fan efficiency, Pressure rise (Pa) and flow (m3/s)"""
# from discussion in
# http://energy-models.com/forum/baseline-fan-power-calculation
inh2o = pascal2inh2o(pascal)
cfm = m3s2cfm(m3s)
return (cfm * inh2o * 1.0) / (635... | How would you implement a function in Python 3 that
calculates fan power in bhp given the fan efficiency Pressure rise and flow | You are a Python code architect, reviewing and designing scalable and efficient code |
def bhp2pascal(bhp, cfm, fan_tot_eff):
"""return inputs for E+ in pascal and m3/s"""
inh2o = bhp * 6356.0 * fan_tot_eff / cfm
pascal = inh2o2pascal(inh2o)
m3s = cfm2m3s(cfm)
return pascal, m3s | Create a Python 3 function to
return inputs for E + in pascal and m3s | You are a Python code architect, reviewing and designing scalable and efficient code |
return the fan power in watts given the fan efficiency Pressure rise and flow | Make a summary of the following Python 3 code
def fan_watts(fan_tot_eff, pascal, m3s):
# got this from a google search
bhp = fan_bhp(fan_tot_eff, pascal, m3s)
return bhp2watts(bhp) | You are a Python code generator, capable of creating scripts from specifications. |
def watts2pascal(watts, cfm, fan_tot_eff):
"""convert and return inputs for E+ in pascal and m3/s"""
bhp = watts2bhp(watts)
return bhp2pascal(bhp, cfm, fan_tot_eff) | Implement a function in Python 3 to
convert and return inputs for E + in pascal and m3 / s | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.