text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_n_cluster_per_event_hist(cluster_table):
'''Calculates the number of cluster in every event.
Parameters
----------
cluster_table : pytables.table
Returns
-------
numpy.Histogram
'''
logging.info("Histogram number of cluster per event")
cluster_in_events = analysis_utils... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_data_statistics(interpreted_files):
'''Quick and dirty function to give as redmine compatible iverview table
'''
print '| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |' # Mean Tot | Mean rel. BCID'
for interpreted_file in interprete... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_bad_data(raw_data, prepend_data_headers=None, trig_count=None):
"""Checking FEI4 raw data array for corrupted data. """ |
consecutive_triggers = 16 if trig_count == 0 else trig_count
is_fe_data_header = logical_and(is_fe_word, is_data_header)
trigger_idx = np.where(is_trigger_word(raw_data) >= 1)[0]
fe_dh_idx = np.where(is_fe_data_header(raw_data) >= 1)[0]
n_triggers = trigger_idx.shape[0]
n_dh = fe_dh_idx.shape[0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_raw_data_file(input_file, start_index=0, limit=200, flavor='fei4b', select=None, tdc_trig_dist=False, trigger_data_mode=0, meta_data_v2=True):
"""Print... |
with tb.open_file(input_file + '.h5', mode="r") as file_h5:
if meta_data_v2:
index_start = file_h5.root.meta_data.read(field='index_start')
index_stop = file_h5.root.meta_data.read(field='index_stop')
else:
index_start = file_h5.root.meta_data.read(field='start_i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_raw_data(raw_data, start_index=0, limit=200, flavor='fei4b', index_offset=0, select=None, tdc_trig_dist=False, trigger_data_mode=0):
"""Printing FEI4 r... |
if not select:
select = ['DH', 'TW', "AR", "VR", "SR", "DR", 'TDC', 'UNKNOWN FE WORD', 'UNKNOWN WORD']
total_words = 0
for index in range(start_index, raw_data.shape[0]):
dw = FEI4Record(raw_data[index], chip_flavor=flavor, tdc_trig_dist=tdc_trig_dist, trigger_data_mode=trigger_data_mode)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def interval_timed(interval):
'''Interval timer decorator.
Taken from: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds/12435256
'''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
stopped = Event()
def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def interval_timer(interval, func, *args, **kwargs):
'''Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
'''
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is after interval
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send_mail(subject, body, smtp_server, user, password, from_addr, to_addrs):
''' Sends a run status mail with the traceback to a specified E-Mail address if a run crashes.
'''
logging.info('Send status E-Mail (' + subject + ')')
content = string.join((
"From: %s" % from_addr,
"To: %s"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _parse_module_cfgs(self):
''' Extracts the configuration of the modules.
'''
# Adding here default run config parameters.
if "dut" not in self._conf or self._conf["dut"] is None:
raise ValueError('Parameter "dut" not defined.')
if "dut_configuration" not in self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''Releasing hardware resources.
'''
try:
self.dut.close()
except Exception:
logging.warning('Closing DUT was not successful')
else:
logging.debug('Closed DUT') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_data(self, data, new_file=False, flush=True):
'''Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int))
'''
for i, module_id in enumerate(self._s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_err(self, exc):
'''Handling of Exceptions.
Parameters
----------
exc : list, tuple
Information of the exception of the format (type, value, traceback).
Uses the return value of sys.exc_info().
'''
if self.reset_rx_on_error and isinstanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_configuration(self, module_id, run_number=None):
''' Returns the configuration for a given module ID.
The working directory is searched for a file matching the module_id with the
given run number. If no run number is defined the last successfull run defines
the run number.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deselect_module(self):
''' Deselect module and cleanup.
'''
self._enabled_fe_channels = [] # ignore any RX sync errors
self._readout_fifos = []
self._filter = []
self._converter = []
self.dut['TX']['OUTPUT_ENABLE'] = 0
self._current_module_handle = No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def readout(self, *args, **kwargs):
''' Running the FIFO readout while executing other statements.
Starting and stopping of the FIFO readout is synchronized between the threads.
'''
timeout = kwargs.pop('timeout', 10.0)
self.start_readout(*args, **kwargs)
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start_readout(self, *args, **kwargs):
''' Starting the FIFO readout.
Starting of the FIFO readout is executed only once by a random thread.
Starting of the FIFO readout is synchronized between all threads reading out the FIFO.
'''
# Pop parameters for fifo_readout.start
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stop_readout(self, timeout=10.0):
''' Stopping the FIFO readout.
Stopping of the FIFO readout is executed only once by a random thread.
Stopping of the FIFO readout is synchronized between all threads reading out the FIFO.
'''
if self._scan_threads and self.current_module_ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_charge(max_tdc, tdc_calibration_values, tdc_pixel_calibration): # Return the charge from calibration
''' Interpolatet the TDC calibration for each pixel from 0 to max_tdc'''
charge_calibration = np.zeros(shape=(80, 336, max_tdc))
for column in range(80):
for row in range(336):
a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_charge_calibration(calibation_file, max_tdc):
''' Open the hit or calibration file and return the calibration per pixel'''
with tb.open_file(calibation_file, mode="r") as in_file_calibration_h5:
tdc_calibration = in_file_calibration_h5.root.HitOrCalibration[:, :, :, 1]
tdc_calibration_va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addEntry(self):
"""Add the `Plot pyBAR data`. entry to `Dataset` menu. """ |
export_icon = QtGui.QIcon()
pixmap = QtGui.QPixmap(os.path.join(PLUGINSDIR,
'csv/icons/document-export.png'))
export_icon.addPixmap(pixmap, QtGui.QIcon.Normal, QtGui.QIcon.On)
self.plot_action = QtGui.QAction(
translate('PlotpyBAR... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateDatasetMenu(self):
"""Update the `export` QAction when the Dataset menu is pulled down. This method is a slot. See class ctor for details. """ |
enabled = True
current = self.vtgui.dbs_tree_view.currentIndex()
if current:
leaf = self.vtgui.dbs_tree_model.nodeFromIndex(current)
if leaf.node_kind in (u'group', u'root group'):
enabled = False
self.plot_action.setEnabled(enabled) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self):
"""Export a given dataset to a `CSV` file. This method is a slot connected to the `export` QAction. See the :meth:`addEntry` method for details. ... |
# The PyTables node tied to the current leaf of the databases tree
current = self.vtgui.dbs_tree_view.currentIndex()
leaf = self.vtgui.dbs_tree_model.nodeFromIndex(current).node
data_name = leaf.name
hists_1d = ['HistRelBcid', 'HistErrorCounter', 'HistTriggerErrorCounter', 'Hi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send_meta_data(socket, conf, name):
'''Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf can be any config dictionary.
'''
meta_data = dict(
name=name,
conf=conf
)
try:
socket.send_json(meta_data, flag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def save_raw_data_from_data_queue(data_queue, filename, mode='a', title='', scan_parameters=None): # mode="r+" to append data, raw_data_file_h5 must exist, "w" to overwrite raw_data_file_h5, "a" to append data, if raw_data_file_h5 does not exist it is created
'''Writing raw data file from data queue
If you ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def worker(self, fifo):
'''Worker thread continuously filtering and converting data when data becomes available.
'''
logging.debug('Starting worker thread for %s', fifo)
self._fifo_conditions[fifo].acquire()
while True:
try:
data_tuple = self._f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def writer(self, index, no_data_timeout=None):
'''Writer thread continuously calling callback function for writing data when data becomes available.
'''
is_fe_data_header = logical_and(is_fe_word, is_data_header)
logging.debug('Starting writer thread with index %d', index)
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterable(item):
"""generate iterable from item, but leaves out strings
""" |
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
return item
else:
return [item] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_float_time():
'''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def groupby_dict(dictionary, key):
''' Group dict of dicts by key.
'''
return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), key=lambda name: dictionary[name][key])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_file_dir_up(filename, path=None, n=None):
'''Finding file in directory upwards.
'''
if path is None:
path = os.getcwd()
i = 0
while True:
current_path = path
for _ in range(i):
current_path = os.path.split(current_path)[0]
if os.path.isf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def set_standard_settings(self):
'''Set all settings to their standard values.
'''
if self.is_open(self.out_file_h5):
self.out_file_h5.close()
self.out_file_h5 = None
self._setup_clusterizer()
self.chunk_size = 3000000
self.n_injections = None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_tot_value(self, value):
"""Set maximum ToT value that is considered to be a hit""" |
self._max_tot_value = value
self.interpreter.set_max_tot(self._max_tot_value)
self.histogram.set_max_tot(self._max_tot_value)
self.clusterizer.set_max_hit_charge(self._max_tot_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_fields(self, result, field_name):
""" If Schema access, parse fields and build respective lists """ |
field_list = []
for key, value in result.get('schema', {}).get(field_name, {}).items():
if key not in field_list:
field_list.append(key)
return field_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_fields(self):
""" Builds a list of valid fields """ |
declared_fields = self.solr._send_request('get', ADMIN_URL)
result = decoder.decode(declared_fields)
self.field_list = self._parse_fields(result, 'fields')
# Build regular expressions to match dynamic fields.
# dynamic field names may have exactly one wildcard, either at
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_doc(self, doc, namespace, timestamp):
"""Reformats the given document before insertion into Solr. This method reformats the document in the following ... |
# Translate the _id field to whatever unique key we're using.
# _id may not exist in the doc, if we retrieved it from Solr
# as part of update.
if '_id' in doc:
doc[self.unique_key] = u(doc.pop("_id"))
# Update namespace and timestamp metadata
if 'ns' in do... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_update(self, doc, update_spec):
"""Override DocManagerBase.apply_update to have flat documents.""" |
# Replace a whole document
if not '$set' in update_spec and not '$unset' in update_spec:
# update_spec contains the new document.
# Update the key in Solr based on the unique_key mentioned as
# parameter.
update_spec['_id'] = doc[self.unique_key]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upsert(self, doc, namespace, timestamp):
"""Update or insert a document into Solr This method should call whatever add/insert/update method exists for the ba... |
if self.auto_commit_interval is not None:
self.solr.add([self._clean_doc(doc, namespace, timestamp)],
commit=(self.auto_commit_interval == 0),
commitWithin=u(self.auto_commit_interval))
else:
self.solr.add([self._clean_doc(doc,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bulk_upsert(self, docs, namespace, timestamp):
"""Update or insert multiple documents into Solr docs may be any iterable """ |
if self.auto_commit_interval is not None:
add_kwargs = {
"commit": (self.auto_commit_interval == 0),
"commitWithin": str(self.auto_commit_interval)
}
else:
add_kwargs = {"commit": False}
cleaned = (self._clean_doc(d, namespace... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr The input is a python dictionary that represents a mongo document. """ |
self.solr.delete(id=u(document_id),
commit=(self.auto_commit_interval == 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stream_search(self, query):
"""Helper method for iterating over Solr search results.""" |
for doc in self.solr.search(query, rows=100000000):
if self.unique_key != "_id":
doc["_id"] = doc.pop(self.unique_key)
yield doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, start_ts, end_ts):
"""Called to query Solr for documents in a time range.""" |
query = '_ts: [%s TO %s]' % (start_ts, end_ts)
return self._stream_search(query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_last_doc(self):
"""Returns the last document stored in the Solr engine. """ |
#search everything, sort by descending timestamp, return 1 row
try:
result = self.solr.search('*:*', sort='_ts desc', rows=1)
except ValueError:
return None
for r in result:
r['_id'] = r.pop(self.unique_key)
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def blockmix_salsa8(BY, Yi, r):
'''Blockmix; Used by SMix.'''
start = (2 * r - 1) * 16
X = BY[start:start + 16] # BlockMix - 1
for i in xrange(0, 2 * r): # BlockMix - 2
for xi in xrange(0, 16): ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def smix(B, Bi, r, N, V, X):
'''SMix; a specific case of ROMix. See scrypt.pdf in the links above.'''
X[:32 * r] = B[Bi:Bi + 32 * r] # ROMix - 1
for i in xrange(0, N): # ROMix - 2
aod = i * 32 * r # ROMix - 3
V[aod:aod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash(password, salt, N, r, p, dkLen):
"""Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((... |
# This only matters to Python 3
if not check_bytes(password):
raise ValueError('password must be a byte array')
if not check_bytes(salt):
raise ValueError('salt must be a byte array')
# Scrypt implementation. Significant thanks to https://github.com/wg/scrypt
if N < 2 or (N & (N ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _load_get_attr(self, name):
'Return an internal attribute after ensuring the headers is loaded if necessary.'
if self._mode in _allowed_read and self._N is None:
self._read_header()
return getattr(self, name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''Close the underlying file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def verify_file(fp, password):
'Returns whether a scrypt encrypted file is valid.'
sf = ScryptFile(fp = fp, password = password)
for line in sf: pass
sf.close()
return sf.valid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def readline(self, size = None):
'''Next line from the decrypted file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.'''
if self.closed: raise Valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _read_header(self):
'''Read and parse the header and calculate derived keys.'''
try:
# Read the entire header
header = self._fp.read(96)
if len(header) != 96:
raise InvalidScryptFileFormat("Incomplete header")
# Magic number
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def read(self, size = None):
'''Read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _write_header(self):
'Writes the header to the underlying file object.'
header = b'scrypt' + CHR0 + struct.pack('>BII', int(math.log(self.N, 2)), self.r, self.p) + self.salt
# Add the header checksum to the header
checksum = hashlib.sha256(header).digest()[:16]
header += ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _finalize_write(self):
'Finishes any unencrypted bytes and writes the final checksum.'
# Make sure we have written the header
if not self._done_header:
self._write_header()
# Write the remaining decrypted part to disk
block = self._crypto.encrypt(self._decrypted... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write(self, str):
'''Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.'''
if self.closed: raise ValueError('File closed')
if self._mode in _allowed_read:
raise... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeFile(file):
"""remove a file""" |
if "y" in speech.question("Are you sure you want to remove " + file + "? (Y/N): "):
speech.speak("Removing " + file + " with the 'rm' command.")
subprocess.call(["rm", "-r", file])
else:
speech.speak("Okay, I won't remove " + file + ".") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(location):
"""copy file or directory at a given location; can be pasted later""" |
copyData = settings.getDataFile()
copyFileLocation = os.path.abspath(location)
copy = {"copyLocation": copyFileLocation}
dataFile = open(copyData, "wb")
pickle.dump(copy, dataFile)
speech.speak(location + " copied successfully!")
speech.speak("Tip: use 'hallie paste' to paste this file.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paste(location):
"""paste a file or directory that has been previously copied""" |
copyData = settings.getDataFile()
if not location:
location = "."
try:
data = pickle.load(open(copyData, "rb"))
speech.speak("Pasting " + data["copyLocation"] + " to current directory.")
except:
speech.fail("It doesn't look like you've copied anything yet.")
speech.fail("Type 'hallie copy <file>' to copy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_zfs_apt_repository():
""" adds the ZFS repository """ |
with settings(hide('warnings', 'running', 'stdout'),
warn_only=False, capture=True):
sudo('DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update')
install_ubuntu_development_tools()
apt_install(packages=['software-properties-common',
'dkms',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apt_install(**kwargs):
""" installs a apt package """ |
for pkg in list(kwargs['packages']):
if is_package_installed(distribution='ubuntu', pkg=pkg) is False:
sudo("DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get install -y %s" % pkg)
# if we didn't abort above, we should return True
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apt_add_key(keyid, keyserver='keyserver.ubuntu.com', log=False):
""" trust a new PGP key related to a apt-repository """ |
if log:
log_green(
'trusting keyid %s from %s' % (keyid, keyserver)
)
with settings(hide('warnings', 'running', 'stdout')):
sudo('apt-key adv --keyserver %s --recv %s' % (keyserver, keyid))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_apt_repositories(prefix, url, version, repositories):
""" adds an apt repository """ |
with settings(hide('warnings', 'running', 'stdout'),
warn_only=False, capture=True):
sudo('apt-add-repository "%s %s %s %s"' % (prefix,
url,
version,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_package_installed(distribution, pkg):
""" checks if a particular package is installed """ |
if ('centos' in distribution or
'el' in distribution or
'redhat' in distribution):
return(is_rpm_package_installed(pkg))
if ('ubuntu' in distribution or
'debian' in distribution):
return(is_deb_package_installed(pkg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_rpm_package_installed(pkg):
""" checks if a particular rpm package is installed """ |
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo("rpm -q %s" % pkg)
if result.return_code == 0:
return True
elif result.return_code == 1:
return False
else: # print error to user... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yum_install(**kwargs):
""" installs a yum package """ |
if 'repo' in kwargs:
repo = kwargs['repo']
for pkg in list(kwargs['packages']):
if is_package_installed(distribution='el', pkg=pkg) is False:
if 'repo' in locals():
log_green(
"installing %s from repo %s ..." % (pkg, repo))
sudo("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yum_group_install(**kwargs):
""" instals a yum group """ |
for grp in list(kwargs['groups']):
log_green("installing %s ..." % grp)
if 'repo' in kwargs:
repo = kwargs['repo']
sudo("yum groupinstall -y --quiet "
"--enablerepo=%s '%s'" % (repo, grp))
else:
sudo("yum groups mark install -y --quiet '%... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recherche(self, pattern, entete, in_all=False):
"""abstractSearch in fields of collection and reset rendering. Returns number of results. If in_all is True, ... |
if in_all:
self.collection = self.get_all()
self.collection.recherche(pattern, entete)
self._reset_render()
return len(self.collection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch_background_job(self, job, on_error=None, on_success=None):
"""Launch the callable job in background thread. Succes or failure are controlled by on_err... |
if not self.main.mode_online:
self.sortie_erreur_GUI(
"Local mode activated. Can't run background task !")
self.reset()
return
on_error = on_error or self.sortie_erreur_GUI
on_success = on_success or self.sortie_standard_GUI
def thre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filtre(liste_base, criteres) -> groups.Collection: """ Return a filter list, bases on criteres :param liste_base: Acces list """ |
def choisi(ac):
for cat, li in criteres.items():
v = ac[cat]
if not (v in li):
return False
return True
return groups.Collection(a for a in liste_base if choisi(a)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_users(self):
"""Default implentation requires users from DB. Should setup `users` attribute""" |
r = sql.abstractRequetesSQL.get_users()()
self.users = {d["id"]: dict(d) for d in r} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_modules(self):
"""Should instance interfaces and set them to interface, following `modules`""" |
if self.INTERFACES_MODULE is None:
raise NotImplementedError("A module containing interfaces modules "
"should be setup in INTERFACES_MODULE !")
else:
for module, permission in self.modules.items():
i = getattr(self.INTERFACE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_autolog(self, user_id):
""" Read auto-connection parameters and returns local password or None """ |
try:
with open("local/init", "rb") as f:
s = f.read()
s = security.protege_data(s, False)
self.autolog = json.loads(s).get("autolog", {})
except FileNotFoundError:
return
mdp = self.autolog.get(user_id, None)
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loggin(self, user_id, mdp, autolog):
"""Check mdp and return True it's ok""" |
r = sql.abstractRequetesSQL.check_mdp_user(user_id, mdp)
if r():
# update auto-log params
self.autolog[user_id] = autolog and mdp or False
self.modules = self.users[user_id]["modules"] # load modules list
dic = {"autolog": self.autolog, "modules": self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mkpad(items):
'''
Find the length of the longest element of a list. Return that value + two.
'''
pad = 0
stritems = [str(e) for e in items] # cast list to strings
for e in stritems:
index = stritems.index(e)
if len(stritems[index]) > pad:
pad = len(stritems[index... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mkcols(l, rows):
'''
Compute the size of our columns by first making them a divisible of our row
height and then splitting our list into smaller lists the size of the row
height.
'''
cols = []
base = 0
while len(l) > rows and len(l) % rows != 0:
l.append("")
for i in rang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mkrows(l, pad, width, height):
'''
Compute the optimal number of rows based on our lists' largest element and
our terminal size in columns and rows.
Work out our maximum column number by dividing the width of the terminal by
our largest element.
While the length of our list is greater than... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prtcols(items, vpad=6):
'''
After computing the size of our rows and columns based on the terminal size
and length of the largest element, use zip to aggregate our column lists
into row lists and then iterate over the row lists and print them.
'''
from os import get_terminal_size
items =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def return_timer(self, name, status, timer):
''' Return a text formatted timer '''
timer_template = '%s %s %s : %s : %9s'
t = str(timedelta(0, timer)).split(',')[-1].strip().split(':')
#t = str(timedelta(0, timer)).split(':')
if len(t) == 4:
h, m, s = int(t[0])*24 + int(t[1]), i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def print_timers(self):
''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS '''
self.timer += time()
total_time = self.timer
tmp = '* %s *'
debug.log(
'',
'* '*29,
tmp%(' '*51),
tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cmd(self):
""" This function combines and return the commanline call of the program. """ |
cmd = []
if self.path is not None:
if '/' in self.path and not os.path.exists(self.path):
debug.log('Error: path contains / but does not exist: %s'%self.path)
else:
if self.ptype is not None:
if os.path.exists(self.ptype):
cmd.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_args(self, arg):
""" This function appends the provided arguments to the program object. """ |
debug.log("Adding Arguments: %s"%(arg))
if isinstance(arg, (int,float)): self.args.append(str(arg))
if isinstance(arg, str): self.args.append(arg)
if isinstance(arg, list):
if sys.version_info < (3, 0):
self.args.extend([str(x) if not isinstance(x, (unicode)) else x.encode(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_stdout(self):
""" This function will read the standard out of the program and print it """ |
# First we check if the file we want to print does exists
if self.wdir != '':
stdout = "%s/%s"%(self.wdir, self.stdout)
else:
stdout = self.stdout
if os.path.exists(stdout):
with open_(stdout, 'r') as f:
debug.print_out("\n".join([line for line in f]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_out_var(self, varnames=[]):
""" This function will read the standard out of the program, catch variables and return the values EG. #varname=value """ |
if self.wdir != '':
stdout = "%s/%s"%(self.wdir, self.stdout)
else:
stdout = self.stdout
response = [None]*len(varnames)
# First we check if the file we want to print does exists
if os.path.exists(stdout):
with open_(stdout, 'r') as f:
for line in f:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reporter(self):
""" Runs the necessary methods to parse raw read outputs """ |
logging.info('Preparing reports')
# Populate self.plusdict in order to reuse parsing code from an assembly-based method
for sample in self.runmetadata.samples:
self.plusdict[sample.name] = dict()
self.matchdict[sample.name] = dict()
if sample.general.bestasse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_parse(self):
""" If the pipeline has previously been run on these data, instead of reading through the results, parse the report instead """ |
# Initialise lists
report_strains = list()
genus_list = list()
if self.analysistype == 'mlst':
for sample in self.runmetadata.samples:
try:
genus_list.append(sample.general.referencegenus)
except AttributeError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_type(filename, **kwargs):
""" Utility function to call classes based on filename extension. Just usefull if you are reading the file and don't know fil... |
extension = os.path.splitext(filename)[1]
case = {'.xls': Xls,
'.xlsx': Xlsx,
'.csv': Csv}
if extension and case.get(extension.lower()):
low_extension = extension.lower()
new_kwargs = dict()
class_name = case.get(low_extension)
class_kwargs = inspect... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_gene_seqs(database_path, gene):
""" This function takes the database path and a gene name as inputs and returns the gene sequence contained in the file g... |
gene_path = database_path + "/" + gene + ".fsa"
gene_seq = ""
# Open fasta file
with open(gene_path) as gene_file:
header = gene_file.readline()
for line in gene_file:
seq = line.strip()
gene_seq += seq
return gene_seq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_best_sequence(hits_found, specie_path, gene, silent_N_flag):
""" This function takes the list hits_found as argument. This contains all hits found for t... |
# Get information from the fisrt hit found
all_start = hits_found[0][0]
current_end = hits_found[0][1]
final_sbjct = hits_found[0][2]
final_qry = hits_found[0][3]
sbjct_len = hits_found[0][4]
alternative_overlaps = []
# Check if more then one hit was found within the same gen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_mismatches(gene, sbjct_start, sbjct_seq, qry_seq, alternative_overlaps = []):
""" This function finds mis matches between two sequeces. Depending on the... |
# Initiate the mis_matches list that will store all found mis matcehs
mis_matches = []
# Find mis matches in RNA genes
if gene in RNA_gene_list:
mis_matches += find_nucleotid_mismatches(sbjct_start, sbjct_seq, qry_seq)
else:
# Check if the gene sequence is with a promoter
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_nuc_indel(gapped_seq, indel_seq):
""" This function finds the entire indel missing in from a gapped sequence compared to the indel_seqeunce. It is assum... |
ref_indel = indel_seq[0]
for j in range(1,len(gapped_seq)):
if gapped_seq[j] == "-":
ref_indel += indel_seq[j]
else:
break
return ref_indel |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aa(codon):
""" This function converts a codon to an amino acid. If the codon is not valid an error message is given, or else, the amino acid is returned. """ |
codon = codon.upper()
aa = {"ATT": "I", "ATC": "I", "ATA": "I",
"CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "TTA": "L", "TTG": "L",
"GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
"TTT": "F", "TTC": "F",
"ATG": "M",
"TGT": "C", "TGC": "C",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_codon(seq, codon_no, start_offset):
""" This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ |
seq = seq.replace("-","")
codon_start_pos = int(codon_no - 1)*3 - start_offset
codon = seq[codon_start_pos:codon_start_pos + 3]
return codon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_insertion(sbjct_seq, codon_no, sbjct_nucs, aa_alt, start_offset):
""" This function is used to name a insertion mutation based on the HGVS recommendatio... |
start_codon_no = codon_no - 1
if len(sbjct_nucs) == 3:
start_codon_no = codon_no
start_codon = get_codon(sbjct_seq, start_codon_no, start_offset)
end_codon = get_codon(sbjct_seq, codon_no, start_offset)
pos_name = "p.%s%d_%s%dins%s"%(aa(start_codon), start_codon_no, aa(end_codon), codon_no,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_indel_mutation(sbjct_seq, indel, sbjct_rf_indel, qry_rf_indel, codon_no, mut, start_offset):
""" This function serves to name the individual mutations d... |
# Get the subject and query sequences without gaps
sbjct_nucs = sbjct_rf_indel.replace("-", "")
qry_nucs = qry_rf_indel.replace("-", "")
# Translate nucleotides to amino acids
aa_ref = ""
aa_alt = ""
for i in range(0, len(sbjct_nucs), 3):
aa_ref += aa(sbjct_nucs[i:i+3])
for i i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_inframe_gap(seq, nucs_needed = 3):
""" This funtion takes a sequnece starting with a gap or the complementary seqeuence to the gap, and the number of nuc... |
nuc_count = 0
gap_indel = ""
nucs = ""
for i in range(len(seq)):
# Check if the character is not a gap
if seq[i] != "-":
# Check if the indel is a 'clean'
# i.e. if the insert or deletion starts at the first nucleotide in the codon and can be divided by 3
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self):
"""Try merging all the bravado_core models across all loaded APIs. If duplicates occur, use the same bravado-core model to represent each, so br... |
# The sole purpose of this method is to trick isinstance to return true
# on model_values of the same kind but different apis/specs at:
# https://github.com/Yelp/bravado-core/blob/4840a6e374611bb917226157b5948ee263913abc/bravado_core/marshal.py#L160
log.info("Merging models of apis " ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create( self, name, command_to_run, description="", environment_variables=None, required_arguments=None, required_arguments_default_values=None, extra_data_to... |
# Set None for optional list and dicts to proper datatypes
if environment_variables is None:
environment_variables = []
if required_arguments is None:
required_arguments = []
if required_arguments_default_values is None:
required_arguments_default_v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def response_data_to_model_instance(self, response_data):
"""Convert response data to a task type model. Args: response_data (dict):
The data from the request's... |
# Coerce datetime strings into datetime objects
response_data["datetime_created"] = dateutil.parser.parse(
response_data["datetime_created"]
)
# Instantiate a model for the task instance
return super(
BaseTaskTypeManager, self
).response_data_to_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy(version):
""" Deploy to pypi as specified version. """ |
NAME = "pathquery"
git = Command("git").in_dir(DIR.project)
version_file = DIR.project.joinpath("VERSION")
old_version = version_file.bytes().decode('utf8')
if version_file.bytes().decode("utf8") != version:
DIR.project.joinpath("VERSION").write_text(version)
git("add", "VERSION").r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hvenvup(package, directory):
""" Install a new version of a package in the hitch venv. """ |
pip = Command(DIR.gen.joinpath("hvenv", "bin", "pip"))
pip("uninstall", package, "-y").run()
pip("install", DIR.project.joinpath(directory).abspath()).run() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.