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 processed every time. """
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._valid_lines) + len(self._invalid_lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are :param filter_func: [required] Filter method, see filters.py for all available filters. :type filter_func: function :param reverse: negate the filter (so accept all log lines that return ``False``). :type reverse: boolean :returns: a new instance of Log containing only log lines that passed the filter function. :rtype: :class:`Log` """
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 possible if not reverse: for i in self._valid_lines: if filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) else: for i in self._valid_lines: if not filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) return new_log_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 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 with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """
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 milliseconds), improve the command line interface to allow to send parameters to each command or globally. """
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 of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently set to 1. """
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 if first_on_queue is None: first_on_queue = line.accept_date if current_queue == 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) current_peak = 0 current_span = 0 first_on_queue = None if current_queue > current_peak: current_peak = current_queue # case of a series that does not end if current_queue > 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) return peaks
<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 request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable. """
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`` and ``-d``) as this command output can be huge otherwise. """
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( seconds=date.second, microseconds=date.microsecond, ) minute_formatted = date - seconds_and_micro append_to.append((minute_formatted, counter)) # note that _valid_lines is kept sorted by date for line in self._valid_lines: line_date = line.accept_date if line_date - current_minute < one_minute and \ line_date.minute == current_minute.minute: current_minute_counter += 1 else: format_and_append( requests, current_minute, current_minute_counter, ) current_minute_counter = 1 current_minute = line_date if current_minute_counter > 0: format_and_append( requests, current_minute, current_minute_counter, ) return 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_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 but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server. """
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 hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally. """
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 function has run. :param method func: The method that is interacting with the database. """
@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_handler.handle_session(session, exc=exc) raise exc else: self.session_handler.handle_session(session) return resp return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype: type """
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, '.'.join(parts)) except NotImplementedError: # This is for pickle type columns. return object
<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 manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a string input into the appropriate format. :rtype: ripozo.viewsets.fields.base.BaseField """
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 dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will use those fields. Otherwise, it will use the fields defined in cls.fields :param Session session: The sqlalchemy session :return: The serialized model. It will use the self.fields attribute for this. :rtype: dict """
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_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """
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 Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation of the models and the dictionary of meta data :rtype: list, dict """
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) ) pagination_pk -= 1 # logic works zero based. Pagination shouldn't be though query = query.filter_by(**filters) if pagination_pk: query = query.offset(pagination_pk * pagination_count) if pagination_count: query = query.limit(pagination_count + 1) count = query.count() next_link = None previous_link = None if count > pagination_count: next_link = {self.pagination_pk_query_arg: pagination_pk + 2, self.pagination_count_query_arg: pagination_count} if pagination_pk > 0: previous_link = {self.pagination_pk_query_arg: pagination_pk, self.pagination_count_query_arg: pagination_count} field_dict = self.dot_field_list_to_dict(self.list_fields) props = self.serialize_model(query[:pagination_count], field_dict=field_dict) meta = dict(links=dict(next=next_link, previous=previous_link)) return props, meta
<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 Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to update them to. :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """
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 :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException """
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 model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict """
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] model_dict = {} for name, sub in six.iteritems(field_dict): value = getattr(model, name) if sub: value = self.serialize_model(value, field_dict=sub) model_dict[name] = value return model_dict
<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 keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance. """
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 :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :return: The model with the updated :rtype: Model """
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 = description.strip() print('{0}: {1}\n'.format(cmd.__name__, description))
<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, description))
<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() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop().getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) del pool
<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 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """
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 else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn("IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN
<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) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode)
<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._source = 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 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 returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """
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.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_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 _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 string, int or float. """
# 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. Returns a new escaped string. """
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 a new unescaped string. """
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. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose keys are variables, and values are updated variable values. Returns None if msg is not a message. """
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)) if sent == 0: self.connected = False raise ScratchConnectionError("Connection broken") total_sent += sent
<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 == '': self.connected = False raise ScratchConnectionError("Connection broken") data += chunk return 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 _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 or cycles. "emitters" is a list of emitters, starting with a spout followed by 0 or more bolts that run in a chain."""
# 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 in emitters: emitter.initialize(config, {}) with cls() as self: # Read from the spout. spout = emitters[0] spout_id = self.emitter_id(spout) old_length = -1 length = len(self.pending[spout_id]) while length > old_length and (max_spout_emits is None or length < max_spout_emits): old_length = length self.activate(spout) spout.nextTuple() length = len(self.pending[spout_id]) # For each bolt in the sequence, consume all upstream input. for i, bolt in enumerate(emitters[1:]): previous = emitters[i] self.activate(bolt) while len(self.pending[self.emitter_id(previous)]) > 0: bolt.process(self.read(previous)) def make_storm_tuple(t, emitter): return t def make_python_list(t, emitter): return list(t.values) def make_python_tuple(t, emitter): return tuple(t.values) def make_named_tuple(t, emitter): return self.get_output_type(emitter)(*t.values) if result_type == STORM_TUPLE: make = make_storm_tuple elif result_type == LIST: make = make_python_list elif result_type == NAMEDTUPLE: make = make_named_tuple else: assert False, 'Invalid result type specified: %s' % result_type result_values = \ [ [ make(t, emitter) for t in self.processed[self.emitter_id(emitter)]] for emitter in emitters[:-1] ] + \ [ [ make(t, emitters[-1]) for t in self.pending[self.emitter_id(emitters[-1])] ] ] return dict((k, v) for k, v in zip(emitters, result_values))
<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 isinstance(stream, six.string_types): with open(stream, 'wb') as f: write_it(f) else: write_it(stream) return topology
<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(stream, six.string_types): with open(stream, 'rb') as f: return read_it(f) else: return read_it(stream)
<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 pid = os.getpid() # Use pipe name based on pid pipe = NamedPipe(pipename(pid)) old_stdout, old_stderr = sys.stdout, sys.stderr txt = '' pipe.put("Interrupting process at following point:\n" + ''.join(traceback.format_stack(frame)) + ">>> ") try: while pipe.is_open() and _raiseEx.ex is None: line = pipe.get() if line is None: continue # EOF txt += line try: code = codeop.compile_command(txt) if code: sys.stdout = six.StringIO() sys.stderr = sys.stdout six.exec_(code, globs, locs) txt = '' pipe.put(sys.stdout.getvalue() + '>>> ') else: pipe.put('... ') except: txt='' # May be syntax err. sys.stdout = six.StringIO() sys.stderr = sys.stdout traceback.print_exc() pipe.put(sys.stdout.getvalue() + '>>> ') finally: sys.stdout = old_stdout # Restore redirected output. sys.stderr = old_stderr pipe.close() except Exception: # Don't allow debug exceptions to propogate to real program. traceback.print_exc() if _raiseEx.ex is not None: raise _raiseEx.ex
<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], types.UnicodeType): unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8') return unencoded_pairs
<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 names of the required values. """
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`` the NVP method ``kwargs`` the actual call parameters """
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'] = self.config.API_SIGNATURE elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.config.API_PASSWORD certificate = (self.config.API_CERTIFICATE_FILENAME, self.config.API_KEY_FILENAME) elif self.config.API_AUTHENTICATION_MODE == "UNIPAY": payload['SUBJECT'] = self.config.UNIPAY_SUBJECT none_configs = [config for config, value in payload.items() if value is None] if none_configs: raise PayPalConfigError( "Config(s) %s cannot be None. Please, check this " "interface's config." % none_configs) # all keys in the payload must be uppercase for key, value in kwargs.items(): payload[key.upper()] = value return {'data': payload, 'cert': certificate, 'url': self.config.API_ENDPOINT, 'timeout': self.config.HTTP_TIMEOUT, 'verify': self.config.API_CA_CERTS}
<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 length: 255 single-byte characters Input mask: ?@?.?? ``street``:: First line of the billing or shipping postal address to verify. To pass verification, the value of Street must match the first three single-byte characters of a postal address on file for the PayPal member. Maximum string length: 35 single-byte characters. Alphanumeric plus - , . ‘ # \ Whitespace and case of input value are ignored. ``zip``:: Postal code to verify. To pass verification, the value of Zip mustmatch the first five single-byte characters of the postal code of the verified postal address for the verified PayPal member. Maximumstring length: 16 single-byte characters. Whitespace and case of input value are ignored. """
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 ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` should be the same as passed to `DoExpressCheckoutPayment`. Flow for a payment involving a `DoAuthorization` call:: 1. One or many calls to `SetExpressCheckout` with pertinent order details, returns `TOKEN` 1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to Order, `AMT` set to the amount of the transaction, returns `TRANSACTIONID` 1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the amount of the transaction. 1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID` returned by `DoAuthorization`) """
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, DoDirectPayment or DoExpressCheckoutPayment for the ``authorizationid``. The `amt` should be the same as the authorized transaction. """
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 issue a Sale immediately:: charge = { 'amt': '10.00', 'creditcardtype': 'Visa', 'acct': '4812177017895760', 'expdate': '012010', 'cvv2': '962', 'firstname': 'John', 'lastname': 'Doe', 'street': '1 Main St', 'city': 'San Jose', 'state': 'CA', 'zip': '95131', 'countrycode': 'US', 'currencycode': 'USD', } direct_payment("Sale", **charge) Or, since "Sale" is the default: direct_payment(**charge) To issue an Authorization, simply pass "Authorization" instead of "Sale". You may also explicitly set ``paymentaction`` as a keyword argument: direct_payment(paymentaction="Sale", **charge) """
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 list of dictionaries with properly named keys. Note that the API will limit returned transactions to 100. Required Kwargs * STARTDATE Optional Kwargs STATUS = one of ['Pending','Processing','Success','Denied','Reversed'] """
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 must be verified by the customer by redirecting them to the PayPal website. Use the token returned in the response from :meth:`set_express_checkout` with this function to figure out where to redirect the user to. The button text on the PayPal page can be controlled via `useraction`. The documented possible values are `commit` and `continue`. However, any other value will only result in a warning. :param str token: The unique token identifying this transaction. :param str useraction: Control the button text on the PayPal page. :rtype: str :returns: The URL to redirect the user to for approval. """
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, RuntimeWarning) url += '&useraction=%s' % useraction return url
<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 plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile was created as well as default values for ignored fields and some pertinent stastics. e.g.: response = create_recurring_payments_profile(**profile_info) profileid = response.PROFILEID details = get_recurring_payments_profile(profileid) The response from PayPal is somewhat self-explanatory, but for a description of each field, visit the following URI: https://www.x.com/docs/DOC-1194 """
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`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the change in status. """
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 used for getting profile details. The keyed arguments are data in the payment profile which you wish to change. The profileid does not change. Anything else will take the new value. Most of, though not all of, the fields available are shared with creating a profile, but for the complete list of parameters, you can visit the following URI: https://www.x.com/docs/DOC-1212 """
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=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton The L_BUTTONVARn fields are especially important, so make sure to read those and act accordingly. See unit tests for some examples. """
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 PayPal says our query was successful. """
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) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not. """
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 retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity. """
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 Meta option. """
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( model, fields=opts.fields )) # Generate the fields provided in the current class base_fields = super(SchemaMeta, mcs).get_declared_fields( klass, *args, **kwargs ) declared_fields.update(base_fields) # Customize fields with provided kwargs for field_name, field_kwargs in klass.opts.model_fields_kwargs.items(): field = declared_fields.get(field_name, None) if field: # Copy to prevent alteration of a possible parent class's field field = copy.copy(field) for key, value in field_kwargs.items(): setattr(field, key, value) declared_fields[field_name] = field if opts.model_dump_only_pk and opts.model: # If primary key is automatically generated (nominal case), we # must make sure this field is read-only if opts.model._auto_id_field is True: field_name = opts.model._meta['id_field'] id_field = declared_fields.get(field_name) if id_field: # Copy to prevent alteration of a possible parent class's field id_field = copy.copy(id_field) id_field.dump_only = True declared_fields[field_name] = id_field return declared_fields
<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: return self.handle_puback() elif cmd == NC.CMD_PUBREC: return self.handle_pubrec() elif cmd == NC.CMD_PUBREL: return self.handle_pubrel() elif cmd == NC.CMD_PUBCOMP: return self.handle_pubcomp() elif cmd == NC.CMD_SUBSCRIBE: sys.exit(-1) elif cmd == NC.CMD_SUBACK: return self.handle_suback() elif cmd == NC.CMD_UNSUBSCRIBE: print "Received UNSUBSCRIBE" sys.exit(-1) elif cmd == NC.CMD_UNSUBACK: return self.handle_unsuback() else: self.logger.warning("Unknown protocol. Cmd = %d", cmd) return NC.ERR_PROTOCOL
<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 #variable header mid = self.mid_generate() pkt.write_uint16(mid) #payload for (topic, qos) in topics: pkt.write_string(topic) pkt.write_byte(qos) return self.packet_queue(pkt)
<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 header mid = self.mid_generate() pkt.write_uint16(mid) #payload for topic in topics: pkt.write_string(topic) return self.packet_queue(pkt)
<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("PUBLISH:err payload len:%d", payloadlen) return NC.ERR_PAYLOAD_SIZE #wildcard check : TODO mid = self.mid_generate() if qos in (0,1,2): return self.send_publish(mid, topic, payload, qos, retain, False) else: self.logger.error("Unsupport QoS= %d", qos) return NC.ERR_NOT_SUPPORTED
<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.read_byte() if ret != NC.ERR_SUCCESS: return ret evt = event.EventConnack(retcode, session_present) self.push_event(evt) if retcode == NC.CONNECT_ACCEPTED: self.state = NC.CS_CONNECTED return NC.ERR_SUCCESS elif retcode >= 1 and retcode <= 5: return NC.ERR_CONN_REFUSED else: return NC.ERR_PROTOCOL
<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_qos is None: return NC.ERR_NO_MEM i = 0 while self.in_packet.pos < self.in_packet.remaining_length: ret, byte = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: granted_qos = None return ret granted_qos[i] = byte i += 1 evt = event.EventSuback(mid, list(granted_qos)) self.push_event(evt) granted_qos = None 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_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) ret, ba_data = self.in_packet.read_string() message.msg.topic = ba_data.decode('utf8') if ret != NC.ERR_SUCCESS: return ret #fix_sub_topic TODO if message.msg.qos > 0: ret, word = self.in_packet.read_uint16() message.msg.mid = word if ret != NC.ERR_SUCCESS: return ret message.msg.payloadlen = self.in_packet.remaining_length - self.in_packet.pos if message.msg.payloadlen > 0: ret, message.msg.payload = self.in_packet.read_bytes(message.msg.payloadlen) if ret != NC.ERR_SUCCESS: return ret self.logger.debug("Received PUBLISH(dup = %d,qos=%d,retain=%s", message.dup, message.msg.qos, message.msg.retain) self.logger.debug("\tmid=%d, topic=%s, payloadlen=%d", message.msg.mid, message.msg.topic, message.msg.payloadlen) message.timestamp = time.time() qos = message.msg.qos if qos in (0,1,2): evt = event.EventPublish(message.msg) self.push_event(evt) return NC.ERR_SUCCESS else: return NC.ERR_PROTOCOL 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 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(payload), qos, retain, dup)
<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 #variable header: acknowledged message id pkt.write_uint16(mid) return self.packet_queue(pkt)
<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: return (socket.timeout, "timeout") except socket.error as e: return (socket.error, e.strerror if e.strerror else e.message) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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, errmsg except socket.timeout: return data, errno.ETIMEDOUT, "Connection timed out" except socket.error as (errnum, errmsg): return data, errnum, errmsg ba_data = bytearray(data) if len(ba_data) == 0: return ba_data, errno.ECONNRESET, "Connection closed" return ba_data, 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 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 socket.timeout: return -1, (socket.timeout, "timeout") except socket.error as (_, msg): return -1, (socket.error, msg) return length, None