code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
link = FILTER_MAPS['link'][source] html = soup.find_all('link', {link['key']: link['pattern']}) if link['type'] == 'url': for line in html: data['url'] = line.get('href') else: for line in html: data['images'].append({ ...
def _filter_link_tag_data(self, source, soup, data, url)
This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS`` :param source: The key of the meta dictionary in ``FILTER_MAPS['link']`` :type source: string :param soup: BeautifulSoup instance to find meta tags :type soup: instance :param...
3.934626
3.084819
1.275481
all_images = soup.find_all('img') for image in all_images: item = normalize_image_data(image, url) data['images'].append(item)
def _find_all_images(self, soup, data, url)
This method finds all images in the web page content :param soup: BeautifulSoup instance to find meta tags :type soup: instance :param data: The response dictionary to manipulate :type data: (dict)
4.137154
4.599367
0.899505
try: headers = decode_header(value) except email.errors.HeaderParseError: return str_decode(str_encode(value, default_charset, 'replace'), default_charset) else: for index, (text, charset) in enumerate(headers): logger.debug("Mail header no. {index}: {data} encoding ...
def decode_mail_header(value, default_charset='us-ascii')
Decode a header value into a unicode string.
3.030164
3.067595
0.987798
headers = [h for h in message.get_all(header_name, [])] addresses = email.utils.getaddresses(headers) for index, (address_name, address_email) in enumerate(addresses): addresses[index] = {'name': decode_mail_header(address_name), 'email': address_email} logg...
def get_mail_addresses(message, header_name)
Retrieve all email addresses from one message header.
3.341279
3.350729
0.99718
if len(headers) == 0: return [] if sys.version_info[0] == 3: headers = bytes(headers, "ascii") return list(imaplib.ParseFlags(headers))
def parse_flags(headers)
Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py
4.287761
3.245653
1.321078
if self.count >= random.randint(DharmaConst.VARIABLE_MIN, DharmaConst.VARIABLE_MAX): return "%s%d" % (self.var, random.randint(1, self.count)) var = random.choice(self) prefix = self.eval(var[0], state) suffix = self.eval(var[1], state) self.count += 1 ...
def generate(self, state)
Return a random variable if any, otherwise create a new default variable.
3.99482
3.727165
1.071812
logging.debug("Using configuration from: %s", settings.name) exec(compile(settings.read(), settings.name, 'exec'), globals(), locals())
def process_settings(self, settings)
A lazy way of feeding Dharma with configuration settings.
6.984201
6.048973
1.154609
out, end = [], 0 token = token.replace("\\n", "\n") for m in re.finditer(self.xref_registry, token, re.VERBOSE | re.DOTALL): if m.start(0) > end: out.append(String(token[end:m.start(0)], self.current_obj)) end = m.end(0) if m.group("ty...
def parse_xrefs(self, token)
Search token for +value+ and !variable! style references. Be careful to not xref a new variable.
2.438311
2.365331
1.030854
for i, token in enumerate(tokens): if isinstance(token, ElementXRef): variable = token.value break else: logging.error("%s: Variable assignment syntax error", self.id()) sys.exit(-1) if variable != self.current_obj.iden...
def parse_assign_variable(self, tokens)
Example: tokens dharma.String: 'let ', dharma.ElementXRef: 'GrammarNS:<VarName>', dharma.String: '= new ', dharma.ValueXRef: 'GrammarNS:<ValueName>'
3.845521
3.164486
1.215212
reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref: reverse_xref.setdefault(xref, []).append(v.ident) for leaf in leaves: self.calculate_leaf_path(le...
def calculate_leaf_paths(self)
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
4.058947
3.046192
1.332466
# Setup pre-conditions. if not self.variance: logging.error("%s: No variance information %s", self.id(), self.variance) sys.exit(-1) for var in self.variable.values(): var.clear() # Handle variances variances = [] for _ in ra...
def generate_content(self)
Generates a test case as a string.
4.272002
3.949264
1.081721
for path in self.default_grammars: grammars.insert(0, open(os.path.relpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.normcase(path))))) for fo in grammars: logging.debug("Processing g...
def process_grammars(self, grammars)
Process provided grammars by parsing them into Python objects.
4.020743
3.910742
1.028128
try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request...
def set_preferences(request, dashboard_id)
This view serves and validates a preferences form.
1.77044
1.791221
0.988399
if menu is None: menu = get_admin_menu(context) menu.init_with_context(context) has_bookmark_item = False bookmark = None if len([c for c in menu.children if isinstance(c, items.Bookmarks)]) > 0: has_bookmark_item = True url = context['request'].get_full_path() ...
def admin_tools_render_menu(context, menu=None)
Template tag that renders the menu, it takes an optional ``Menu`` instance as unique argument, if not given, the menu will be retrieved with the ``get_admin_menu`` function.
2.671599
2.693781
0.991765
item.init_with_context(context) context.update({ 'template': item.template, 'item': item, 'index': index, 'selected': item.is_selected(context['request']), 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_menu_item(context, item, index=None)
Template tag that renders a given menu item, it takes a ``MenuItem`` instance as unique parameter.
3.496988
3.762249
0.929494
if menu is None: menu = get_admin_menu(context) context.update({ 'template': 'admin_tools/menu/css.html', 'css_files': menu.Media.css, }) return context
def admin_tools_render_menu_css(context, menu=None)
Template tag that renders the menu css files,, it takes an optional ``Menu`` instance as unique argument, if not given, the menu will be retrieved with the ``get_admin_menu`` function.
3.732671
3.781599
0.987061
css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) if not css: css = '/'.join(['admin_tools', 'css', 'theming.css']) return mark_safe( '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % staticfiles_storage.url(css) )
def render_theming_css()
Template tag that renders the needed css files for the theming app.
3.016702
2.870799
1.050823
if request.method == "POST": form = BookmarkForm(user=request.user, data=request.POST) if form.is_valid(): bookmark = form.save() if not request.is_ajax(): messages.success(request, 'Bookmark added') if request.POST.get('next'): ...
def add_bookmark(request)
This view serves and validates a bookmark form. If requested via ajax it also returns the drop bookmark form to replace the add bookmark form.
2.068084
2.047889
1.009861
bookmark = get_object_or_404(Bookmark, id=id, user=request.user) if request.method == "POST": bookmark.delete() if not request.is_ajax(): messages.success(request, 'Bookmark removed') if request.POST.get('next'): return HttpResponseRedirect(request.PO...
def remove_bookmark(request, id)
This view deletes a bookmark. If requested via ajax it also returns the add bookmark form to replace the drop bookmark form.
2.830086
2.775184
1.019783
import imp from django.conf import settings try: from importlib import import_module except ImportError: # Django < 1.9 and Python < 2.7 from django.utils.importlib import import_module blacklist.append('admin_tools.dashboard') blacklist.append('admin_tools.menu') ...
def autodiscover(blacklist=[])
Automagically discover custom dashboards and menus for installed apps. Optionally you can pass a ``blacklist`` of apps that you don't want to provide their own app index dashboard.
2.57117
2.577404
0.997581
ret = ['dashboard-module'] if not self.enabled: ret.append('disabled') if self.draggable: ret.append('draggable') if self.collapsible: ret.append('collapsible') if self.deletable: ret.append('deletable') ret += self...
def render_css_classes(self)
Return a string containing the css classes for the module. >>> mod = DashboardModule(enabled=False, draggable=True, ... collapsible=True, deletable=True) >>> mod.render_css_classes() 'dashboard-module disabled draggable collapsible deletable' >>> mod.css_cl...
2.933823
1.917408
1.530099
if super(Group, self).is_empty(): return True for child in self.children: if not child.is_empty(): return False return True
def is_empty(self)
A group of modules is considered empty if it has no children or if all its children are empty. >>> from admin_tools.dashboard.modules import DashboardModule, LinkList >>> mod = Group() >>> mod.is_empty() True >>> mod.children.append(DashboardModule()) >>> mod.is_...
3.091484
2.960264
1.044327
if location == 'index': return get_index_dashboard(context) elif location == 'app_index': return get_app_index_dashboard(context) raise ValueError('Invalid dashboard location: "%s"' % location)
def get_dashboard(context, location)
Returns the dashboard that match the given ``location`` (index or app_index).
2.967438
2.224669
1.333879
# this is a mess, needs cleanup ! app = context['app_list'][0] model_list = [] app_label = None app_title = app['name'] admin_site = get_admin_site(context=context) for model, model_admin in admin_site._registry.items(): if app['app_label'] == model._meta.app_label: ...
def get_app_index_dashboard(context)
Returns the admin dashboard defined by the user or the default one.
3.708616
3.668882
1.01083
models = [] for m in self.models: mod, cls = m.rsplit('.', 1) mod = import_module(mod) models.append(getattr(mod, cls)) return models
def get_app_model_classes(self)
Helper method that returns a list of model classes for the current app.
2.621265
2.469184
1.061592
# Import this here to silence RemovedInDjango19Warning. See #15 from django.contrib.contenttypes.models import ContentType return [ContentType.objects.get_for_model(c) for c in self.get_app_model_classes()]
def get_app_content_types(self)
Return a list of all content_types for this app.
6.035448
5.181947
1.164707
if dashboard is None: dashboard = get_dashboard(context, location) dashboard.init_with_context(context) dashboard._prepare_children() try: preferences = DashboardPreferences.objects.get( user=context['request'].user, dashboard_id=dashboard.get_id() ...
def admin_tools_render_dashboard(context, location='index', dashboard=None)
Template tag that renders the dashboard, it takes two optional arguments: ``location`` The location of the dashboard, it can be 'index' (for the admin index dashboard) or 'app_index' (for the app index dashboard), the default value is 'index'. ``dashboard`` An instance of ``Das...
3.207256
3.399672
0.943401
module.init_with_context(context) context.update({ 'template': module.template, 'module': module, 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_dashboard_module(context, module)
Template tag that renders a given dashboard module, it takes a ``DashboardModule`` instance as first parameter.
3.732152
4.592712
0.812625
if dashboard is None: dashboard = get_dashboard(context, location) context.update({ 'template': 'admin_tools/dashboard/css.html', 'css_files': dashboard.Media.css, }) return context
def admin_tools_render_dashboard_css( context, location='index', dashboard=None)
Template tag that renders the dashboard css files, it takes two optional arguments: ``location`` The location of the dashboard, it can be 'index' (for the admin index dashboard) or 'app_index' (for the app index dashboard), the default value is 'index'. ``dashboard`` An ins...
3.532653
5.367438
0.658164
current_url = request.get_full_path() return self.url == current_url or \ len([c for c in self.children if c.is_selected(request)]) > 0
def is_selected(self, request)
Helper method that returns ``True`` if the menu item is active. A menu item is considered as active if it's URL or one of its descendants URL is equals to the current URL.
3.317135
2.93249
1.131167
items = self._visible_models(context['request']) apps = {} for model, perms in items: if not (perms['change'] or perms.get('view', False)): continue app_label = model._meta.app_label if app_label not in apps: apps[app_l...
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
2.381603
2.281452
1.043898
items = self._visible_models(context['request']) for model, perms in items: if not (perms['change'] or perms.get('view', False)): continue title = model._meta.verbose_name_plural url = self._get_admin_change_url(model, context) ite...
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
4.037042
3.855882
1.046983
from admin_tools.menu.models import Bookmark for b in Bookmark.objects.filter(user=context['request'].user): self.children.append(MenuItem(mark_safe(b.title), b.url)) if not len(self.children): self.enabled = False
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
4.761484
4.205109
1.132309
if app_name in _cache: return _cache[app_name] template_dir = None for app in apps.get_app_configs(): if app.label == app_name: template_dir = join(app.path, 'templates') break _cache[app_name] = template_dir return template_dir
def get_app_template_dir(app_name)
Get the template directory for an application Uses apps interface available in django 1.7+ Returns a full path, or None if the app was not found.
1.985201
2.183719
0.909092
if ':' not in template_name: return [] app_name, template_name = template_name.split(":", 1) template_dir = get_app_template_dir(app_name) if template_dir: try: from django.template import Origin origin = Origin( ...
def get_template_sources(self, template_name, template_dirs=None)
Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take care of the actual loading for us.
2.749252
2.511037
1.094867
id = 1 new_value = value while new_value in seen_values: new_value = "%s%s" % (value, id) id += 1 seen_values.add(new_value) return new_value
def uniquify(value, seen_values)
Adds value to seen_values set and ensures it is unique
1.995579
1.878969
1.06206
items = [] admin_site = get_admin_site(request=request) for model, model_admin in admin_site._registry.items(): perms = model_admin.get_model_perms(request) if True not in perms.values(): continue items.append((model, perms,)) return items
def get_avail_models(request)
Returns (model, perm,) for all models user can possibly see
2.870507
2.590896
1.107921
items = get_avail_models(request) included = [] def full_name(model): return '%s.%s' % (model.__module__, model.__name__) # I beleive that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorythm is fine for model lists because they are small and admin...
def filter_models(request, models, exclude)
Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user.
4.262907
4.191586
1.017015
app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,))
def _get_admin_app_list_url(self, model, context)
Returns the admin change url.
3.318582
2.993007
1.108779
app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower()))
def _get_admin_change_url(self, model, context)
Returns the admin change url.
2.90539
2.707503
1.073088
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) self.receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.receiver_socket.setsockopt(s...
def attempt_connection(self)
Establish a multicast connection - uses 2 sockets (one for sending, the other for receiving)
1.531999
1.444905
1.060277
frame_type = f.cmd.lower() if frame_type in ['disconnect']: return if frame_type == 'send': frame_type = 'message' f.cmd = 'MESSAGE' if frame_type in ['connected', 'message', 'receipt', 'error', 'heartbeat']: if frame_type == 'm...
def process_frame(self, f, frame_str)
:param Frame f: Frame object :param bytes frame_str: Raw frame content
4.089363
4.071439
1.004402
self.transport.start()
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers)
:param str username: :param str passcode: :param bool wait: :param dict headers: :param keyword_headers:
66.003433
74.241013
0.889043
self.transport.subscriptions[id] = destination
def subscribe(self, destination, id, ack='auto', headers=None, **keyword_headers)
:param str destination: :param str id: :param str ack: :param dict headers: :param keyword_headers:
13.034926
22.12302
0.589202
Protocol12.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
:param str receipt: :param dict headers: :param keyword_headers:
7.221163
9.141191
0.789959
if headers is None: headers = {} frame = utils.Frame(cmd, headers, body) if cmd == CMD_BEGIN: trans = headers[HDR_TRANSACTION] if trans in self.transactions: self.notify('error', {}, 'Transaction %s already started' % trans) ...
def send_frame(self, cmd, headers=None, body='')
:param str cmd: :param dict headers: :param body:
2.126364
2.176088
0.97715
thread = threading.Thread(None, callback) thread.daemon = True # Don't let thread prevent termination thread.start() return thread
def default_create_thread(callback)
Default thread creation - used to create threads when the client doesn't want to provide their own thread creation. :param function callback: the callback function provided to threading.Thread
4.131225
6.289228
0.656873
headers = {} for header_line in lines[offset:]: header_match = HEADER_LINE_RE.match(header_line) if header_match: key = header_match.group('key') key = re.sub(r'\\.', _unescape_header, key) if key not in headers: value = header_match.group...
def parse_headers(lines, offset=0)
Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str)
2.235553
2.365923
0.944897
f = Frame() if frame == b'\x0a': f.cmd = 'heartbeat' return f mat = PREAMBLE_END_RE.search(frame) if mat: preamble_end = mat.start() body_start = mat.end() else: preamble_end = len(frame) body_start = preamble_end preamble = decode(frame[0:pr...
def parse_frame(frame)
Parse a STOMP frame into a Frame object. :param bytes frame: the frame received from the server (as a byte string) :rtype: Frame
3.031318
3.077531
0.984984
headers = {} for header_map in header_map_list: if header_map: headers.update(header_map) return headers
def merge_headers(header_map_list)
Helper function for combining multiple header maps into one. :param list(dict) header_map_list: list of maps :rtype: dict
2.346391
2.840128
0.826157
(sx, sy) = shb (cx, cy) = chb x = 0 y = 0 if cx != 0 and sy != '0': x = max(cx, int(sy)) if cy != 0 and sx != '0': y = max(cy, int(sx)) return x, y
def calculate_heartbeats(shb, chb)
Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :rtype: (int,int)
3.179691
3.156417
1.007374
lines = [] body = None if frame.body: if body_encoding: body = encode(frame.body, body_encoding) else: body = encode(frame.body) if HDR_CONTENT_LENGTH in frame.headers: frame.headers[HDR_CONTENT_LENGTH] = len(body) if frame.cmd: ...
def convert_frame(frame, body_encoding=None)
Convert a frame to a list of lines separated by newlines. :param Frame frame: the Frame object to convert :rtype: list(str)
2.594622
2.661939
0.974711
Protocol10.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Call the protocol disconnection, and then stop the transport itself. :param str receipt: the receipt to use with the disconnect :param dict headers: a map of any additional headers to send with the disconnection :param keyword_headers: any additional headers to send with the disconnection
6.496724
8.828448
0.735885
Protocol11.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Call the protocol disconnection, and then stop the transport itself. :param str receipt: the receipt to use with the disconnect :param dict headers: a map of any additional headers to send with the disconnection :param keyword_headers: any additional headers to send with the disconnection
6.590714
8.999455
0.732346
if type(char_data) is str: return char_data.encode(encoding, errors='replace') elif type(char_data) is bytes: return char_data else: raise TypeError('message should be a string or bytes, found %s' % type(char_data))
def encode(char_data, encoding='utf-8')
Encode the parameter as a byte string. :param char_data: the data to encode :rtype: bytes
2.426794
2.687092
0.90313
if type(char_data) is unicode: return char_data.encode(encoding, 'replace') else: return char_data
def encode(char_data, encoding='utf-8')
Encode the parameter as a byte string. :param char_data: :rtype: bytes
2.563989
3.062938
0.837101
if 'heart-beat' in headers: self.heartbeats = utils.calculate_heartbeats( headers['heart-beat'].replace(' ', '').split(','), self.heartbeats) if self.heartbeats != (0, 0): self.send_sleep = self.heartbeats[0] / 1000 # by default, ...
def on_connected(self, headers, body)
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats are not 0, we start up the heartbeat loop accordingly. :param dict headers: headers in t...
5.30266
4.934635
1.07458
if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP: if self.heartbeats != (0, 0): frame.headers[HDR_HEARTBEAT] = '%s,%s' % self.heartbeats if self.next_outbound_heartbeat is not None: self.next_outbound_heartbeat = monotonic() + self.send_sleep
def on_send(self, frame)
Add the heartbeat header to the frame when connecting, and bump next outbound heartbeat timestamp. :param Frame frame: the Frame object
4.985047
4.206603
1.185053
log.info('Starting heartbeat loop') now = monotonic() # Setup the initial due time for the outbound heartbeat if self.send_sleep != 0: self.next_outbound_heartbeat = now + self.send_sleep while self.running: now = monotonic() next_e...
def __heartbeat_loop(self)
Main loop for sending (and monitoring received) heartbeats.
3.160058
3.118487
1.013331
if 'receipt-id' in headers and headers['receipt-id'] == self.receipt: with self.receipt_condition: self.received = True self.receipt_condition.notify()
def on_receipt(self, headers, body)
If the receipt id can be found in the headers, then notify the waiting thread. :param dict headers: headers in the message :param body: the message content
3.803776
3.703018
1.02721
with self.receipt_condition: while not self.received: self.receipt_condition.wait() self.received = False
def wait_on_receipt(self)
Wait until we receive a message receipt.
4.283626
3.345509
1.280411
if log.isEnabledFor(logging.DEBUG): log.debug("received an error %s [%s]", body, headers) else: log.info("received an error %s", body) self.errors += 1
def on_error(self, headers, body)
Increment the error count. See :py:meth:`ConnectionListener.on_error` :param dict headers: headers in the message :param body: the message content
3.385314
3.743304
0.904365
log.info("connecting %s %s (x %s)", host_and_port[0], host_and_port[1], self.connections) self.connections += 1
def on_connecting(self, host_and_port)
Increment the connection count. See :py:meth:`ConnectionListener.on_connecting` :param (str,int) host_and_port: the host and port as a tuple
3.994561
4.418553
0.904043
print('on_send %s %s %s' % (frame.cmd, frame.headers, frame.body))
def on_send(self, frame)
:param Frame frame:
5.07326
4.505223
1.126084
frame = utils.Frame(cmd, headers, body) self.transport.transmit(frame)
def send_frame(self, cmd, headers=None, body='')
Encode and send a stomp frame through the underlying transport. :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message
7.510192
9.045649
0.830255
assert transaction is not None, "'transaction' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_ABORT, headers)
def abort(self, transaction, headers=None, **keyword_headers)
Abort a transaction. :param str transaction: the identifier of the transaction :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
4.969215
5.442982
0.912958
assert id is not None, "'id' is required" headers = {HDR_MESSAGE_ID: id} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_RECEIPT] = receipt self.send_frame(CMD_ACK, headers)
def ack(self, id, transaction=None, receipt=None)
Acknowledge 'consumption' of a message by id. :param str id: identifier of the message :param str transaction: include the acknowledgement in the specified transaction
3.061419
3.725553
0.821736
headers = utils.merge_headers([headers, keyword_headers]) if not transaction: transaction = utils.get_uuid() headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_BEGIN, headers) return transaction
def begin(self, transaction=None, headers=None, **keyword_headers)
Begin a transaction. :param str transaction: the identifier for the transaction (optional - if not specified a unique transaction id will be generated) :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker ...
4.762887
4.887878
0.974428
assert transaction is not None, "'transaction' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_COMMIT, headers)
def commit(self, transaction=None, headers=None, **keyword_headers)
Commit a transaction. :param str transaction: the identifier for the transaction :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
5.102454
5.402798
0.94441
if not self.transport.is_connected(): log.debug('Not sending disconnect, already disconnected') return headers = utils.merge_headers([headers, keyword_headers]) rec = receipt or utils.get_uuid() headers[HDR_RECEIPT] = rec self.set_receipt(rec, CMD...
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Disconnect from the server. :param str receipt: the receipt to use (once the server acknowledges that receipt, we're officially disconnected; optional - if not specified a unique receipt id will be generated) :param dict headers: a map of any additional headers the broker requir...
5.174473
5.479046
0.944411
assert destination is not None, "'destination' is required" assert body is not None, "'body' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_DESTINATION] = destination if content_type: headers[HDR_CONTENT_TYPE] = content_typ...
def send(self, destination, body, content_type=None, headers=None, **keyword_headers)
Send a message to a destination. :param str destination: the destination of the message (e.g. queue or topic name) :param body: the content of the message :param str content_type: the content type of the message :param dict headers: a map of any additional headers the broker requires ...
2.534903
2.699469
0.939038
assert destination is not None, "'destination' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_DESTINATION] = destination if id: headers[HDR_ID] = id headers[HDR_ACK] = ack self.send_frame(CMD_SUBSCRIBE, headers)
def subscribe(self, destination, id=None, ack='auto', headers=None, **keyword_headers)
Subscribe to a destination. :param str destination: the topic or queue to subscribe to :param str id: a unique id to represent the subscription :param str ack: acknowledgement mode, either auto, client, or client-individual (see http://stomp.github.io/stomp-specification-1.2.html#SU...
3.023811
3.427271
0.882279
assert id is not None or destination is not None, "'id' or 'destination' is required" headers = utils.merge_headers([headers, keyword_headers]) if id: headers[HDR_ID] = id if destination: headers[HDR_DESTINATION] = destination self.send_frame(CMD_...
def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers)
Unsubscribe from a destination by either id or the destination name. :param str destination: the name of the topic or queue to unsubscribe from :param str id: the unique identifier of the topic or queue to unsubscribe from :param dict headers: a map of any additional headers the broker requires...
3.302716
3.330226
0.991739
if cmd != CMD_CONNECT: if headers is None: headers = {} self._escape_headers(headers) frame = utils.Frame(cmd, headers, body) self.transport.transmit(frame)
def send_frame(self, cmd, headers=None, body='')
Encode and send a stomp frame through the underlying transport: :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message
5.636301
6.066148
0.92914
cmd = CMD_STOMP headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_ACCEPT_VERSION] = self.version if self.transport.vhost: headers[HDR_HOST] = self.transport.vhost if username is not None: headers[HDR_LOGIN] = username ...
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers)
Start a connection. :param str username: the username to connect with :param str passcode: the password used to authenticate with :param bool wait: if True, wait for the connection to be established/acknowledged :param dict headers: a map of any additional headers the broker requires ...
3.413848
3.496392
0.976392
assert id is not None, "'id' is required" assert subscription is not None, "'subscription' is required" headers = {HDR_MESSAGE_ID: id, HDR_SUBSCRIPTION: subscription} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_R...
def nack(self, id, subscription, transaction=None, receipt=None)
Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str subscription: the subscription this message is associated with :param str transaction: include this nack in a named transaction
2.430817
2.55023
0.953176
for key, val in headers.items(): try: val = val.replace('\\', '\\\\').replace('\n', '\\n').replace(':', '\\c').replace('\r', '\\r') except: pass headers[key] = val
def _escape_headers(self, headers)
:param dict(str,str) headers:
3.075926
2.807126
1.095756
assert id is not None, "'id' is required" headers = {HDR_ID: id} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_RECEIPT] = receipt self.send_frame(CMD_NACK, headers)
def nack(self, id, transaction=None, receipt=None)
Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str transaction: include this nack in a named transaction
3.204924
3.624555
0.884226
for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket(af, socktype, proto) if timeout is not None: sock.settimeout(timeout) sock.connect(sa) return sock ...
def get_socket(host, port, timeout=None)
Return a socket. :param str host: the hostname to connect to :param int port: the port number to connect to :param timeout: if specified, set the socket timeout
1.578835
2.096554
0.753062
self.running = True self.attempt_connection() receiver_thread = self.create_thread_fc(self.__receiver_loop) receiver_thread.name = "StompReceiver%s" % getattr(receiver_thread, "name", "Thread") self.notify('connecting')
def start(self)
Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection.
10.291236
9.57439
1.074871
with self.__receiver_thread_exit_condition: while not self.__receiver_thread_exited and self.is_connected(): self.__receiver_thread_exit_condition.wait()
def stop(self)
Stop the connection. Performs a clean shutdown by waiting for the receiver thread to exit.
5.275153
3.999221
1.319045
with self.__connect_wait_condition: self.connected = connected if connected: self.__connect_wait_condition.notify()
def set_connected(self, connected)
:param bool connected:
4.622567
4.034128
1.145865
with self.__listeners_change_condition: self.listeners[name] = listener
def set_listener(self, name, listener)
Set a named listener to use with this connection. See :py:class:`stomp.listener.ConnectionListener` :param str name: the name of the listener :param ConnectionListener listener: the listener object
9.302919
56.159794
0.165651
frame_type = f.cmd.lower() if frame_type in ['connected', 'message', 'receipt', 'error', 'heartbeat']: if frame_type == 'message': (f.headers, f.body) = self.notify('before_message', f.headers, f.body) if log.isEnabledFor(logging.DEBUG): l...
def process_frame(self, f, frame_str)
:param Frame f: Frame object :param bytes frame_str: raw frame content
3.32945
3.2148
1.035663
if frame_type == 'receipt': # logic for wait-on-receipt notification receipt = headers['receipt-id'] receipt_value = self.__receipts.get(receipt) with self.__send_wait_condition: self.set_receipt(receipt, None) self.__send_...
def notify(self, frame_type, headers=None, body=None)
Utility function for notifying listeners of incoming and outgoing messages :param str frame_type: the type of message :param dict headers: the map of headers associated with the message :param body: the content of the message
3.586651
3.555908
1.008646
with self.__listeners_change_condition: listeners = sorted(self.listeners.items()) for (_, listener) in listeners: if not listener: continue try: listener.on_send(frame) except AttributeError: conti...
def transmit(self, frame)
Convert a frame object to a frame string and transmit to the server. :param Frame frame: the Frame object to transmit
5.030027
5.354122
0.939468
if timeout is not None: wait_time = timeout / 10.0 else: wait_time = None with self.__connect_wait_condition: while self.running and not self.is_connected() and not self.connection_error: self.__connect_wait_condition.wait(wait_time) ...
def wait_for_connection(self, timeout=None)
Wait until we've established a connection with the server. :param float timeout: how long to wait, in seconds
3.324434
3.510079
0.947111
log.info("Starting receiver loop") notify_disconnected = True try: while self.running: try: while self.running: frames = self.__read() for frame in frames: f = ut...
def __receiver_loop(self)
Main loop listening for incoming data.
3.985015
3.978559
1.001623
fastbuf = BytesIO() while self.running: try: try: c = self.receive() except exception.InterruptedException: log.debug("socket read interrupted, restarting") continue except Except...
def __read(self)
Read the next frame(s) from the socket. :return: list of frames read :rtype: list(bytes)
3.658151
3.607882
1.013933
try: return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self) except socket.error: return False
def is_connected(self)
Return true if the socket managed by this connection is connected :rtype: bool
3.804403
3.859329
0.985768
self.running = False if self.socket is not None: if self.__need_ssl(): # # Even though we don't want to use the socket, unwrap is the only API method which does a proper SSL # shutdown # try: ...
def disconnect_socket(self)
Disconnect the underlying socket connection
4.203829
4.110526
1.022698
if self.socket is not None: try: with self.__socket_semaphore: self.socket.sendall(encoded_frame) except Exception: _, e, _ = sys.exc_info() log.error("Error sending frame", exc_info=1) raise e ...
def send(self, encoded_frame)
:param bytes encoded_frame:
3.416809
3.245437
1.052804
try: return self.socket.recv(self.__recv_bytes) except socket.error: _, e, _ = sys.exc_info() if get_errno(e) in (errno.EAGAIN, errno.EINTR): log.debug("socket read interrupted, restarting") raise exception.InterruptedException...
def receive(self)
:rtype: bytes
4.495944
4.158549
1.081133
self.connection_error = False sleep_exp = 1 connect_count = 0 while self.running and self.socket is None and ( connect_count < self.__reconnect_attempts_max or self.__reconnect_attempts_max == -1 ): for host_and_port in self.__host_and_ports...
def attempt_connection(self)
Try connecting to the (host, port) tuples specified at construction time.
2.304512
2.278092
1.011597
if not ssl: raise Exception("SSL connection requested, but SSL library not found") for host_port in for_hosts: self.__ssl_params[host_port] = dict(key_file=key_file, cert_file=cert_file, ...
def set_ssl(self, for_hosts=[], key_file=None, cert_file=None, ca_certs=None, cert_validator=None, ssl_version=DEFAULT_SSL_VERSION, password=None)
Sets up SSL configuration for the given hosts. This ensures socket is wrapped in a SSL connection, raising an exception if the SSL module can't be found. :param for_hosts: a list of tuples describing hosts this SSL configuration should be applied to :param cert_file: the path to a X509 certific...
2.430012
3.109711
0.781427
if not host_and_port: host_and_port = self.current_host_and_port return host_and_port in self.__ssl_params
def __need_ssl(self, host_and_port=None)
Whether current host needs SSL or not. :param (str,int) host_and_port: the host/port pair to check, default current_host_and_port
3.381877
3.487208
0.969795
if not host_and_port: host_and_port = self.current_host_and_port return self.__ssl_params.get(host_and_port)
def get_ssl(self, host_and_port=None)
Get SSL params for the given host. :param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
3.15714
2.61064
1.209336
if self.__quit: return if self.verbose: self.__sysout(frame_type) for k, v in headers.items(): self.__sysout('%s: %s' % (k, v)) else: if 'message-id' in headers: self.__sysout('message-id: %s' % headers['mes...
def __print_async(self, frame_type, headers, body)
Utility function to print a message and setup the command prompt for the next input
2.566287
2.594296
0.989204
self.__sysout('') if 'filename' in headers: content = base64.b64decode(body.encode()) if os.path.exists(headers['filename']): fname = '%s.%s' % (headers['filename'], int(time.time())) else: fname = headers['filename'] ...
def on_message(self, headers, body)
See :py:meth:`ConnectionListener.on_message` Special case: if the header 'filename' is present, the content is written out as a file
3.125573
3.004019
1.040464
text = unicodedata.normalize('NFC', text) if include_punctuation: return [ token.casefold() for token in TOKEN_RE_WITH_PUNCTUATION.findall(text) ] else: return [ token.strip("'").casefold() for token in TOKEN_RE.findall(text) ...
def simple_tokenize(text, include_punctuation=False)
Tokenize the given text using a straightforward, Unicode-aware token expression. The expression mostly implements the rules of Unicode Annex #29 that are contained in the `regex` module's word boundary matching, including the refinement that splits words between apostrophes and vowels in order to s...
2.769818
3.238294
0.855332