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 image(img, cmap='gray', bar=False, nans=True, clim=None, size=7, ax=None):
""" Streamlined display of images using matplotlib. Parameters img : ndarray, 2D o... |
from matplotlib.pyplot import axis, colorbar, figure, gca
img = asarray(img)
if (nans is True) and (img.dtype != bool):
img = nan_to_num(img)
if ax is None:
f = figure(figsize=(size, size))
ax = gca()
if img.ndim == 3:
if bar:
raise ValueError("Cannot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(cls):
""" Returns a list of all configured endpoints the server is listening on. For each endpoint, the list of allowed databases is returned too if set.... |
api = Client.instance().api
endpoint_list = api.endpoint.get()
return endpoint_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 create(cls, url, databases):
""" If databases is an empty list, all databases present in the server will become accessible via the endpoint, with the _system... |
api = Client.instance().api
result = api.endpoint.post(data={
'endpoint': url,
'databases': databases,
})
return 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 destroy(cls, url):
""" This operation deletes an existing endpoint from the list of all endpoints, and makes the server stop listening on the endpoint. *Note... |
api = Client.instance().api
api.endpoint(url).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(self):
""" Return a deferred that will be fired when the event is fired. """ |
d = defer.Deferred()
if self._result is None:
self._waiters.append(d)
else:
self._fire_deferred(d)
return 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 close(self, reason):
"""Explicitly close a channel""" |
self._closing = True
self.do_close(reason)
self._closing = 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 _raise_closed(reason):
"""Raise the appropriate Closed-based error for the given reason.""" |
if isinstance(reason, Message):
if reason.method.klass.name == "channel":
raise ChannelClosed(reason)
elif reason.method.klass.name == "connection":
raise ConnectionClosed(reason)
raise Closed(reason) |
<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, reason=None, within=0):
"""Explicitely close the connection. @param reason: Optional closing reason. If not given, ConnectionDone will be used. @... |
if self.closed:
return
if reason is None:
reason = ConnectionDone()
if within > 0:
channel0 = yield self.channel(0)
deferred = channel0.connection_close()
call = self.clock.callLater(within, deferred.cancel)
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 copy(self):
'''Returns a copy of this namespace.
Note: we truly create a copy of the dictionary but keep
_macros and _blocks.
'''
return Namespace(self.dictionary.copy(), self._macros, self._blocks) |
<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_tcp_check(self, ip, results):
""" Attempt to establish a TCP connection. If not successful, record the IP in the results dict. Always closes the connecti... |
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
sock.connect((ip, self.conf['tcp_check_port']))
except:
# Any problem during the connection attempt? We won't diagnose it,
# we just indicate failure by adding th... |
<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_health_checks(self, list_of_ips):
""" Perform a health check on a list of IP addresses. Each check (we use a TCP connection attempt) is run in its own thr... |
threads = []
results = []
# Start the thread for each IP we wish to check.
for count, ip in enumerate(list_of_ips):
thread = threading.Thread(
target = self._do_tcp_check,
name = "%s:%s" % (self.thread_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 start(self):
""" Start the monitoring thread of the plugin. """ |
logging.info("TCP health monitor plugin: Starting to watch "
"instances.")
self.monitor_thread = threading.Thread(target = self.start_monitoring,
name = self.thread_name)
self.monitor_thread.daemon = True
self.monito... |
<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_arguments(cls, parser, sys_arg_list=None):
""" Arguments for the TCP health monitor plugin. """ |
parser.add_argument('--tcp_check_interval',
dest='tcp_check_interval',
required=False, default=2, type=float,
help="TCP health-test interval in seconds, "
"default 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 _check_negatives(numbers):
"Raise warning for negative numbers."
negatives = filter(lambda x: x < 0, filter(None, numbers))
if any(negatives):
neg_values = ', '.join(map(str, negatives))
msg = 'Found negative value(s): {0!s}. '.format(neg_values)
msg += 'While not forbidden, the... |
<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_emphasis(numbers, emph):
"Find index postions in list of numbers to be emphasized according to emph."
pat = '(\w+)\:(eq|gt|ge|lt|le)\:(.+)'
# find values to be highlighted
emphasized = {} # index: color
for (i, n) in enumerate(numbers):
if n is None:
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scale_values(numbers, num_lines=1, minimum=None, maximum=None):
"Scale input numbers to appropriate range."
# find min/max values, ignoring Nones
filtered = [n for n in numbers if n is not None]
min_ = min(filtered) if minimum is None else minimum
max_ = max(filtered) if maximum is None else ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sparklines(numbers=[], num_lines=1, emph=None, verbose=False, minimum=None, maximum=None, wrap=None):
""" Return a list of 'sparkline' strings for a given li... |
assert num_lines > 0
if len(numbers) == 0:
return ['']
# raise warning for negative numbers
_check_negatives(numbers)
values = scale_values(numbers, num_lines=num_lines, minimum=minimum, maximum=maximum)
# find values to be highlighted
emphasized = _check_emphasis(numbers, emph... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def batch(batch_size, items):
"Batch items into groups of batch_size"
items = list(items)
if batch_size is None:
return [items]
MISSING = object()
padded_items = items + [MISSING] * (batch_size - 1)
groups = zip(*[padded_items[i::batch_size] for i in range(batch_size)])
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 demo(nums=[]):
"Print a few usage examples on stdout."
nums = nums or [3, 1, 4, 1, 5, 9, 2, 6]
fmt = lambda num: '{0:g}'.format(num) if isinstance(num, (float, int)) else 'None'
nums1 = list(map(fmt, nums))
if __name__ == '__main__':
prog = sys.argv[0]
else:
prog = 'sparkli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expire_data(self):
""" Remove all expired entries. """ |
expire_time_stamp = time.time() - self.expire_time
self.timed_data = {d: t for d, t in self.timed_data.items()
if t > expire_time_stamp} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, data_set):
""" Refresh the time of all specified elements in the supplied data set. """ |
now = time.time()
for d in data_set:
self.timed_data[d] = now
self._expire_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 _accumulate_ips_from_plugins(self, ip_type_name, plugin_queue_lookup, ip_accumulator):
""" Retrieve all IPs of a given type from all sub-plugins. ip_type_nam... |
all_reported_ips = set()
for pname, q in plugin_queue_lookup.items():
# Get all the IPs of the specified type from all the plugins.
ips = utils.read_last_msg_from_queue(q)
if ips:
logging.debug("Sub-plugin '%s' reported %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 start_monitoring(self):
""" Pass IP lists to monitor sub-plugins and get results from them. Override the common definition of this function, since in the mul... |
logging.info("Multi-plugin health monitor: Started in thread.")
try:
while True:
# Get new IP addresses and pass them on to the sub-plugins
new_ips = self.get_new_working_set()
if new_ips:
logging.debug("Sending list of %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 load_sub_plugins_from_str(cls, plugins_str):
""" Load plugin classes based on column separated list of plugin names. Returns dict with plugin name as key and... |
plugin_classes = {}
if plugins_str:
for plugin_name in plugins_str.split(":"):
pc = load_plugin(plugin_name, MONITOR_DEFAULT_PLUGIN_MODULE)
plugin_classes[plugin_name] = pc
return plugin_classes |
<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_arguments(cls, parser, sys_arg_list=None):
""" Arguments for the Multi health monitor plugin. """ |
parser.add_argument('--multi_plugins',
dest='multi_plugins', required=True,
help="Column seperated list of health monitor "
"plugins (only for 'multi' health monitor "
"plugin)")
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 read_route_spec_config(fname):
""" Read, parse and sanity check the route spec config file. The config file needs to be in this format: { "<CIDR-1>" : [ "hos... |
try:
try:
f = open(fname, "r")
except IOError as e:
# Cannot open file? Doesn't exist?
raise ValueError("Cannot open file: " + str(e))
data = json.loads(f.read())
f.close()
# Sanity checking on the data object
data = common.parse_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 start(self):
""" Start the configfile change monitoring thread. """ |
fname = self.conf['file']
logging.info("Configfile watcher plugin: Starting to watch route spec "
"file '%s' for changes..." % fname)
# Initial content of file needs to be processed at least once, before
# we start watching for any changes to it. Therefore, we 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 stop(self):
""" Stop the config change monitoring thread. """ |
self.observer_thread.stop()
self.observer_thread.join()
logging.info("Configfile watcher plugin: Stopped") |
<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_arguments(cls, parser, sys_arg_list=None):
""" Arguments for the configfile mode. """ |
parser.add_argument('-f', '--file', dest='file', required=True,
help="config file for routing groups "
"(only in configfile mode)")
return ["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 check_arguments(cls, conf):
""" Sanity checks for options needed for configfile mode. """ |
try:
# Check we have access to the config file
f = open(conf['file'], "r")
f.close()
except IOError as e:
raise ArgsError("Cannot open config file '%s': %s" %
(conf['file'], 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 load_plugin(plugin_name, default_plugin_module):
""" Load a plugin plugin. Supports loading of plugins that are part of the vpcrouter, as well as external pl... |
try:
if "." in plugin_name:
# Assume external plugin, full path
plugin_mod_name = plugin_name
plugin_class_name = plugin_name.split(".")[-1].capitalize()
else:
# One of the built-in plugins
plugin_mod_name = "%s.%s" % (default_plugin_m... |
<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_signal_receiver(self, signal):
""" Remove an installed signal receiver by signal name. See also :py:meth:`add_signal_receiver` :py:exc:`exceptions.Con... |
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) # noqa
... |
<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_request(self, request, url, **kwargs):
"Actually makes the HTTP request."
try:
response = request(url, stream=True, **kwargs)
except RequestException as e:
raise RequestError(e)
else:
if response.status_code >= 400:
raise Respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _request(self, method, endpoint, id=None, **kwargs):
"Handles retrying failed requests and error handling."
request = getattr(requests, method, None)
if not callable(request):
raise RequestError('Invalid method %s' % method)
# Find files, separate them out to correct kwar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, file_to_be_downloaded, perform_download=True, download_to_path=None):
""" file_to_be_downloaded is a file-like object that has already been up... |
response = self.get(
'/path/data/', file_to_be_downloaded, raw=False)
if not perform_download:
# The caller can decide how to process the download of the data
return response
if not download_to_path:
download_to_path = file_to_be_downloaded.split(... |
<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_notebook(self, data):
"""Create notebook under notebook directory.""" |
r = requests.post('http://{0}/api/notebook'.format(self.zeppelin_url),
json=data)
self.notebook_id = r.json()['body'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_notebook_to_execute(self):
"""Wait for notebook to finish executing before continuing.""" |
while True:
r = requests.get('http://{0}/api/notebook/job/{1}'.format(
self.zeppelin_url, self.notebook_id))
if r.status_code == 200:
try:
data = r.json()['body']
if all(paragraph['status'] in ['FINISH... |
<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_executed_notebook(self):
"""Return the executed notebook.""" |
r = requests.get('http://{0}/api/notebook/{1}'.format(
self.zeppelin_url, self.notebook_id))
if r.status_code == 200:
return r.json()['body']
else:
print('ERROR: Could not get executed notebook.', file=sys.stderr)
sys.exit(1) |
<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_notebook(self, body):
"""Save notebook depending on user provided output path.""" |
directory = os.path.dirname(self.output_path)
full_path = os.path.join(directory, self.notebook_name)
try:
with open(full_path, 'w') as fh:
fh.write(json.dumps(body, indent=2))
except ValueError:
print('ERROR: Could not save executed notebook to p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_notebook(self, data):
"""Execute input notebook and save it to file. If no output path given, the output will be printed to stdout. If any errors occ... |
self.create_notebook(data)
self.run_notebook()
self.wait_for_notebook_to_execute()
body = self.get_executed_notebook()
err = False
output = []
for paragraph in body['paragraphs']:
if 'results' in paragraph and paragraph['results']['code'] == '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 _setup_arg_parser(args_list, watcher_plugin_class, health_plugin_class):
""" Configure and return the argument parser for the command line options. If a watc... |
parser = argparse.ArgumentParser(
description="VPC router: Manage routes in VPC route table")
# General arguments
parser.add_argument('--verbose', dest="verbose", action='store_true',
help="produces more output")
parser.add_argument('-l', '--logfile', dest='l... |
<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_args(args_list, watcher_plugin_class, health_plugin_class):
""" Parse command line arguments and return relevant values in a dict. Also perform basic ... |
conf = {}
# Setting up the command line argument parser. Note that we pass the
# complete list of all plugins, so that their parameter can be added to the
# official parameter handling, the help screen, etc. Some plugins may even
# add further plugins themselves, but will handle this themselves.
... |
<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():
""" Starting point of the executable. """ |
try:
# A bit of a hack: We want to load the plugins (specified via the mode
# and health parameter) in order to add their arguments to the argument
# parser. But this means we first need to look into the CLI arguments
# to find them ... before looking at the arguments. So we first p... |
<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_plugins_info(self):
""" Collect the current live info from all the registered plugins. Return a dictionary, keyed on the plugin name. """ |
d = {}
for p in self.plugins:
d.update(p.get_info())
return 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 get_state_repr(self, path):
""" Returns the current state, or sub-state, depending on the path. """ |
if path == "ips":
return {
"failed_ips" : self.failed_ips,
"questionable_ips" : self.questionable_ips,
"working_set" : self.working_set,
}
if path == "route_info":
return {
"route_spec" : ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_json(self, path="", with_indent=False):
""" Return a rendering of the current state in JSON. """ |
if path not in self.top_level_links:
raise StateError("Unknown path")
return json.dumps(self.get_state_repr(path),
indent=4 if with_indent else 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 as_html(self, path=""):
""" Return a rendering of the current state in HTML. """ |
if path not in self.top_level_links:
raise StateError("Unknown path")
header = """
<html>
<head>
<title>VPC-router state</title>
</head>
<body>
<h3>VPC-router state</h3>
<hr>
<font 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 start(self):
""" Start the config watch thread or process. """ |
# Normally, we should start a thread or process here, pass the message
# queue self.q_route_spec to that thread and let it send route
# configurations through that queue. But since we're just sending a
# single, fixed configuration, we can just do that right here.
# Note that th... |
<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_arguments(cls, parser, sys_arg_list=None):
""" Callback to add command line options for this plugin to the argparse parser. """ |
parser.add_argument('--fixed_cidr', dest="fixed_cidr", required=True,
help="specify the route CIDR "
"(only in fixedconf mode)")
parser.add_argument('--fixed_hosts', dest="fixed_hosts", required=True,
help="list of... |
<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_arguments(cls, conf):
""" Callback to perform sanity checking for the plugin's specific parameters. """ |
# Perform sanity checking on CIDR
utils.ip_check(conf['fixed_cidr'], netmask_expected=True)
# Perform sanity checking on host list
for host in conf['fixed_hosts'].split(":"):
utils.ip_check(host) |
<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_new_working_set(self):
""" Get a new list of IPs to work with from the queue. This returns None if there is no update. Read all the messages from the que... |
new_list_of_ips = None
while True:
try:
new_list_of_ips = self.q_monitor_ips.get_nowait()
self.q_monitor_ips.task_done()
if type(new_list_of_ips) is MonitorPluginStopSignal:
raise StopReceived()
except Queue.Emp... |
<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_monitoring(self):
""" Monitor IP addresses and send notifications if one of them has failed. This function will continuously monitor q_monitor_ips for ... |
time.sleep(1)
# This is our working set. This list may be updated occasionally when
# we receive messages on the q_monitor_ips queue. But irrespective of
# any received updates, the list of IPs in here is regularly checked.
list_of_ips = []
currently_fai... |
<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_route_spec_config(data):
""" Parse and sanity check the route spec config. The config data is a blob of JSON that needs to be in this format: { "<CIDR-... |
# Sanity checking on the data object
if type(data) is not dict:
raise ValueError("Expected dictionary at top level")
try:
for k, v in data.items():
utils.ip_check(k, netmask_expected=True)
if type(v) is not list:
raise ValueError("Expect list of IPs 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 _update_health_monitor_with_new_ips(route_spec, all_ips, q_monitor_ips):
""" Take the current route spec and compare to the current list of known IP addresse... |
# Extract all the IP addresses from the route spec, unique and sorted.
new_all_ips = \
sorted(set(itertools.chain.from_iterable(route_spec.values())))
if new_all_ips != all_ips:
logging.debug("New route spec detected. Updating "
"health-monitor with: %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 _event_monitor_loop(region_name, vpc_id, watcher_plugin, health_plugin, iterations, sleep_time, route_check_time_interval=30):
""" Monitor queues to receive ... |
q_route_spec = watcher_plugin.get_route_spec_queue()
q_monitor_ips, q_failed_ips, q_questionable_ips = \
health_plugin.get_queues()
time.sleep(sleep_time) # Wait to allow monitor to report results
current_route_spec = {} # The last route spec we have ... |
<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_plugins(watcher_plugin, health_plugin):
""" Stops all plugins. """ |
logging.debug("Stopping health-check monitor...")
health_plugin.stop()
logging.debug("Stopping config change observer...")
watcher_plugin.stop() |
<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_watcher(conf, watcher_plugin_class, health_plugin_class, iterations=None, sleep_time=1):
""" Start watcher loop, listening for config changes or failed... |
if CURRENT_STATE._stop_all:
logging.debug("Not starting plugins: Global stop")
return
# Start the working threads (health monitor, config event monitor, etc.)
# and return the thread handles and message queues in a thread-info dict.
watcher_plugin, health_plugin = \
start_p... |
<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_header(self, title):
"""Generate the header for the Markdown file.""" |
header = ['---',
'title: ' + title,
'author(s): ' + self.user,
'tags: ',
'created_at: ' + str(self.date_created),
'updated_at: ' + str(self.date_updated),
'tldr: ',
'thumbnail: ',
... |
<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_code(self, lang, body):
"""Wrap text with markdown specific flavour.""" |
self.out.append("```" + lang)
self.build_markdown(lang, body)
self.out.append("```") |
<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_input(self, paragraph):
"""Parse paragraph for the language of the code and the code itself.""" |
try:
lang, body = paragraph.split(None, 1)
except ValueError:
lang, body = paragraph, None
if not lang.strip().startswith('%'):
lang = 'scala'
body = paragraph.strip()
else:
lang = lang.strip()[1:]
if lang == 'md':
... |
<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_md_row(self, row, header=False):
"""Translate row into markdown format.""" |
if not row:
return
cols = row.split('\t')
if len(cols) == 1:
self.out.append(cols[0])
else:
col_md = '|'
underline_md = '|'
if cols:
for col in cols:
col_md += col + '|'
... |
<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_output(self, fout):
"""Squash self.out into string. Join every line in self.out with a new line and write the result to the output file. """ |
fout.write('\n'.join([s for s in self.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 convert(self, json, fout):
"""Convert json to markdown. Takes in a .json file as input and convert it to Markdown format, saving the generated .png images in... |
self.build_markdown_body(json) # create the body
self.build_header(json['name']) # create the md header
self.build_output(fout) |
<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_markdown_body(self, text):
"""Generate the body for the Markdown file. - processes each json block one by one - for each block, process: - the creator ... |
key_options = {
'dateCreated': self.process_date_created,
'dateUpdated': self.process_date_updated,
'title': self.process_title,
'text': self.process_input
}
for paragraph in text['paragraphs']:
if 'user' in paragraph:
... |
<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_image(self, msg):
"""Convert base64 encoding to png. Strips msg of the base64 image encoding and outputs the images to the specified directory. """ |
result = self.find_message(msg)
if result is None:
return
self.index += 1
images_path = 'images'
if self.directory:
images_path = os.path.join(self.directory, images_path)
if not os.path.isdir(images_path):
os.makedirs(images_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 process_results(self, paragraph):
"""Route Zeppelin output types to corresponding handlers.""" |
if 'result' in paragraph and paragraph['result']['msg']:
msg = paragraph['result']['msg']
self.output_options[paragraph['result']['type']](msg) |
<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_results(self, paragraph):
"""Routes Zeppelin output types to corresponding handlers.""" |
if 'editorMode' in paragraph['config']:
mode = paragraph['config']['editorMode'].split('/')[-1]
if 'results' in paragraph and paragraph['results']['msg']:
msg = paragraph['results']['msg'][0]
if mode not in ('text', 'markdown'):
self.o... |
<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_route_spec_request():
""" Process request for route spec. Either a new one is posted or the current one is to be retrieved. """ |
try:
if bottle.request.method == 'GET':
# Just return what we currenty have cached as the route spec
data = CURRENT_STATE.route_spec
if not data:
bottle.response.status = 404
msg = "Route spec not found!"
else:
... |
<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(self):
""" Start the HTTP change monitoring thread. """ |
# Store reference to message queue in module global variable, so that
# our Bottle app handler functions have easy access to it.
global _Q_ROUTE_SPEC
_Q_ROUTE_SPEC = self.q_route_spec
logging.info("Http watcher plugin: "
"Starting to watch for route spec on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_results(function):
"""Return decorated function that caches the results.""" |
def save_to_permacache():
"""Save the in-memory cache data to the permacache.
There is a race condition here between two processes updating at the
same time. It's perfectly acceptable to lose and/or corrupt the
permacache information as each process's in-memory cache will remain
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_date(the_datetime):
"""Attempt to return a human-readable time delta string.""" |
# Source modified from
# http://stackoverflow.com/a/5164027/176978
diff = datetime.utcnow() - the_datetime
if diff.days > 7 or diff.days < 0:
return the_datetime.strftime('%A %B %d, %Y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{0} days ago'.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 update_check(package_name, package_version, bypass_cache=False, url=None, **extra_data):
"""Convenience method that outputs to stdout if an update is availab... |
checker = UpdateChecker(url)
checker.bypass_cache = bypass_cache
result = checker.check(package_name, package_version, **extra_data)
if result:
print(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 check(self, package_name, package_version, **extra_data):
"""Return a UpdateResult object if there is a newer version.""" |
data = extra_data
data['package_name'] = package_name
data['package_version'] = package_version
data['python_version'] = sys.version.split()[0]
data['platform'] = platform.platform(True) or 'Unspecified'
try:
headers = {'connection': 'close',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addMonitor(self, monitorFriendlyName, monitorURL):
""" Returns True if Monitor was added, otherwise False. """ |
url = self.baseUrl
url += "newMonitor?apiKey=%s" % self.apiKey
url += "&monitorFriendlyName=%s" % monitorFriendlyName
url += "&monitorURL=%s&monitorType=1" % monitorURL
url += "&monitorAlertContacts=%s" % monitorAlertContacts
url += "&noJsonCallback=1&format=json"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getMonitors(self, response_times=0, logs=0, uptime_ratio=''):
""" Returns status and response payload for all known monitors. """ |
url = self.baseUrl
url += "getMonitors?apiKey=%s" % (self.apiKey)
url += "&noJsonCallback=1&format=json"
# responseTimes - optional (defines if the response time data of each
# monitor will be returned. Should be set to 1 for getting them. Default
# is 0)
if resp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getMonitorById(self, monitorId):
""" Returns monitor status and alltimeuptimeratio for a MonitorId. """ |
url = self.baseUrl
url += "getMonitors?apiKey=%s&monitors=%s" % (self.apiKey, monitorId)
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
status = response.get('monitors').get('monitor')[0].get('status')
alltimeu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getMonitorByName(self, monitorFriendlyName):
""" Returns monitor status and alltimeuptimeratio for a MonitorFriendlyName. """ |
url = self.baseUrl
url += "getMonitors?apiKey=%s" % self.apiKey
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
monitors = response.get('monitors').get('monitor')
for i in range(len(monitors)):
m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def editMonitor(self, monitorID, monitorStatus=None, monitorFriendlyName=None, monitorURL=None, monitorType=None, monitorSubType=None, monitorPort=None, monitorKe... |
url = self.baseUrl
url += "editMonitor?apiKey=%s" % self.apiKey
url += "&monitorID=%s" % monitorID
if monitorStatus:
# Pause, Start Montir
url += "&monitorStatus=%s" % monitorStatus
if monitorFriendlyName:
# Update their FriendlyName
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deleteMonitorById(self, monitorID):
""" Returns True or False if monitor is deleted """ |
url = self.baseUrl
url += "deleteMonitor?apiKey=%s" % self.apiKey
url += "&monitorID=%s" % monitorID
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
return True
else:
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 getAlertContacts(self, alertContacts=None, offset=None, limit=None):
""" Get Alert Contacts """ |
url = self.baseUrl
url += "getAlertContacts?apiKey=%s" % self.apiKey
if alertContacts:
url += "&alertContacts=%s" % alertContacts
if offset:
url += "&offset=%s" % offset
if limit:
url += "&limit=%s" % limit
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromfile(file_, threadpool_size=None, ignore_lock=False):
""" Instantiate BlockStorageRAM device from a file saved in block storage format. The file_ argumen... |
close_file = False
if not hasattr(file_, 'read'):
file_ = open(file_, 'rb')
close_file = True
try:
header_data = file_.read(BlockStorageRAM._index_offset)
block_size, block_count, user_header_size, locked = \
struct.unpack(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tofile(self, file_):
""" Dump all storage data to a file. The file_ argument can be a file object or a string that represents a filename. If called with a fi... |
close_file = False
if not hasattr(file_, 'write'):
file_ = open(file_, 'wb')
close_file = True
file_.write(self._f)
if close_file:
file_.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_to_logger(fn):
""" Wrap a Bottle request so that a log line is emitted after it's handled. """ |
@wraps(fn)
def _log_to_logger(*args, **kwargs):
actual_response = fn(*args, **kwargs)
# modify this to log exactly what you need:
logger.info('%s %s %s %s' % (bottle.request.remote_addr,
bottle.request.method,
bot... |
<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_request(path):
""" Return the current status. """ |
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/html" in accept:
ret = CURRENT_STATE.as_html(path=path)
bottle.response.content_type = "text/html"
elif "application/json" in accept:
ret = CU... |
<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(self):
""" Start the HTTP server thread. """ |
logging.info("HTTP server: "
"Starting to listen for requests on '%s:%s'..." %
(self.conf['addr'], self.conf['port']))
self.my_server = MyWSGIRefServer(host=self.conf['addr'],
port=self.conf['port'],
... |
<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(self):
""" Stop the HTTP server thread. """ |
self.my_server.stop()
self.http_thread.join()
logging.info("HTTP server: Stopped") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_stats(self, responses, no_responses):
""" Maintain some stats about our requests. """ |
slowest_rtt = 0.0
slowest_ip = None
fastest_rtt = 9999999.9
fastest_ip = None
rtt_total = 0.0
for ip, rtt in responses.items():
rtt_total += rtt
if rtt > slowest_rtt:
slowest_rtt = rtt
slowest_ip = ip
... |
<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_health_checks(self, list_of_ips):
""" Perform a health check on a list of IP addresses, using ICMPecho. Return tuple with list of failed IPs and questiona... |
# Calculate a decent overall timeout time for a ping attempt: 3/4th of
# the monitoring interval. That way, we know we're done with this ping
# attempt before the next monitoring attempt is started.
ping_timeout = self.get_monitor_interval() * 0.75
# Calculate a decent number o... |
<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_arguments(cls, parser, sys_arg_list=None):
""" Arguments for the ICMPecho health monitor plugin. """ |
parser.add_argument('--icmp_check_interval',
dest='icmp_check_interval',
required=False, default=2, type=float,
help="ICMPecho interval in seconds, default 2 "
"(only for 'icmpecho' health monit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_check(ip, netmask_expected=False):
""" Sanity check that the specified string is indeed an IP address or mask. """ |
try:
if netmask_expected:
if "/" not in ip:
raise netaddr.core.AddrFormatError()
netaddr.IPNetwork(ip)
else:
netaddr.IPAddress(ip)
except netaddr.core.AddrFormatError:
if netmask_expected:
raise ArgsError("Not a valid CIDR ... |
<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_valid_ip_or_cidr(val, return_as_cidr=False):
""" Checks that the value is a valid IP address or a valid CIDR. Returns the specified value. If 'return_a... |
is_ip = True
if "/" in val:
ip_check(val, netmask_expected=True)
is_ip = False
else:
ip_check(val, netmask_expected=False)
if return_as_cidr and is_ip:
# Convert a plain IP to a CIDR
if val == "0.0.0.0":
# Special case for the default route
... |
<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_cidr_in_cidr(small_cidr, big_cidr):
""" Return True if the small CIDR is contained in the big CIDR. """ |
# The default route (0.0.0.0/0) is handled differently, since every route
# would always be contained in there. Instead, only a small CIDR of
# "0.0.0.0/0" can match against it. Other small CIDRs will always result in
# 'False' (not contained).
if small_cidr == "0.0.0.0/0":
return big_cidr ... |
<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_last_msg_from_queue(q):
""" Read all messages from a queue and return the last one. This is useful in many cases where all messages are always the compl... |
msg = None
while True:
try:
# The list of IPs is always a full list.
msg = q.get_nowait()
q.task_done()
except Queue.Empty:
# No more messages, all done for now
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def param_extract(args, short_form, long_form, default=None):
""" Quick extraction of a parameter from the command line argument list. In some cases we need to p... |
val = default
for i, a in enumerate(args):
# Long form may use "--xyz=foo", so need to split on '=', but it
# doesn't necessarily do that, can also be "--xyz foo".
elems = a.split("=", 1)
if elems[0] in [short_form, long_form]:
# At least make sure that an actual nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base10_integer_to_basek_string(k, x):
"""Convert an integer into a base k string.""" |
if not (2 <= k <= max_k_labeled):
raise ValueError("k must be in range [2, %d]: %s"
% (max_k_labeled, k))
return ((x == 0) and numerals[0]) or \
(base10_integer_to_basek_string(k, x // k).\
lstrip(numerals[0]) + numerals[x % k]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def basek_string_to_base10_integer(k, x):
"""Convert a base k string into an integer.""" |
assert 1 < k <= max_k_labeled
return sum(numeral_index[c]*(k**i)
for i, c in enumerate(reversed(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 calculate_bucket_level(k, b):
""" Calculate the level in which a 0-based bucket lives inside of a k-ary heap. """ |
assert k >= 2
if k == 2:
return log2floor(b+1)
v = (k - 1) * (b + 1) + 1
h = 0
while k**(h+1) < v:
h += 1
return h |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_last_common_level(k, b1, b2):
""" Calculate the highest level after which the paths from the root to these buckets diverge. """ |
l1 = calculate_bucket_level(k, b1)
l2 = calculate_bucket_level(k, b2)
while l1 > l2:
b1 = (b1-1)//k
l1 -= 1
while l2 > l1:
b2 = (b2-1)//k
l2 -= 1
while b1 != b2:
b1 = (b1-1)//k
b2 = (b2-1)//k
l1 -= 1
return l1 |
<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_as_dot(self, f, data=None, max_levels=None):
"Write the tree in the dot language format to f."
assert (max_levels is None) or (max_levels >= 0)
def visit_node(n, levels):
lbl = "{"
if data is None:
if self.k <= max_k_labeled:
... |
<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_image_as_pdf(self, filename, data=None, max_levels=None):
"Write the heap as PDF file."
assert (max_levels is None) or (max_levels >= 0)
import os
if not filename.endswith('.pdf'):
filename = filename+'.pdf'
tmpfd, tmpname = tempfile.mkstemp(suffix='dot')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.