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 process_ioc(args):
"""Process actions related to the IOC switch.""" |
client = IndicatorClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_indicators()
elif args.single:
response = client.add_indicators(indicators=[args.single],
private=args.private, tags=args.tags)
else:
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_events(args):
"""Process actions related to events switch.""" |
client = EventsClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_events()
elif args.flush:
response = client.flush_events()
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Run the code.""" |
parser = ArgumentParser(description="Blockade Analyst Bench")
subs = parser.add_subparsers(dest='cmd')
ioc = subs.add_parser('ioc', help="Perform actions with IOCs")
ioc.add_argument('--single', '-s', help="Send a single IOC")
ioc.add_argument('--file', '-f', help="Parse a file of IOCs")
ioc.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 window(iterable, size=2):
''' yields wondows of a given size '''
iterable = iter(iterable)
d = deque(islice(iterable, size-1), maxlen=size)
for _ in map(d.append, iterable):
yield tuple(d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def payment_mode(self, payment_mode):
"""Sets the payment_mode of this CreditCardPayment. :param payment_mode: The payment_mode of this CreditCardPayment. :type:... |
allowed_values = ["authorize", "capture"]
if payment_mode is not None and payment_mode not in allowed_values:
raise ValueError(
"Invalid value for `payment_mode` ({0}), must be one of {1}"
.format(payment_mode, allowed_values)
)
self._pay... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_via_correlation_coefficient(image, template, raw_tolerance=1, normed_tolerance=0.9):
""" Matching algorithm based on 2-dimensional version of Pearson p... |
h, w = image.shape
th, tw = template.shape
temp_mean = np.mean(template)
temp_minus_mean = template - temp_mean
convolution = fftconvolve(image, temp_minus_mean[::-1,::-1])
convolution = convolution[th-1:h, tw-1:w]
match_position_dict = get_tiles_at_potential_match_regions(image, template, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_positions(shape, list_of_coords):
""" In cases where we have multiple matches, each highlighted by a region of coordinates, we need to separate matches... |
match_array = np.zeros(shape)
try:
# excpetion hit on this line if nothing in list_of_coords- i.e. no matches
match_array[list_of_coords[:,0],list_of_coords[:,1]] = 1
labelled = label(match_array)
objects = find_objects(labelled[0])
coords = [{'x':(slice_x.start, slice_x... |
<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_empty(self):
'''
Return `True` if form is valid and contains an empty lookup.
'''
return (self.is_valid() and
not self.simple_lookups and
not self.complex_conditions and
not self.extra_conditions) |
<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_inventory(hosts_file=HOSTS_FILE):
'''Loads Ansible inventory from file.
Parameters
----------
hosts_file: str, optional
path to Ansible hosts file
Returns
-------
ConfigParser.SafeConfigParser
content of `hosts_file`
'''
inventory = SafeConfigParser(allow_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 save_inventory(inventory, hosts_file=HOSTS_FILE):
'''Saves Ansible inventory to file.
Parameters
----------
inventory: ConfigParser.SafeConfigParser
content of the `hosts_file`
hosts_file: str, optional
path to Ansible hosts file
'''
with open(hosts_file, 'w') as 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 _init_config(self, width, height, spi=None, spiMosi= None, spiDC=None, spiCS=None, spiReset=None, spiClk=None):
"""! SPI hardware and display width, height i... |
self._spi = spi
self._spi_mosi = spiMosi
self._spi_dc = spiDC
self._spi_cs = spiCS
self._spi_reset = spiReset
self._spi_clk = spiClk
self.width = width
self.height = height |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_io(self):
"""! GPIO initialization. Set GPIO into BCM mode and init other IOs mode """ |
GPIO.setwarnings(False)
GPIO.setmode( GPIO.BCM )
pins = [ self._spi_dc ]
for pin in pins:
GPIO.setup( pin, GPIO.OUT ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self, fill = 0x00):
"""! Clear buffer data and other data RPiDiaplay object just implemented clear buffer data """ |
self._buffer = [ fill ] * ( self.width * self.height ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the ... |
count = 1
no_of_servers = len(self._rabbit_urls)
while True:
server_choice = (count % no_of_servers) - 1
self._url = self._rabbit_urls[server_choice]
try:
logger.info('Connecting', attempt=count)
return pika.SelectConnectio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nack_message(self, delivery_tag, **kwargs):
"""Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ |
logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs)
self._channel.basic_nack(delivery_tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tx_id(properties):
""" Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message h... |
tx_id = properties.headers['tx_id']
logger.info("Retrieved tx_id from message properties: tx_id={}".format(tx_id))
return tx_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_message(self, unused_channel, basic_deliver, properties, body):
"""Called on receipt of a message from a queue. Processes the message using the self._proc... |
if self.check_tx_id:
try:
tx_id = self.tx_id(properties)
logger.info('Received message',
queue=self._queue,
delivery_tag=basic_deliver.delivery_tag,
app_id=properties.app_id,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self, username, password):
"""Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication again... |
# Update the username and password bound to this instance for re-authentication needs.
self._username = username
self._password = password
# Attempt to authenticate.
resp = requests.get(
self._url,
auth=(username, password),
**self._default_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 _refresh(self):
"""Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentica... |
# Request and set a new API token.
new_token = self.authenticate(self._username, self._password)
self._token = new_token
logger.info('New API token received: "{}".'.format(new_token))
return self._token |
<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(self, token):
"""Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a... |
# Attempt to authenticate.
url = '{}{}/'.format(self._url, 'verify')
resp = requests.post(
url,
json={'token': token},
**self._default_request_kwargs
)
if resp.status_code == 200:
return resp.json().get('data', None)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def preprocess(net, image):
'''
convert to Caffe input image layout
'''
return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_step(
net,
step_size = 1.5,
end = "inception_4c/output",
jitter = 32,
clip = True,
objective = objective_L2
):
'''
basic gradient ascent step
'''
src = net.blobs["data"]
dst = net.blobs[end]
ox, oy = np.random.randint(- jitter, jitter + 1, 2)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deepdream(
net,
base_image,
iter_n = 10,
octave_n = 4,
octave_scale = 1.4,
end = "inception_4c/output",
clip = True,
**step_params
):
'''
an ascent through different scales called "octaves"
'''
# Prepare base images for all octaves.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(param_path='parameters.txt'):
""" Entry point function for analysis based on parameter files. Parameters param_path : str Path to user-generated paramet... |
# Confirm parameters file is present
if not os.path.isfile(param_path):
raise IOError, "Parameter file not found at %s" % param_path
# Get raw params and base options (non-run-dependent options)
params, base_options = _get_params_base_options(param_path)
# Configure and start logging
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_analysis(options):
""" Do analysis for a single run, as specified by options. Parameters options : dict Option names and values for analysis """ |
module = _function_location(options)
core_results = _call_analysis_function(options, module)
if module == 'emp' and ('models' in options.keys()):
fit_results = _fit_models(options, core_results)
else:
fit_results = None
_save_results(options, module, core_results, fit_results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call_analysis_function(options, module):
""" Call function from module and get result, using inputs from options Parameters options : dict Option names and ... |
args, kwargs = _get_args_kwargs(options, module)
return eval("%s.%s(*args, **kwargs)" % (module, options['analysis'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _emp_extra_options(options):
""" Get special options patch, cols, and splits if analysis in emp module """ |
# Check that metadata is valid
metadata_path = os.path.normpath(os.path.join(options['param_dir'],
options['metadata']))
if not os.path.isfile(metadata_path):
raise IOError, ("Path to metadata file %s is invalid." %
metadata... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fit_models(options, core_results):
""" Fit models to empirical result from a function in emp module Parameters options : dict Option names and values for an... |
logging.info("Fitting models")
models = options['models'].replace(' ', '').split(';')
# TODO: Make work for 2D results, i.e., curves, comm_sep, o_ring
# TODO: Make work for curves in general (check if 'x' present in core_res)
fit_results = []
for core_result in core_results: # Each subset
... |
<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_results(options, module, core_results, fit_results):
""" Save results of analysis as tables and figures Parameters options : dict Option names and valu... |
logging.info("Saving all results")
# Use custom plot format
mpl.rcParams.update(misc.rcparams.ggplot_rc)
# Make run directory
os.makedirs(options['run_dir'])
# Write core results
_write_core_tables(options, module, core_results)
# Write additional results if analysis from emp
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 _write_subset_index_file(options, core_results):
""" Write table giving index of subsets, giving number and subset string """ |
f_path = os.path.join(options['run_dir'], '_subset_index.csv')
subset_strs = zip(*core_results)[0]
index = np.arange(len(subset_strs)) + 1
df = pd.DataFrame({'subsets': subset_strs}, index=index)
df.to_csv(f_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pad_plot_frame(ax, pad=0.01):
""" Provides padding on sides of frame equal to pad fraction of plot """ |
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
xr = xmax - xmin
yr = ymax - ymin
ax.set_xlim(xmin - xr*pad, xmax + xr*pad)
ax.set_ylim(ymin - yr*pad, ymax + yr*pad)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _output_cdf_plot(core_result, spid, models, options, fit_results):
"""Function for plotting cdf""" |
# CDF
x = core_result['y'].values
df = emp.empirical_cdf(x)
df.columns = ['x', 'empirical']
def calc_func(model, df, shapes):
return eval("mod.%s.cdf(df['x'], *shapes)" % model)
plot_exec_str = "ax.step(df['x'], emp, color='k', lw=3);ax.set_ylim(top=1)"
_save_table_and_plot(spid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def openOnlyAccel(self, cycleFreq = 0x00 ):
"""! Trun on device into Accelerometer Only Low Power Mode @param cycleFreq can be choise: @see VAL_PWR_MGMT_2_LP_WAK... |
self.openWith(accel = True, gyro = False, temp = False, cycle = True, cycleFreq = cycleFreq) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setMotionInt(self, motDHPF = 0x01, motTHR = 0x14, motDUR = 0x30, motDeteDec = 0x15 ):
"""! Set to enable Motion Detection Interrupt @param motDHPF Set the Di... |
#After power on (0x00 to register (decimal) 107), the Motion Detection Interrupt can be enabled as follows:
#self._sendCmd( self.REG_PWR_MGMT_1, 0x00 )
#(optionally?) Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
self._sendCmd( self.REG_SIGNAL_PATH_RE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readAccelRange( self ):
"""! Reads the range of accelerometer setup. @return an int value. It should be one of the following values: @see ACCEL_RANGE_2G @see... |
raw_data = self._readByte(self.REG_ACCEL_CONFIG)
raw_data = (raw_data | 0xE7) ^ 0xE7
return raw_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAccelData( self, raw = False ):
"""! Gets and returns the X, Y and Z values from the accelerometer. @param raw If raw is True, it will return the data in ... |
x = self._readWord(self.REG_ACCEL_XOUT_H)
y = self._readWord(self.REG_ACCEL_YOUT_H)
z = self._readWord(self.REG_ACCEL_ZOUT_H)
accel_scale_modifier = None
accel_range = self.readAccelRange()
if accel_range == self.ACCEL_RANGE_2G:
accel_scale_modifier = 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 readGyroRange( self ):
"""! Read range of gyroscope. @return an int value. It should be one of the following values (GYRO_RANGE_250DEG) @see GYRO_RANGE_250DE... |
raw_data = self._readByte( self.REG_GYRO_CONFIG )
raw_data = (raw_data | 0xE7) ^ 0xE7
return raw_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getGyroData(self):
"""! Gets and returns the X, Y and Z values from the gyroscope @return a dictionary with the measurement results or Boolean. @retval False... |
x = self._readWord(self.REG_GYRO_XOUT_H)
y = self._readWord(self.REG_GYRO_YOUT_H)
z = self._readWord(self.REG_GYRO_ZOUT_H)
gyro_scale_modifier = None
gyro_range = self.readGyroRange()
if gyro_range == self.GYRO_RANGE_250DEG:
gyro_scale_modifier = self.GYRO_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAllData(self, temp = True, accel = True, gyro = True):
"""! Get all the available data. @param temp: True - Allow to return Temperature data @param accel:... |
allData = {}
if temp:
allData["temp"] = self.getTemp()
if accel:
allData["accel"] = self.getAccelData( raw = False )
if gyro:
allData["gyro"] = self.getGyroData()
return allData |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def repeater(pipe, how_many=2):
''' this function repeats each value in the pipeline however many times you need '''
r = range(how_many)
for i in pipe:
for _ in r:
yield 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 kld(p1, p2):
"""Compute Kullback-Leibler divergence between p1 and p2.
It assumes that p1 and p2 are already normalized that each of them sums to 1.
""" |
return np.sum(np.where(p1 != 0, p1 * np.log(p1 / p2), 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 jsd(p1, p2):
"""Compute Jensen-Shannon divergence between p1 and p2.
It assumes that p1 and p2 are already normalized that each of them sums to 1.
""" |
m = (p1 + p2) / 2
return (kld(p1, m) + kld(p2, m)) / 2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):
"""Calculate Jensen-Shannon divergence between query and reference gene expre... |
gene_jsd_dict = dict()
reference_genes = ref_gene_expression_dict.keys()
assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.'
for gene in gene_set:
if gene not in network.nodes:
continue
neighbors = find_neighbors(network, gene... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookupProcessor(name):
"""Lookup processor class object by its name""" |
if name in _proc_lookup:
return _proc_lookup[name]
else:
error_string = 'If you are creating a new processor, please read the\
documentation on creating a new processor'
raise LookupError("Unknown processor %s\n%s" % (name, error_string)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, value, entity=None, request=None):
""" Validate and serialize the value. This is the default implementation """ |
ret = self.from_python(value)
self.validate(ret)
self.run_validators(value)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def side_task(pipe, *side_jobs):
''' allows you to run a function in a pipeline without affecting the data '''
# validate the input
assert iterable(pipe), 'side_task needs the first argument to be iterable'
for sj in side_jobs:
assert callable(sj), 'all side_jobs need to be functions, not {}'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connects to the ec2 cloud provider :return: :py:class:`boto.ec2.connection.EC2Connection` :raises: Generic exception on error """ |
# check for existing connection
if self._ec2_connection:
return self._ec2_connection
if not self._vpc:
vpc_connection = None
try:
log.debug("Connecting to ec2 host %s", self._ec2host)
region = ec2.regioninfo.RegionInfo(name=self._region_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def split(pipe, splitter, skip_empty=False):
''' this function works a lot like groupby but splits on given patterns,
the same behavior as str.split provides. if skip_empty is True,
split only yields pieces that have contents
Example:
splitting 1011101010101
by ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_tracking_code(tracking_code, year=None):
""" Given a tracking_code return a list of events related the tracking code """ |
payload = {
'Anio': year or datetime.now().year,
'Tracking': tracking_code,
}
response = _make_request(TRACKING_URL, payload)
if not response['d']:
return []
data = response['d'][0]
destination = data['RetornoCadena6']
payload.update({
'Destino': destinati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comments_nb_counts():
"""Get number of comments for the record `recid`.""" |
recid = request.view_args.get('recid')
if recid is None:
return
elif recid == 0:
return 0
else:
return CmtRECORDCOMMENT.count(*[
CmtRECORDCOMMENT.id_bibrec == recid,
CmtRECORDCOMMENT.star_score == 0,
CmtRECORDCOMMENT.status.notin_(['dm', 'da'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decide_k(airport_code):
"""A function to decide if a leading 'K' is throwing off an airport match and return the correct code.""" |
if airport_code[:1].upper() == 'K':
try: # if there's a match without the K that's likely what it is.
return Airport.objects.get(location_identifier__iexact=airport_code[1:]).location_identifier
except Airport.DoesNotExist:
return airport_code
else:
return airpo... |
<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_date(datestring):
"""Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ |
datestring = str(datestring).strip()
if not datestring[0].isdigit():
raise ParseError()
if 'W' in datestring.upper():
try:
datestring = datestring[:-1] + str(int(datestring[-1:]) -1)
except:
pass
for regex, pattern in DATE_FORMATS:
if regex.mat... |
<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_time(timestring):
"""Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ |
timestring = str(timestring).strip()
for regex, pattern in TIME_FORMATS:
if regex.match(timestring):
found = regex.search(timestring).groupdict()
dt = datetime.utcnow().strptime(found['matched'], pattern)
dt = datetime.combine(date.today(), dt.time())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ |
self.log.debug('starting the ``get`` method')
dbSettings = self.dbSettings
port = False
if "tunnel" in dbSettings and dbSettings["tunnel"]:
port = self._setup_tunnel(
tunnelParameters=dbSettings["tunnel"]
)
# SETUP A DATABASE CONNECTION... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]: """ Returns decorator that calls wrapped function if nothing was found in cache for its a... |
def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]:
@wraps(function)
def wrapped(argument: Domain) -> Range:
try:
return cache[argument]
except KeyError:
return function(argument)
return wrapped
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]: """ Returns decorator that calls wrapped function if nothing was found in cache for its ... |
def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]:
@wraps(function)
def wrapped(argument: Domain) -> Range:
try:
return cache[argument]
except KeyError:
result = function(argument)
cache[argument] = result
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instan... |
return property(map_(WeakKeyDictionary())(getter)) |
<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_context_data(self, **kwargs):
"""Tests cookies. """ |
self.request.session.set_test_cookie()
if not self.request.session.test_cookie_worked():
messages.add_message(
self.request, messages.ERROR, "Please enable cookies.")
self.request.session.delete_test_cookie()
return super().get_context_data(**kwargs) |
<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(root):
# type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example o... |
# print the part before the element
def print_before(previous=0, defined=None, is_last=False):
defined = defined or {}
ret = ''
if previous != 0:
for i in range(previous - 1):
# if the column is still active write |
... |
<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_filter(self):
""" Get FilterForm instance. """ |
return self.filter_form_cls(self.request.GET,
runtime_context=self.get_runtime_context(),
use_filter_chaining=self.use_filter_chaining) |
<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_context_data(self, **kwargs):
""" Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, i... |
context = super(FilterFormMixin, self).get_context_data(**kwargs)
context[self.context_filterform_name] = self.get_filter()
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compile_to_python(exp, env, done=None):
'''assemble steps from dao expression to python code'''
original_exp = exp
compiler = Compiler()
if done is None:
done = il.Done(compiler.new_var(il.ConstLocalVar('v')))
compiler.exit_block_cont_map = {}
compiler.continue_block_cont_map = {}
compile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def last(pipe, items=1):
''' this function simply returns the last item in an iterable '''
if items == 1:
tmp=None
for i in pipe:
tmp=i
return tmp
else:
return tuple(deque(pipe, maxlen=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 print_help(filename, table, dest=sys.stdout):
""" Print help to the given destination file object. """ |
cmds = '|'.join(sorted(table.keys()))
print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(table, args):
""" Dispatches to a function based on the contents of `args`. """ |
# No arguments: print help.
if len(args) == 1:
print_help(args[0], table)
sys.exit(0)
# Bad command or incorrect number of arguments: print help to stderr.
if args[1] not in table or len(args) != len(table[args[1]]) + 1:
print_help(args[0], table, dest=sys.stderr)
sys.e... |
<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_all(s, sub, start=0, end=0, limit=-1, reverse=False):
""" Find all indexes of sub in s. :param s: the string to search :param sub: the string to search ... |
indexes = []
if not bool(s and sub):
return indexes
lstr = len(s)
if lstr <= start:
return indexes
lsub = len(sub)
if lstr < lsub:
return indexes
if limit == 0:
return indexes
elif limit < 0:
limit = lstr
end = min(end, lstr) or lstr
... |
<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_substructure(data, path):
""" Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. [1, 2, [{'f... |
if not len(path):
return data
try:
return get_substructure(data[path[0]], path[1:])
except (TypeError, IndexError, KeyError):
return 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 iterable(target):
''' returns true if the given argument is iterable '''
if any(i in ('next', '__next__', '__iter__') for i in dir(target)):
return True
else:
try:
iter(target)
return True
except:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _thread_worker(self):
"""Process callbacks from the queue populated by &listen.""" |
while self._running:
# Retrieve next cmd, or block
packet = self._queue.get(True)
if isinstance(packet, dict) and QS_CMD in packet:
try:
self._callback_listen(packet)
except Exception as err: # pylint: disable=broad-except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _thread_listen(self):
"""The main &listen loop.""" |
while self._running:
try:
rest = requests.get(URL_LISTEN.format(self._url),
timeout=self._timeout)
if rest.status_code == 200:
self._queue.put(rest.json())
else:
_LOGGER.error... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1 """ |
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g, b = x, c, 0
elif h<180:
r, g, b = 0, c, x
elif h<240:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dir_list(directory):
'''Returns the list of all files in the directory.'''
try:
content = listdir(directory)
return content
except WindowsError as winErr:
print("Directory error: " + str((winErr))) |
<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_dir(directory):
'''Returns the text of all files in a directory.'''
content = dir_list(directory)
text = ''
for filename in content:
text += read_file(directory + '/' + filename)
text += ' '
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def colorize(occurence,maxoccurence,minoccurence):
'''A formula for determining colors.'''
if occurence == maxoccurence:
color = (255,0,0)
elif occurence == minoccurence:
color = (0,0,255)
else:
color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fontsize(count,maxsize,minsize,maxcount):
'''A formula for determining font sizes.'''
size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount)))
if size < minsize:
size = minsize
return size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_display(self):
"""! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片 """ |
self._command([
# 0xAE
self.CMD_SSD1306_DISPLAY_OFF,
#Stop Scroll
self.CMD_SSD1306_SET_SCROLL_DEACTIVE,
# 0xA8 SET MULTIPLEX 0x3F
self.CMD_SSD1306_SET_MULTIPLEX_RATIO,
0x3F,
# 0xD3 SET DISPLAY OFFSET
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(self, buffer = None):
"""! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data ... |
if buffer != None:
self._display_buffer( buffer )
else:
self._display_buffer( self._buffer ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scrollWith(self, hStart = 0x00, hEnd=0x00, vOffset = 0x00, vStart=0x00, vEnd=0x00, int = 0x00, dire = "left" ):
"""! \~english Scroll screen @param hStart: S... |
self._command( [self.CMD_SSD1306_SET_SCROLL_DEACTIVE] )
if vOffset != 0:
self._command( [
self.CMD_SSD1306_SET_SCROLL_VERTICAL_AREA,
vStart,
vEnd,
0x00
])
self._command( [
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, schedule_type, lookup_id, **kwargs):
""" Loads Schedule linked to provided lookup """ |
log = self.get_logger(**kwargs)
log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id))
task_run = QueueTaskRun()
task_run.task_id = self.request.id or uuid4()
task_run.started_at = now()
tr_qs = QueueTaskRun.objects
# Load the schedule active 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 bind(renderer, to):
""" Bind a renderer to the given callable by constructing a new rendering view. """ |
@wraps(to)
def view(request, **kwargs):
try:
returned = to(request, **kwargs)
except Exception as error:
view_error = getattr(renderer, "view_error", None)
if view_error is None:
raise
return view_error(request, error)
tr... |
<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_perm_model():
""" Returns the Perm model that is active in this project. """ |
try:
return django_apps.get_model(settings.PERM_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
"PERM_MODEL refers to model '{}' that has 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 _load_yaml_config(cls, config_data, filename="(unknown)"):
"""Load a yaml config file.""" |
try:
config = yaml.safe_load(config_data)
except yaml.YAMLError as err:
if hasattr(err, 'problem_mark'):
mark = err.problem_mark
errmsg = ("Invalid YAML syntax in Configuration file "
"%(file)s at line: %(line)s, column:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sround(x, precision=0):
""" Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. "... |
sr = StochasticRound(precision=precision)
return sr.round(x) |
<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_chord_line(line):
''' Parse a chord line into a `ChordLineData` object. '''
chords = [
TabChord(position=position, chord=chord)
for chord, position in Chord.extract_chordpos(line)
]
return ChordLineData(chords=chords) |
<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_line_type(line):
''' Decide the line type in function of its contents '''
stripped = line.strip()
if not stripped:
return 'empty'
remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped))
if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)):
return 'chord'
re... |
<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_line(line):
''' Parse a line into a `TabLine` object. '''
line = line.rstrip()
line_type = _get_line_type(line)
return TabLine(
type=line_type,
data=_DATA_PARSERS[line_type](line),
original=line,
) |
<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_tablature(lines):
''' Parse a list of lines into a `Tablature`. '''
lines = [parse_line(l) for l in lines]
return Tablature(lines=lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preview(df,preview_rows = 20):
#,preview_max_cols = 0):
""" Returns a preview of a dataframe, which contains both header rows and tail rows. """ |
if preview_rows < 4:
preview_rows = 4
preview_rows = min(preview_rows,df.shape[0])
outer = math.floor(preview_rows / 4)
return pd.concat([df.head(outer),
df[outer:-outer].sample(preview_rows-2*outer),
df.tail(outer)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def title_line(text):
"""Returns a string that represents the text as a title blurb """ |
columns = shutil.get_terminal_size()[0]
start = columns // 2 - len(text) // 2
output = '='*columns + '\n\n' + \
' ' * start + str(text) + "\n\n" + \
'='*columns + '\n'
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RadiusGrid(gridSize):
""" Return a square grid with values of the distance from the centre of the grid to each gridpoint """ |
x,y=np.mgrid[0:gridSize,0:gridSize]
x = x-(gridSize-1.0)/2.0
y = y-(gridSize-1.0)/2.0
return np.abs(x+1j*y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CircularMaskGrid(gridSize, diameter=None):
""" Return a square grid with ones inside and zeros outside a given diameter circle """ |
if diameter is None: diameter=gridSize
return np.less_equal(RadiusGrid(gridSize),diameter/2.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 AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None):
""" Correct a wavefront using Zernike rejection up to some maximal order. Can operate on mul... |
gridSize=pupils.shape[-1]
pupilsVector=np.reshape(pupils,(-1,gridSize**2))
zernikes=np.reshape(ZernikeGrid(gridSize,maxRadial,diameter),(-1,gridSize**2))
if numRemove is None: numRemove=zernikes.shape[0]
numScreen=pupilsVector.shape[0]
normalisation=1.0/np.sum(zernikes[0])
# Note extra iter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FibreCouple(pupils,modeDiameter):
""" Return the complex amplitudes coupled into a set of fibers """ |
gridSize=pupils.shape[-1]
pupilsVector=np.reshape(pupils,(-1,gridSize**2))
mode=np.reshape(FibreMode(gridSize,modeDiameter),(gridSize**2,))
return np.inner(pupilsVector,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 SingleModeCombine(pupils,modeDiameter=None):
""" Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner ""... |
if modeDiameter is None:
modeDiameter=0.9*pupils.shape[-1]
amplitudes=FibreCouple(pupils,modeDiameter)
cc=np.conj(amplitudes)
fluxes=(amplitudes*cc).real
coherentFluxes=[amplitudes[i]*cc[j]
for i in range(1,len(amplitudes))
for j in range(i)]
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ |
if not isinstance(s, TEXT):
if not isinstance(s, bytes):
raise TypeError('You are required to pass either unicode or '
'bytes here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError as le:
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 to_postdata(self):
"""Serialize as post data for a POST request.""" |
items = []
for k, v in sorted(self.items()): # predictable for testing
items.append((k.encode('utf-8'), to_utf8_optional_iterator(v)))
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_request_token(self, oauth_request):
"""Processes a request_token request and returns the request token on success. """ |
try:
# Get the request token for authorization.
token = self._get_token(oauth_request, 'request')
except Error:
# No token required for the initial token request.
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_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 fetch_access_token(self, oauth_request):
"""Processes an access_token request and returns the access token on success. """ |
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except Error:
verifier = None
# Get the request token.
token = self._get_token(oauth_request, 'request')
... |
<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_token(self, oauth_request, token_type='access'):
"""Try to find the token for the provided request token key.""" |
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mete_upscale_iterative_alt(S, N, doublings):
""" This function is used to upscale from the anchor area. Parameters S : int or float Number of species at anch... |
# Arrays to store N and S at all doublings
n_arr = np.empty(doublings+1)
s_arr = np.empty(doublings+1)
# Loop through all scales
for i in xrange(doublings+1):
# If this is first step (doubling 0), N and S are initial values
if i == 0:
n_arr[i] = N
s_arr[i]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.