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 _is_pickle_valid(self):
"""Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ |
if not os.path.exists(self._pickle_file):
return False
else:
file_mtime = os.path.getmtime(self.logfile)
pickle_mtime = os.path.getmtime(self._pickle_file)
if file_mtime > pickle_mtime:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load(self):
"""Load data from a pickle file. """ |
with open(self._pickle_file, 'rb') as source:
pickler = pickle.Unpickler(source)
for attribute in self._pickle_attributes:
pickle_data = pickler.load()
setattr(self, attribute, pickle_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 _save(self):
"""Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be proce... |
with open(self._pickle_file, 'wb') as source:
pickler = pickle.Pickler(source, pickle.HIGHEST_PROTOCOL)
for attribute in self._pickle_attributes:
attr = getattr(self, attribute, None)
pickler.dump(attr) |
<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_data(self, logfile):
"""Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ |
for line in logfile:
stripped_line = line.strip()
parsed_line = Line(stripped_line)
if parsed_line.valid:
self._valid_lines.append(parsed_line)
else:
self._invalid_lines.append(stripped_line)
self.total_lines = len(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 filter(self, filter_func, reverse=False):
"""Filter current log lines by a given filter function. This allows to drill down data out of the log file by filte... |
new_log_file = Log()
new_log_file.logfile = self.logfile
new_log_file.total_lines = 0
new_log_file._valid_lines = []
new_log_file._invalid_lines = self._invalid_lines[:]
# add the reverse conditional outside the loop to keep the loop as
# straightforward as po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commands(cls):
"""Returns a list of all methods that start with ``cmd_``.""" |
cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')]
return 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 cmd_ip_counter(self):
"""Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header w... |
ip_counter = defaultdict(int)
for line in self._valid_lines:
ip = line.get_ip()
if ip is not None:
ip_counter[ip] += 1
return ip_counter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_status_codes_counter(self):
"""Generate statistics about HTTP status codes. 404, 500 and so on. """ |
status_codes = defaultdict(int)
for line in self._valid_lines:
status_codes[line.status_code] += 1
return status_codes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_request_path_counter(self):
"""Generate statistics about HTTP requests' path.""" |
paths = defaultdict(int)
for line in self._valid_lines:
paths[line.http_request_path] += 1
return paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_slow_requests(self):
"""List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 millisecond... |
slow_requests = [
line.time_wait_response
for line in self._valid_lines
if line.time_wait_response > 1000
]
return slow_requests |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_average_response_time(self):
"""Returns the average response time of all, non aborted, requests.""" |
average = [
line.time_wait_response
for line in self._valid_lines
if line.time_wait_response >= 0
]
divisor = float(len(average))
if divisor > 0:
return sum(average) / float(len(average))
return 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 cmd_average_waiting_time(self):
"""Returns the average queue time of all, non aborted, requests.""" |
average = [
line.time_wait_queues
for line in self._valid_lines
if line.time_wait_queues >= 0
]
divisor = float(len(average))
if divisor > 0:
return sum(average) / float(len(average))
return 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 cmd_server_load(self):
"""Generate statistics regarding how many requests were processed by each downstream server. """ |
servers = defaultdict(int)
for line in self._valid_lines:
servers[line.server_name] += 1
return servers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_queue_peaks(self):
"""Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series o... |
threshold = 1
peaks = []
current_peak = 0
current_queue = 0
current_span = 0
first_on_queue = None
for line in self._valid_lines:
current_queue = line.queue_backend
if current_queue > 0:
current_span += 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 cmd_connection_type(self):
"""Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the req... |
https = 0
non_https = 0
for line in self._valid_lines:
if line.is_https():
https += 1
else:
non_https += 1
return https, non_https |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_requests_per_minute(self):
"""Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` an... |
if len(self._valid_lines) == 0:
return
current_minute = self._valid_lines[0].accept_date
current_minute_counter = 0
requests = []
one_minute = timedelta(minutes=1)
def format_and_append(append_to, date, counter):
seconds_and_micro = timedelta(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_print(self):
"""Returns the raw lines to be printed.""" |
if not self._valid_lines:
return ''
return '\n'.join([line.raw_line for line in self._valid_lines]) + '\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 _sort_lines(self):
"""Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick... |
self._valid_lines = sorted(
self._valid_lines,
key=lambda line: line.accept_date,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sort_and_trim(data, reverse=False):
"""Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is ... |
threshold = 10
data_list = data.items()
data_list = sorted(
data_list,
key=lambda data_info: data_info[1],
reverse=reverse,
)
return data_list[:threshold] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_access_point(func):
""" Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the fun... |
@wraps(func)
def wrapper(self, *args, **kwargs):
"""
Wrapper responsible for handling
sessions
"""
session = self.session_handler.get_session()
try:
resp = func(self, session, *args, **kwargs)
except Exception as exc:
self.session_... |
<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_field_python_type(model, name):
""" Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model... |
try:
return getattr(model, name).property.columns[0].type.python_type
except AttributeError: # It's a relationship
parts = name.split('.')
model = getattr(model, parts.pop(0)).comparator.mapper.class_
return AlchemyManager._get_field_python_type(model, '... |
<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_field_type(cls, name):
""" Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manage... |
python_type = cls._get_field_python_type(cls.model, name)
if python_type in _COLUMN_FIELD_MAP:
field_class = _COLUMN_FIELD_MAP[python_type]
return field_class(name)
return BaseField(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 create(self, session, values, *args, **kwargs):
""" Creates a new instance of the self.model and persists it to the database. :param dict values: The diction... |
model = self.model()
model = self._set_values_on_model(model, values, fields=self.create_fields)
session.add(model)
session.commit()
return self.serialize_model(model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve(self, session, lookup_keys, *args, **kwargs):
""" Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_... |
model = self._get_model(lookup_keys, session)
return self.serialize_model(model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_list(self, session, filters, *args, **kwargs):
""" Retrieves a list of the model for this manager. It is restricted by the filters provided. :param ... |
query = self.queryset(session)
translator = IntegerField('tmp')
pagination_count = translator.translate(
filters.pop(self.pagination_count_query_arg, self.paginate_by)
)
pagination_pk = translator.translate(
filters.pop(self.pagination_pk_query_arg, 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 update(self, session, lookup_keys, updates, *args, **kwargs):
""" Updates the model with the specified lookup_keys and returns the dictified object. :param S... |
model = self._get_model(lookup_keys, session)
model = self._set_values_on_model(model, updates, fields=self.update_fields)
session.commit()
return self.serialize_model(model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, session, lookup_keys, *args, **kwargs):
""" Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use ... |
model = self._get_model(lookup_keys, session)
session.delete(model)
session.commit()
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 serialize_model(self, model, field_dict=None):
""" Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy mod... |
response = self._serialize_model_helper(model, field_dict=field_dict)
return make_json_safe(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 _serialize_model_helper(self, model, field_dict=None):
""" A recursive function for serializing a model into a json ready format. """ |
field_dict = field_dict or self.dot_field_list_to_dict()
if model is None:
return None
if isinstance(model, Query):
model = model.all()
if isinstance(model, (list, set)):
return [self.serialize_model(m, field_dict=field_dict) for m in model]
... |
<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_model(self, lookup_keys, session):
""" Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the ... |
try:
return self.queryset(session).filter_by(**lookup_keys).one()
except NoResultFound:
raise NotFoundException('No model of type {0} was found using '
'lookup_keys {1}'.format(self.model.__name__, lookup_keys)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_values_on_model(self, model, values, fields=None):
""" Updates the values with the specified values. :param Model model: The sqlalchemy model instance :... |
fields = fields or self.fields
for name, val in six.iteritems(values):
if name not in fields:
continue
setattr(model, name, val)
return model |
<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_commands():
"""Prints all commands available from Log with their description. """ |
dummy_log_file = Log()
commands = Log.commands()
commands.sort()
for cmd in commands:
cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd))
description = cmd.__doc__
if description:
description = re.sub(r'\n\s+', ' ', description)
description = descriptio... |
<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_filters():
"""Prints all filters available with their description.""" |
for filter_name in VALID_FILTERS:
filter_func = getattr(filters, 'filter_{0}'.format(filter_name))
description = filter_func.__doc__
if description:
description = re.sub(r'\n\s+', ' ', description)
description.strip()
print('{0}: {1}\n'.format(filter_name, 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 remove_all_observers(self):
""" Removes all registered observers. """ |
for weak_observer in self._weak_observers:
observer = weak_observer()
if observer:
self.remove_observer(observer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startThread(self):
"""Spawns new NSThread to handle notifications.""" |
if self._thread is not None:
return
self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None)
self._thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stopThread(self):
"""Stops spawned NSThread.""" |
if self._thread is not None:
self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES)
self._thread = 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 runPowerNotificationsThread(self):
"""Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" |
pool = NSAutoreleasePool.alloc().init()
@objc.callbackFor(IOPSNotificationCreateRunLoopSource)
def on_power_source_notification(context):
with self._lock:
for weak_observer in self._weak_observers:
observer = weak_observer()
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 stopPowerNotificationsThread(self):
"""Removes the only source from NSRunLoop and cancels thread.""" |
assert NSThread.currentThread() == self._thread
CFRunLoopSourceInvalidate(self._source)
self._source = None
NSThread.currentThread().cancel() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeObserver(self, observer):
""" Removes an observer. @param observer: Previously added observer """ |
with self._lock:
self._weak_observers.remove(weakref.ref(observer))
if len(self._weak_observers) == 0:
self.stopThread() |
<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_time_remaining_estimate(self):
""" In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemain... |
if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+
estimate = float(IOPSGetTimeRemainingEstimate())
if estimate == -1.0:
return common.TIME_REMAINING_UNKNOWN
elif estimate == -2.0:
return common.TIME_REMAINING_UNLIMITED
... |
<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_observer(self, observer):
""" Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ |
super(PowerManagement, self).add_observer(observer)
if len(self._weak_observers) == 1:
if not self._cf_run_loop:
PowerManagement.notifications_observer.addObserver(self)
else:
@objc.callbackFor(IOPSNotificationCreateRunLoopSource)
... |
<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_observer(self, observer):
""" Stops thread and invalidates source. """ |
super(PowerManagement, self).remove_observer(observer)
if len(self._weak_observers) == 0:
if not self._cf_run_loop:
PowerManagement.notifications_observer.removeObserver(self)
else:
CFRunLoopSourceInvalidate(self._source)
self._sou... |
<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_low_battery_warning_level(self):
""" Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC return... |
all_energy_full = []
all_energy_now = []
all_power_now = []
try:
type = self.power_source_type()
if type == common.POWER_TYPE_AC:
if self.is_ac_online():
return common.LOW_BATTERY_WARNING_NONE
elif type == common.PO... |
<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_type(self, s):
""" Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a s... |
# TODO: what if the number is bigger than an int or float?
if s.startswith('"') and s.endswith('"'):
return s[1:-1]
elif s.find('.') != -1:
return float(s)
else:
return int(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 _escape(self, msg):
""" Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Ret... |
escaped = ''
for c in msg:
escaped += c
if c == '"':
escaped += '"'
return escaped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unescape(self, msg):
""" Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns ... |
if isinstance(msg, (int, float, long)):
return msg
unescaped = ''
i = 0
while i < len(msg):
unescaped += msg[i]
if msg[i] == '"':
i+=1
i+=1
return unescaped |
<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_msg(self, msg):
""" Returns True if message is a proper Scratch message, else return False. """ |
if not msg or len(msg) < self.prefix_len:
return False
length = self._extract_len(msg[:self.prefix_len])
msg_type = msg[self.prefix_len:].split(' ', 1)[0]
if length == len(msg[self.prefix_len:]) and msg_type in self.msg_types:
return True
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 _parse_broadcast(self, msg):
""" Given a broacast message, returns the message that was broadcast. """ |
# get message, remove surrounding quotes, and unescape
return self._unescape(self._get_type(msg[self.broadcast_prefix_len:])) |
<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(self, msg):
""" Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload... |
if not self._is_msg(msg):
return None
msg_type = msg[self.prefix_len:].split(' ')[0]
if msg_type == 'broadcast':
return ('broadcast', self._parse_broadcast(msg))
else:
return ('sensor-update', self._parse_sensorupdate(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 _write(self, data):
""" Writes string data out to Scratch """ |
total_sent = 0
length = len(data)
while total_sent < length:
try:
sent = self.socket.send(data[total_sent:])
except socket.error as (err, msg):
self.connected = False
raise ScratchError("[Errno %d] %s" % (err, 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 _read(self, size):
""" Reads size number of bytes from Scratch and returns data as a string """ |
data = ''
while len(data) < size:
try:
chunk = self.socket.recv(size-len(data))
except socket.error as (err, msg):
self.connected = False
raise ScratchError("[Errno %d] %s" % (err, msg))
if chunk == '':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recv(self):
""" Receives and returns a message from Scratch """ |
prefix = self._read(self.prefix_len)
msg = self._read(self._extract_len(prefix))
return prefix + 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 connect(self):
""" Connects to Scratch. """ |
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect((self.host, self.port))
except socket.error as (err, msg):
self.connected = False
raise ScratchError("[Errno %d] %s" % (err, msg))
self.connected = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
""" Closes connection to Scratch """ |
try: # connection may already be disconnected, so catch exceptions
self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect
except socket.error:
pass
self.socket.close()
self.connected = 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 sensorupdate(self, data):
""" Given a dict of sensors and values, updates those sensors with the values in Scratch. """ |
if not isinstance(data, dict):
raise TypeError('Expected a dict')
msg = 'sensor-update '
for key in data.keys():
msg += '"%s" "%s" ' % (self._escape(str(key)),
self._escape(str(data[key])))
self._send(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 run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None):
"""Tests a simple topology. "Simple" means there it has no branches... |
# The config is almost always required. The only known reason to pass
# None is when calling run_simple_topology() multiple times for the
# same components. This can be useful for testing spout ack() and fail()
# behavior.
if config is not None:
for emitter ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, stream):
"""Writes the topology to a stream or file.""" |
topology = self.createTopology()
def write_it(stream):
transportOut = TMemoryBuffer()
protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut)
topology.write(protocolOut)
bytes = transportOut.getvalue()
stream.write(bytes)
if isins... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, stream):
"""Reads the topology from a stream or file.""" |
def read_it(stream):
bytes = stream.read()
transportIn = TMemoryBuffer(bytes)
protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn)
topology = StormTopology()
topology.read(protocolIn)
return topology
if isinstance... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emitMany(*args, **kwargs):
"""A more efficient way to emit a number of tuples at once.""" |
global MODE
if MODE == Bolt:
emitManyBolt(*args, **kwargs)
elif MODE == Spout:
emitManySpout(*args, **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 remote_debug(sig,frame):
"""Handler to allow process to be remotely debugged.""" |
def _raiseEx(ex):
"""Raise specified exception in the remote process"""
_raiseEx.ex = ex
_raiseEx.ex = None
try:
# Provide some useful functions.
locs = {'_raiseEx' : _raiseEx}
locs.update(frame.f_locals) # Unless shadowed.
globs = frame.f_globals
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug_process(pid):
"""Interrupt a running process and debug it.""" |
os.kill(pid, signal.SIGUSR1) # Signal process.
pipe = NamedPipe(pipename(pid), 1)
try:
while pipe.is_open():
txt=raw_input(pipe.get()) + '\n'
pipe.put(txt)
except EOFError:
pass # Exit.
pipe.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 _encode_utf8(self, **kwargs):
""" UTF8 encodes all of the NVP values. """ |
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], t... |
<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_required(self, requires, **kwargs):
""" Checks kwargs for the values specified in 'requires', which is a tuple of strings. These strings are the NVP n... |
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req) |
<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_call_params(self, method, **kwargs):
""" Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` th... |
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method. ``email``:: Email address of a PayPal member to verify. Maximum string le... |
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args) |
<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_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transac... |
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args) |
<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_capture(self, authorizationid, amt, completetype='Complete', **kwargs):
"""Shortcut for the DoCapture method. Use the TRANSACTIONID from DoAuthorization, ... |
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **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 do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method. ``paymentaction`` could be 'Authorization' or 'Sale' To ... |
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **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 transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method. Returns a PayPalResponseList object, which merges the L_ syntax list to a l... |
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout. Express Checkouts ... |
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
Runtim... |
<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_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment... |
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def manage_recurring_payments_profile_status(self, profileid, action, note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` i... |
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args) |
<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_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method. ``profileid`` is the same profile id ... |
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **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 bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method. See the docs for details on arguments: https://cms.paypal.com/mx/cgi-bin/?cmd=_re... |
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **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 success(self):
""" Checks for the presence of errors in the response. Returns ``True`` if all is well, ``False`` otherwise. :rtype: bool :returns ``True`` if... |
return self.ack.upper() in (self.config.ACK_SUCCESS,
self.config.ACK_SUCCESS_WITH_WARNING) |
<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_valid_country_abbrev(abbrev, case_sensitive=False):
""" Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Cou... |
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return True
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 get_name_from_abbrev(abbrev, case_sensitive=False):
""" Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to re... |
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return full_name
raise KeyError('No country with that country code.') |
<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_declared_fields(mcs, klass, *args, **kwargs):
"""Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Met... |
declared_fields = kwargs.get('dict_class', dict)()
# Generate the fields provided through inheritance
opts = klass.opts
model = getattr(opts, 'model', None)
if model:
converter = opts.model_converter()
declared_fields.update(converter.fields_for_model(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loop_misc(self):
"""Misc loop.""" |
self.check_keepalive()
if self.last_retry_check + 1 < time.time():
pass
return NC.ERR_SUCCESS |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def packet_handle(self):
"""Incoming packet handler dispatcher.""" |
cmd = self.in_packet.command & 0xF0
if cmd == NC.CMD_CONNACK:
return self.handle_connack()
elif cmd == NC.CMD_PINGRESP:
return self.handle_pingresp()
elif cmd == NC.CMD_PUBLISH:
return self.handle_publish()
elif cmd == NC.CMD_PUBACK:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscribe(self, topic, qos):
"""Subscribe to some topic.""" |
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("SUBSCRIBE: %s", topic)
return self.send_subscribe(False, [(utf8encode(topic), qos)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(self, topic):
"""Unsubscribe to some topic.""" |
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("UNSUBSCRIBE: %s", topic)
return self.send_unsubscribe(False, [utf8encode(topic)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe_multi(self, topics):
"""Unsubscribe to some topics.""" |
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("UNSUBSCRIBE: %s", ', '.join(topics))
return self.send_unsubscribe(False, [utf8encode(topic) for topic in topics]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_subscribe(self, dup, topics):
"""Send subscribe COMMAND to server.""" |
pkt = MqttPkt()
pktlen = 2 + sum([2+len(topic)+1 for (topic, qos) in topics])
pkt.command = NC.CMD_SUBSCRIBE | (dup << 3) | (1 << 1)
pkt.remaining_length = pktlen
ret = pkt.alloc()
if ret != NC.ERR_SUCCESS:
return ret
#varia... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_unsubscribe(self, dup, topics):
"""Send unsubscribe COMMAND to server.""" |
pkt = MqttPkt()
pktlen = 2 + sum([2+len(topic) for topic in topics])
pkt.command = NC.CMD_UNSUBSCRIBE | (dup << 3) | (1 << 1)
pkt.remaining_length = pktlen
ret = pkt.alloc()
if ret != NC.ERR_SUCCESS:
return ret
#variable hea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, topic, payload = None, qos = 0, retain = False):
"""Publish some payload to server.""" |
#print "PUBLISHING (",topic,"): ", payload
payloadlen = len(payload)
if topic is None or qos < 0 or qos > 2:
print "PUBLISH:err inval"
return NC.ERR_INVAL
#payloadlen <= 250MB
if payloadlen > (250 * 1024 * 1204):
self.logger.error("PU... |
<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_connack(self):
"""Handle incoming CONNACK command.""" |
self.logger.info("CONNACK reveived")
ret, flags = self.in_packet.read_byte()
if ret != NC.ERR_SUCCESS:
self.logger.error("error read byte")
return ret
# useful for v3.1.1 only
session_present = flags & 0x01
ret, retcode = self.in_packet.... |
<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_pingresp(self):
"""Handle incoming PINGRESP packet.""" |
self.logger.debug("PINGRESP received")
self.push_event(event.EventPingResp())
return NC.ERR_SUCCESS |
<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_suback(self):
"""Handle incoming SUBACK packet.""" |
self.logger.info("SUBACK received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
qos_count = self.in_packet.remaining_length - self.in_packet.pos
granted_qos = bytearray(qos_count)
if granted... |
<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_unsuback(self):
"""Handle incoming UNSUBACK packet.""" |
self.logger.info("UNSUBACK received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventUnsuback(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
<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_publish(self):
"""Handle incoming PUBLISH packet.""" |
self.logger.debug("PUBLISH received")
header = self.in_packet.command
message = NyamukMsgAll()
message.direction = NC.DIRECTION_IN
message.dup = (header & 0x08) >> 3
message.msg.qos = (header & 0x06) >> 1
message.msg.retain = (header & 0x01)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_publish(self, mid, topic, payload, qos, retain, dup):
"""Send PUBLISH.""" |
self.logger.debug("Send PUBLISH")
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
#NOTE: payload may be any kind of data
# yet if it is a unicode string we utf8-encode it as convenience
return self._do_send_publish(mid, utf8encode(topic), utf8encode(pa... |
<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_puback(self):
"""Handle incoming PUBACK packet.""" |
self.logger.info("PUBACK received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPuback(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
<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_pubrec(self):
"""Handle incoming PUBREC packet.""" |
self.logger.info("PUBREC received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubrec(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
<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_pubrel(self):
"""Handle incoming PUBREL packet.""" |
self.logger.info("PUBREL received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubrel(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
<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_pubcomp(self):
"""Handle incoming PUBCOMP packet.""" |
self.logger.info("PUBCOMP received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubcomp(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pubrec(self, mid):
"""Send PUBREC response to server.""" |
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("Send PUBREC (msgid=%s)", mid)
pkt = MqttPkt()
pkt.command = NC.CMD_PUBREC
pkt.remaining_length = 2
ret = pkt.alloc()
if ret != NC.ERR_SUCCESS:
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 connect(sock, addr):
"""Connect to some addr.""" |
try:
sock.connect(addr)
except ssl.SSLError as e:
return (ssl.SSLError, e.strerror if e.strerror else e.message)
except socket.herror as (_, msg):
return (socket.herror, msg)
except socket.gaierror as (_, msg):
return (socket.gaierror, msg)
except socket.timeout:
... |
<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(sock, count):
"""Read from socket and return it's byte array representation. count = number of bytes to read """ |
data = None
try:
data = sock.recv(count)
except ssl.SSLError as e:
return data, e.errno, e.strerror if strerror else e.message
except socket.herror as (errnum, errmsg):
return data, errnum, errmsg
except socket.gaierror as (errnum, errmsg):
return data, errnum, errm... |
<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(sock, payload):
"""Write payload to socket.""" |
try:
length = sock.send(payload)
except ssl.SSLError as e:
return -1, (ssl.SSLError, e.strerror if strerror else e.message)
except socket.herror as (_, msg):
return -1, (socket.error, msg)
except socket.gaierror as (_, msg):
return -1, (socket.gaierror, msg)
except s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.