text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Generate a list of the requests peaks on the queue.
<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:>
Generates statistics on how many requests are made via HTTP and how
<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:>
Generates statistics on how many requests were made per minute.
<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:>
Returns the raw lines to be printed.
<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:>
Haproxy writes its logs after having gathered all information
<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:>
Sorts a dictionary with at least two fields on each of them sorting
<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:>
Wraps a function that actually accesses the database.
<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:>
Gets the python type for the attribute on the model
<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:>
Takes a field name and gets an appropriate BaseField instance
<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:>
Creates a new instance of the self.model
<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:>
Retrieves a model using the lookup keys provided.
<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:>
Retrieves a list of the model for this manager.
<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:>
Updates the model with the specified lookup_keys and returns
<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:>
Deletes the model found using the lookup_keys
<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:>
Takes a model and serializes the fields provided into
<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:>
A recursive function for serializing a model
<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:>
Gets the sqlalchemy Model instance associated with
<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:>
Updates the values with the specified values.
<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:>
Prints all commands available from Log with their
<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:>
Prints all filters available with their description.
<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:>
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.
<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:>
Removes an observer.
<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:>
In Mac OS X 10.7+
<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:>
Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop
<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:>
Stops thread and invalidates source.
<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:>
Looks through all power supplies in POWER_SUPPLY_PATH.
<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:>
Converts a string from Scratch to its proper type in Python. Expects a
<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:>
Escapes double quotes by adding another double quote as per the Scratch
<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:>
Removes double quotes that were used to escape double quotes. Expects
<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:>
Returns True if message is a proper Scratch message, else return False.
<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:>
Given a broacast message, returns the message that was broadcast.
<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:>
Parses a Scratch message and returns a tuple with the first element
<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:>
Writes string data out to Scratch
<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:>
Reads size number of bytes from Scratch and returns data as a string
<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:>
Receives and returns a message from Scratch
<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:>
Connects to Scratch.
<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:>
Closes connection to Scratch
<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:>
Given a dict of sensors and values, updates those sensors with the
<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:>
Tests a simple topology. "Simple" means there it has no branches
<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:>
Writes the topology to a stream or file.
<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:>
Reads the topology from a stream or file.
<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:>
A more efficient way to emit a number of tuples at once.
<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:>
Handler to allow process to be remotely debugged.
<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:>
Interrupt a running process and debug it.
<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:>
Checks kwargs for the values specified in 'requires', which is a tuple
<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:>
Returns the prepared call parameters. Mind, these will be keyword
<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:>
Shortcut for the AddressVerify method.
<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:>
Shortcut for the DoAuthorization method.
<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:>
Shortcut for the DoCapture method.
<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:>
Shortcut for the DoDirectPayment method.
<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:>
Shortcut for the TransactionSearch method.
<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:>
Returns the URL to redirect the user to for the Express checkout.
<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:>
Shortcut for the GetRecurringPaymentsProfile method.
<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:>
Shortcut to the ManageRecurringPaymentsProfileStatus method.
<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:>
Shortcut to the UpdateRecurringPaymentsProfile method.
<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:>
Shortcut to the BMCreateButton method.
<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:>
Checks for the presence of errors in the response. Returns ``True`` if
<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:>
Given a country code abbreviation, check to see if it matches the
<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:>
Given a country code abbreviation, get the full name from the table.
<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:>
Updates declared fields with fields converted from the
<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:>
Subscribe to some topic.
<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:>
Unsubscribe to some topic.
<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:>
Unsubscribe to some topics.
<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:>
Publish some payload to server.
<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:>
Connect to some addr.
<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:>
Read from socket and return it's byte array representation.
<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:>
Write payload to socket.
<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 |
<SYSTEM_TASK:>
Write a string to this packet.
<END_TASK>
<USER_TASK:>
Description:
def write_string(self, string):
"""Write a string to this packet.""" |
self.write_uint16(len(string))
self.write_bytes(string, len(string)) |
<SYSTEM_TASK:>
Write n number of bytes to this packet.
<END_TASK>
<USER_TASK:>
Description:
def write_bytes(self, data, n):
"""Write n number of bytes to this packet.""" |
for pos in xrange(0, n):
self.payload[self.pos + pos] = data[pos]
self.pos += n |
<SYSTEM_TASK:>
Read count number of bytes.
<END_TASK>
<USER_TASK:>
Description:
def read_bytes(self, count):
"""Read count number of bytes.""" |
if self.pos + count > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(count)
for x in xrange(0, count):
ba[x] = self.payload[self.pos]
self.pos += 1
return NC.ERR_SUCCESS, ba |
<SYSTEM_TASK:>
Pop an event from event_list.
<END_TASK>
<USER_TASK:>
Description:
def pop_event(self):
"""Pop an event from event_list.""" |
if len(self.event_list) > 0:
evt = self.event_list.pop(0)
return evt
return None |
<SYSTEM_TASK:>
Write packet to network.
<END_TASK>
<USER_TASK:>
Description:
def packet_write(self):
"""Write packet to network.""" |
bytes_written = 0
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN, bytes_written
while len(self.out_packet) > 0:
pkt = self.out_packet[0]
write_length, status = nyamuk_net.write(self.sock, pkt.payload)
if write_length > 0:
pkt.to_process -= write_length
pkt.pos += write_length
bytes_written += write_length
if pkt.to_process > 0:
return NC.ERR_SUCCESS, bytes_written
else:
if status == errno.EAGAIN or status == errno.EWOULDBLOCK:
return NC.ERR_SUCCESS, bytes_written
elif status == errno.ECONNRESET:
return NC.ERR_CONN_LOST, bytes_written
else:
return NC.ERR_UNKNOWN, bytes_written
"""
if pkt.command & 0xF6 == NC.CMD_PUBLISH and self.on_publish is not None:
self.in_callback = True
self.on_publish(pkt.mid)
self.in_callback = False
"""
#next
del self.out_packet[0]
#free data (unnecessary)
self.last_msg_out = time.time()
return NC.ERR_SUCCESS, bytes_written |
<SYSTEM_TASK:>
Close our socket.
<END_TASK>
<USER_TASK:>
Description:
def socket_close(self):
"""Close our socket.""" |
if self.sock != NC.INVALID_SOCKET:
self.sock.close()
self.sock = NC.INVALID_SOCKET |
<SYSTEM_TASK:>
The actual public IP of this host.
<END_TASK>
<USER_TASK:>
Description:
def real_ip(self):
"""
The actual public IP of this host.
""" |
if self._real_ip is None:
response = get(ICANHAZIP)
self._real_ip = self._get_response_text(response)
return self._real_ip |
<SYSTEM_TASK:>
Get the current IP Tor is using.
<END_TASK>
<USER_TASK:>
Description:
def get_current_ip(self):
"""
Get the current IP Tor is using.
:returns str
:raises TorIpError
""" |
response = get(ICANHAZIP, proxies={"http": self.local_http_proxy})
if response.ok:
return self._get_response_text(response)
raise TorIpError("Failed to get the current Tor IP") |
<SYSTEM_TASK:>
Check if the current Tor's IP is usable.
<END_TASK>
<USER_TASK:>
Description:
def _ip_is_usable(self, current_ip):
"""
Check if the current Tor's IP is usable.
:argument current_ip: current Tor IP
:type current_ip: str
:returns bool
""" |
# Consider IP addresses only.
try:
ipaddress.ip_address(current_ip)
except ValueError:
return False
# Never use real IP.
if current_ip == self.real_ip:
return False
# Do dot allow IP reuse.
if not self._ip_is_safe(current_ip):
return False
return True |
<SYSTEM_TASK:>
Handle registering and releasing used Tor IPs.
<END_TASK>
<USER_TASK:>
Description:
def _manage_used_ips(self, current_ip):
"""
Handle registering and releasing used Tor IPs.
:argument current_ip: current Tor IP
:type current_ip: str
""" |
# Register current IP.
self.used_ips.append(current_ip)
# Release the oldest registred IP.
if self.reuse_threshold:
if len(self.used_ips) > self.reuse_threshold:
del self.used_ips[0] |
<SYSTEM_TASK:>
Returns True if command dict is "local subsection", meaning
<END_TASK>
<USER_TASK:>
Description:
def is_local_subsection(command_dict):
"""Returns True if command dict is "local subsection", meaning
that it is "if", "else" or "for" (not a real call, but calls
run_section recursively.""" |
for local_com in ['if ', 'for ', 'else ']:
if list(command_dict.keys())[0].startswith(local_com):
return True
return False |
<SYSTEM_TASK:>
This function creates a frame
<END_TASK>
<USER_TASK:>
Description:
def create_frame(self):
"""
This function creates a frame
""" |
frame = Gtk.Frame()
frame.set_shadow_type(Gtk.ShadowType.IN)
return frame |
<SYSTEM_TASK:>
Function creates box. Based on orientation
<END_TASK>
<USER_TASK:>
Description:
def create_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0):
"""
Function creates box. Based on orientation
it can be either HORIZONTAL or VERTICAL
""" |
h_box = Gtk.Box(orientation=orientation, spacing=spacing)
h_box.set_homogeneous(False)
return h_box |
<SYSTEM_TASK:>
Function creates a button with lave.
<END_TASK>
<USER_TASK:>
Description:
def button_with_label(self, description, assistants=None):
"""
Function creates a button with lave.
If assistant is specified then text is aligned
""" |
btn = self.create_button()
label = self.create_label(description)
if assistants is not None:
h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL)
h_box.pack_start(label, False, False, 0)
label_ass = self.create_label(
assistants, justify=Gtk.Justification.LEFT
)
label_ass.set_alignment(0, 0)
h_box.pack_start(label_ass, False, False, 12)
btn.add(h_box)
else:
btn.add(label)
return btn |
<SYSTEM_TASK:>
The function creates a image from name defined in image_name
<END_TASK>
<USER_TASK:>
Description:
def create_image(self, image_name=None, scale_ratio=1, window=None):
"""
The function creates a image from name defined in image_name
""" |
size = 48 * scale_ratio
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True)
image = Gtk.Image()
# Creating the cairo surface is necessary for proper scaling on HiDPI
try:
surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, window)
image.set_from_surface(surface)
# Fallback for GTK+ older than 3.10
except AttributeError:
image.set_from_pixbuf(pixbuf)
return image |
<SYSTEM_TASK:>
The function creates a button with image
<END_TASK>
<USER_TASK:>
Description:
def button_with_image(self, description, image=None, sensitive=True):
"""
The function creates a button with image
""" |
btn = self.create_button()
btn.set_sensitive(sensitive)
h_box = self.create_box()
try:
img = self.create_image(image_name=image,
scale_ratio=btn.get_scale_factor(),
window=btn.get_window())
except: # Older GTK+ than 3.10
img = self.create_image(image_name=image)
h_box.pack_start(img, False, False, 12)
label = self.create_label(description)
h_box.pack_start(label, False, False, 0)
btn.add(h_box)
return btn |
<SYSTEM_TASK:>
The function creates a checkbutton with label
<END_TASK>
<USER_TASK:>
Description:
def checkbutton_with_label(self, description):
"""
The function creates a checkbutton with label
""" |
act_btn = Gtk.CheckButton(description)
align = self.create_alignment()
act_btn.add(align)
return align |
<SYSTEM_TASK:>
Function creates a checkbox with his name
<END_TASK>
<USER_TASK:>
Description:
def create_checkbox(self, name, margin=10):
"""
Function creates a checkbox with his name
""" |
chk_btn = Gtk.CheckButton(name)
chk_btn.set_margin_right(margin)
return chk_btn |
<SYSTEM_TASK:>
Function creates an Entry with corresponding text
<END_TASK>
<USER_TASK:>
Description:
def create_entry(self, text="", sensitive="False"):
"""
Function creates an Entry with corresponding text
""" |
text_entry = Gtk.Entry()
text_entry.set_sensitive(sensitive)
text_entry.set_text(text)
return text_entry |
<SYSTEM_TASK:>
Function creates a link button with corresponding text and
<END_TASK>
<USER_TASK:>
Description:
def create_link_button(self, text="None", uri="None"):
"""
Function creates a link button with corresponding text and
URI reference
""" |
link_btn = Gtk.LinkButton(uri, text)
return link_btn |
<SYSTEM_TASK:>
This is generalized method for creating Gtk.Button
<END_TASK>
<USER_TASK:>
Description:
def create_button(self, style=Gtk.ReliefStyle.NORMAL):
"""
This is generalized method for creating Gtk.Button
""" |
btn = Gtk.Button()
btn.set_relief(style)
return btn |
<SYSTEM_TASK:>
Function creates a menu item with an image
<END_TASK>
<USER_TASK:>
Description:
def create_image_menu_item(self, text, image_name):
"""
Function creates a menu item with an image
""" |
menu_item = Gtk.ImageMenuItem(text)
img = self.create_image(image_name)
menu_item.set_image(img)
return menu_item |
<SYSTEM_TASK:>
The function is used for creating lable with HTML text
<END_TASK>
<USER_TASK:>
Description:
def create_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None):
"""
The function is used for creating lable with HTML text
""" |
label = Gtk.Label()
name = name.replace('|', '\n')
label.set_markup(name)
label.set_justify(justify)
label.set_line_wrap(wrap_mode)
if tooltip is not None:
label.set_has_tooltip(True)
label.connect("query-tooltip", self.parent.tooltip_queries, tooltip)
return label |
<SYSTEM_TASK:>
The function is used for creating button with all features
<END_TASK>
<USER_TASK:>
Description:
def add_button(self, grid_lang, ass, row, column):
"""
The function is used for creating button with all features
like signal on tooltip and signal on clicked
The function does not have any menu.
Button is add to the Gtk.Grid on specific row and column
""" |
#print "gui_helper add_button"
image_name = ass[0].icon_path
label = "<b>" + ass[0].fullname + "</b>"
if not image_name:
btn = self.button_with_label(label)
else:
btn = self.button_with_image(label, image=ass[0].icon_path)
#print "Dependencies button",ass[0]._dependencies
if ass[0].description:
btn.set_has_tooltip(True)
btn.connect("query-tooltip",
self.parent.tooltip_queries,
self.get_formatted_description(ass[0].description)
)
btn.connect("clicked", self.parent.btn_clicked, ass[0].name)
if row == 0 and column == 0:
grid_lang.add(btn)
else:
grid_lang.attach(btn, column, row, 1, 1)
return btn |
<SYSTEM_TASK:>
Add button that opens the window for installing more assistants
<END_TASK>
<USER_TASK:>
Description:
def add_install_button(self, grid_lang, row, column):
"""
Add button that opens the window for installing more assistants
""" |
btn = self.button_with_label('<b>Install more...</b>')
if row == 0 and column == 0:
grid_lang.add(btn)
else:
grid_lang.attach(btn, column, row, 1, 1)
btn.connect("clicked", self.parent.install_btn_clicked)
return btn |
<SYSTEM_TASK:>
The function creates a menu item
<END_TASK>
<USER_TASK:>
Description:
def menu_item(self, sub_assistant, path):
"""
The function creates a menu item
and assigns signal like select and button-press-event for
manipulation with menu_item. sub_assistant and path
""" |
if not sub_assistant[0].icon_path:
menu_item = self.create_menu_item(sub_assistant[0].fullname)
else:
menu_item = self.create_image_menu_item(
sub_assistant[0].fullname, sub_assistant[0].icon_path
)
if sub_assistant[0].description:
menu_item.set_has_tooltip(True)
menu_item.connect("query-tooltip",
self.parent.tooltip_queries,
self.get_formatted_description(sub_assistant[0].description),
)
menu_item.connect("select", self.parent.sub_menu_select, path)
menu_item.connect("button-press-event", self.parent.sub_menu_pressed)
menu_item.show()
return menu_item |
<SYSTEM_TASK:>
Function generates menu from based on ass parameter
<END_TASK>
<USER_TASK:>
Description:
def generate_menu(self, ass, text, path=None, level=0):
"""
Function generates menu from based on ass parameter
""" |
menu = self.create_menu()
for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())):
if index != 0:
text += "|"
text += "- " + sub[0].fullname
new_path = list(path)
if level == 0:
new_path.append(ass[0].name)
new_path.append(sub[0].name)
menu_item = self.menu_item(sub, new_path)
if sub[1]:
# If assistant has subassistants
(sub_menu, txt) = self.generate_menu(sub, text, new_path, level=level + 1)
menu_item.set_submenu(sub_menu)
menu.append(menu_item)
return menu, text |
<SYSTEM_TASK:>
The function is used for creating button with menu and submenu.
<END_TASK>
<USER_TASK:>
Description:
def add_submenu(self, grid_lang, ass, row, column):
"""
The function is used for creating button with menu and submenu.
Also signal on tooltip and signal on clicked are specified
Button is add to the Gtk.Grid
""" |
text = "Available subassistants:\n"
# Generate menus
path = []
(menu, text) = self.generate_menu(ass, text, path=path)
menu.show_all()
if ass[0].description:
description = self.get_formatted_description(ass[0].description) + "\n\n"
else:
description = ""
description += text.replace('|', '\n')
image_name = ass[0].icon_path
lbl_text = "<b>" + ass[0].fullname + "</b>"
if not image_name:
btn = self.button_with_label(lbl_text)
else:
btn = self.button_with_image(lbl_text, image=image_name)
btn.set_has_tooltip(True)
btn.connect("query-tooltip",
self.parent.tooltip_queries,
description
)
btn.connect_object("event", self.parent.btn_press_event, menu)
if row == 0 and column == 0:
grid_lang.add(btn)
else:
grid_lang.attach(btn, column, row, 1, 1) |
<SYSTEM_TASK:>
Function creates a scrolled window with layout manager
<END_TASK>
<USER_TASK:>
Description:
def create_scrolled_window(self, layout_manager, horizontal=Gtk.PolicyType.NEVER, vertical=Gtk.PolicyType.ALWAYS):
"""
Function creates a scrolled window with layout manager
""" |
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(layout_manager)
scrolled_window.set_policy(horizontal, vertical)
return scrolled_window |
<SYSTEM_TASK:>
Function creates a Gtk Grid with spacing
<END_TASK>
<USER_TASK:>
Description:
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True):
"""
Function creates a Gtk Grid with spacing
and homogeous tags
""" |
grid_lang = Gtk.Grid()
grid_lang.set_column_spacing(row_spacing)
grid_lang.set_row_spacing(col_spacing)
grid_lang.set_border_width(12)
grid_lang.set_row_homogeneous(row_homogenous)
grid_lang.set_column_homogeneous(col_homogenous)
return grid_lang |
<SYSTEM_TASK:>
Function creates a question dialog with title text
<END_TASK>
<USER_TASK:>
Description:
def create_question_dialog(self, text, second_text):
"""
Function creates a question dialog with title text
and second_text
""" |
dialog = self.create_message_dialog(
text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION
)
dialog.format_secondary_text(second_text)
response = dialog.run()
dialog.destroy()
return response |
<SYSTEM_TASK:>
Function creates a file chooser dialog with title text
<END_TASK>
<USER_TASK:>
Description:
def create_file_chooser_dialog(self, text, parent, name=Gtk.STOCK_OPEN):
"""
Function creates a file chooser dialog with title text
""" |
text = None
dialog = Gtk.FileChooserDialog(
text, parent,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, name, Gtk.ResponseType.OK)
)
response = dialog.run()
if response == Gtk.ResponseType.OK:
text = dialog.get_filename()
dialog.destroy()
return text |
<SYSTEM_TASK:>
Function creates a text view with wrap_mode
<END_TASK>
<USER_TASK:>
Description:
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):
"""
Function creates a text view with wrap_mode
and justification
""" |
text_view = Gtk.TextView()
text_view.set_wrap_mode(wrap_mode)
text_view.set_editable(editable)
if not editable:
text_view.set_cursor_visible(False)
else:
text_view.set_cursor_visible(visible)
text_view.set_justification(justify)
return text_view |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.