code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo("Getting list of repositories ... ", nl=False, err=use_stderr) context_msg = "Failed to get list of repositories!" with handle_api_exceptions(ctx, opts=opts, context_msg=co...
def repos(ctx, opts, owner, page, page_size)
List repositories for a namespace (owner). OWNER: Specify the OWNER namespace (i.e. user or org) to list the repositories for that namespace. If OWNER isn't specified it'll default to the currently authenticated user (if any). If you're unauthenticated, no results will be returned.
2.959769
3.080464
0.960819
status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "stage": stage}
def _get_package_status(package)
Get the status for a package.
4.872631
4.760975
1.023452
# cast number types naturally if isinstance(value, BOOL_COERCEABLE_TYPES): return bool(value) # try to coerce string into number val = text_type(value).strip().lower().replace('.', '', 1) if val.isnumeric(): return bool(float(val)) elif val in BOOLISH_TRUE: return Tr...
def boolify(value, nullable=False, return_string=False)
Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for...
4.115078
4.592555
0.896033
# value must be a string, or there at least needs to be a type hint if isinstance(value, string_types): value = value.strip() elif type_hint is None: # can't do anything because value isn't a string and there's no type hint return value # now we either have a stripped strin...
def typify(value, type_hint=None)
Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type. Args: value (Any): Usually a string, not a sequence type_hint (type or Tuple[type]): Examples: >>> typify('32') 32 ...
3.357394
3.404948
0.986034
# TODO: flatlistify((1, 2, 3), 4, (5, 6, 7)) if val is None: return return_type() elif isiterable(val): return return_type(val) else: return return_type((val, ))
def listify(val, return_type=tuple)
Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c']
3.2279
3.711357
0.869736
# ---------------------------------------------------------------------- # https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132 # ---------------------------------------------------------------------- # First try with a carray rootsfile = os.path.join(rootdir, ROOTDIRS) if...
def open(rootdir, mode='a')
open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) ...
4.936336
4.627403
1.066761
owner, repo, slug = owner_repo_package delete_args = { "owner": click.style(owner, bold=True), "repo": click.style(repo, bold=True), "package": click.style(slug, bold=True), } prompt = "delete the %(package)s from %(owner)s/%(repo)s" % delete_args if not utils.confirm_...
def delete(ctx, opts, owner_repo_package, yes)
Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'.
2.897777
3.30583
0.876566
# pylint: disable=unused-argument form = "OWNER/REPO/IDENTIFIER" return validators.validate_slashes(param, value, minimum=3, maximum=3, form=form)
def validate_owner_repo_identifier(ctx, param, value)
Ensure that owner/repo/identifier is formatted correctly.
8.118072
6.403582
1.267739
@click.option( "--show-tokens", default=False, is_flag=True, help="Show entitlement token string contents in output.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.inv...
def common_entitlements_options(f)
Add common options for entitlement commands.
3.133436
2.762586
1.13424
@common_entitlements_options @decorators.common_cli_config_options @decorators.common_cli_list_options @decorators.common_cli_output_options @decorators.common_api_auth_options @decorators.initialise_api @click.argument( "owner_repo", metavar="OWNER/REPO", callback=validators.v...
def list_entitlements_options(f)
Options for list entitlements subcommand.
3.202554
3.414094
0.938039
owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo( "Getting list of entitlements for the %(repository)s " "repository ... " % {"repository": click.style(repo, bold=True)}, nl=Fa...
def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens)
List entitlements for a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to list entitlements for. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents list your-org/your-repo
3.418057
4.097784
0.834123
if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Updated", "Identifier"] rows = [] for entitlement in sorted(data, key=itemgetter("name")): rows.append( [ click.style( "%(name)s (%(ty...
def print_entitlements(opts, data, page_info=None, show_list_info=True)
Print entitlements as a table or output in another format.
3.068623
3.037867
1.010124
owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Creating %(name)s entitlement for the %(repository)s " "repository ... " % { "name": click.style(name, bold=True...
def create(ctx, opts, owner_repo, show_tokens, name, token)
Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents create your-org/your-repo --name ...
3.584463
4.06602
0.881566
owner, repo, identifier = owner_repo_identifier delete_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } prompt = ( "delete the %(identifier)s entitlement from the %(repository)s " "repository" % delete_args ...
def delete(ctx, opts, owner_repo_identifier, yes)
Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ...
3.100396
3.460426
0.895958
owner, repo, identifier = owner_repo_identifier # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Updating %(identifier)s entitlement for the %(repository)s " "repository ... " % { "ident...
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token)
Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmi...
3.45696
3.935204
0.87847
owner, repo, identifier = owner_repo_identifier refresh_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" p...
def refresh(ctx, opts, owner_repo_identifier, show_tokens, yes)
Refresh an entitlement in a repository. Note that this changes the token associated with the entitlement. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-o...
3.496021
3.768675
0.927653
owner, repo = owner_repo sync_args = { "source": click.style(source, bold=True), "dest": click.style(repo, bold=True), "warning": click.style("*** WARNING ***", fg="yellow"), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.o...
def sync(ctx, opts, owner_repo, show_tokens, source, yes)
Sync entitlements from another repository. ***WARNING*** This will DELETE ALL of the existing entitlements in the repository and replace them with entitlements from the source repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to sync entitleme...
3.148001
3.051498
1.031625
"Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
def ctime(message=None)
Counts the time spent in some context
7.595915
5.562204
1.36563
# pylint: disable=fixme # pylint: disable=global-statement # FIXME: Yes, I know this is not great. We'll fix it later. :-) global LAST_CLIENT, LAST_HEADERS if LAST_CLIENT and LAST_HEADERS: # Wait based on previous client/headers rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atex...
def maybe_rate_limit(client, headers, atexit=False)
Optionally pause the process based on suggested rate interval.
4.878541
4.691337
1.039904
if not client or not headers: return False if not getattr(client.config, "rate_limit", False): return False rate_info = RateLimitsInfo.from_headers(headers) if not rate_info or not rate_info.interval: return False if rate_info.interval: cb = getattr(client.con...
def rate_limit(client, headers, atexit=False)
Pause the process based on suggested rate interval.
2.723082
2.606416
1.044761
client = get_status_api() with catch_raise_api_exception(): data, _, headers = client.status_check_basic_with_http_info() ratelimits.maybe_rate_limit(client, headers) if with_version: return data.detail, data.version return data.detail
def get_status(with_version=False)
Retrieve status (and optionally) version from the API.
8.144464
7.718613
1.055172
return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x)
Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq tha...
4.185452
8.70474
0.480824
try: reduce(lambda _, y: y(), seq) except TypeError as e: if text_type(e) != "reduce() of empty sequence with no initial value": raise
def call_each(seq)
Calls each element of sequence to invoke the side effect. Args: seq: Returns: None
5.775576
6.556496
0.880894
try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", param=param, ) value = "%s:%s" % (username.strip(), password) value = base64.b64encode(byte...
def transform_api_header_authorization(param, value)
Transform a username:password value into a base64 string.
2.991302
2.648552
1.12941
# pylint: disable=unused-argument if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=", 1) k = k.strip() for bad_header in BAD_API_HEADERS: if bad_header == k: raise clic...
def validate_api_headers(param, value)
Validate that API headers is a CSV of k=v pairs.
2.64849
2.485463
1.065592
try: value = value.split("/") except ValueError: value = None if value: if len(value) < minimum: value = None elif maximum and len(value) > maximum: value = None if not value: form = form or "/".join("VALUE" for _ in range(minimum)) ...
def validate_slashes(param, value, minimum=2, maximum=None, form=None)
Ensure that parameter has slashes and minimum parts.
2.966388
2.996016
0.990111
# pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
def validate_owner_repo(ctx, param, value)
Ensure that owner/repo is formatted correctly.
7.968082
6.639894
1.200031
# pylint: disable=unused-argument form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
def validate_owner_repo_package(ctx, param, value)
Ensure that owner/repo/package is formatted correctly.
7.305305
5.975819
1.222478
# pylint: disable=unused-argument form = "OWNER/REPO/DISTRO[/RELEASE]" return validate_slashes(param, value, minimum=3, maximum=4, form=form)
def validate_owner_repo_distro(ctx, param, value)
Ensure that owner/repo/distro/version is formatted correctly.
8.320134
7.300499
1.139667
# pylint: disable=unused-argument if value == 0: raise click.BadParameter( "Page is not zero-based, please set a value to 1 or higher.", param=param ) return value
def validate_page(ctx, param, value)
Ensure that a valid value for page is chosen.
5.0677
4.17783
1.212998
# pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
def validate_page_size(ctx, param, value)
Ensure that a valid value for page size is chosen.
3.934587
3.425156
1.148732
if not all([self.api_key, self.api_secret]): raise AuthException() endpoint = "/v1/me/getbalance" return self.request(endpoint, params=params)
def getbalance(self, **params)
Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
4.249979
5.413595
0.785057
''' removes all overridden and inherited variables from hosts and groups ''' global _vars _vars = dict() _vars[host] = inventory_mgr.inventory.get_host_vars(host) for group in host.get_groups(): remove_inherited_and_overridden_vars(_vars[host], group, inventory_mgr) remove_in...
def tidy_all_the_variables(host, inventory_mgr)
removes all overridden and inherited variables from hosts and groups
4.604796
3.487307
1.320445
import os from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars ''' merges all entities by inventory source ''' data = {} for inventory_dir in self.variable_manager._inventory._sources: if ',' in inventory_dir: # skip host...
def _plugins_inventory(self, entities)
merges all entities by inventory source
5.367305
4.58888
1.169633
# TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: self.password = options['password'] else: self.password = None sel...
def handle(self, *args, **options)
gets data from WordPress site
3.229385
3.141353
1.028024
soup = BeautifulSoup(body, "html5lib") for img in soup.findAll('img'): old_url = img['src'] if 'width' in img: width = img['width'] if 'height' in img: height = img['height'] else: width = 100 ...
def create_images_from_urls_in_content(self, body)
create Image objects and transfer image files to media root
2.723071
2.707502
1.00575
for comment in comments: if comment.wordpress_id == comment_id: return comment
def lookup_comment_by_wordpress_id(self, comment_id, comments)
Returns Django comment object with this wordpress id
2.87577
2.393482
1.201501
for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title = self.convert_html_entities(title) title = new_title slug = post.get('slug') description = post.get('description') ...
def create_blog_pages(self, posts, blog_index, *args, **options)
create Blog post entries from wordpress data
3.071972
3.015002
1.018896
slug_field = instance._meta.get_field(slug_field_name) slug = getattr(instance, slug_field.attname) slug_len = slug_field.max_length # Sort out the initial slug, limiting its length if necessary. slug = slugify(value) if slug_len: slug = slug[:slug_len] slug = _slug_strip(slug...
def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-')
Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all(...
1.61475
1.699754
0.94999
separator = separator or '' if separator == '-' or not separator: re_sep = '-' else: re_sep = '(?:-|%s)' % re.escape(separator) # Remove multiple instances and if an alternate separator is provided, # replace the default '-' separator. if separator != re_sep: value =...
def _slug_strip(value, separator='-')
Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator.
2.98264
2.69717
1.10584
LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None) if LIMIT_AUTHOR_CHOICES: if isinstance(LIMIT_AUTHOR_CHOICES, str): limit = Q(groups__name=LIMIT_AUTHOR_CHOICES) else: limit = Q() for s in LIMIT_AUTHOR_CHOICES: ...
def limit_author_choices()
Limit choices in blog author field based on config settings
2.334913
2.200277
1.061191
context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all_categories'] = BlogCategory.objects.all() context['root_categories'] = BlogCategory...
def get_blog_context(context)
Get context data useful on all blog related pages
2.842538
2.84274
0.999929
# splitting xml into sections, pre_chan is preamble before <channel> pre_chan, chan, post_chan= xml_string.partition('<channel>') # replace xmlns statements on preamble pre_chan = re.sub(r'xmlns:(?P<label>\w*)\=\"(?P<val>[^\"]*)\"', r'xmlns:\g<label>...
def remove_xmlns(xml_string)
changes the xmlns (XML namespace) so that values are replaced with the string representation of their key this makes the import process for portable >>> xp = XML_parser >>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/">' >>> xp.remove...
6.858259
6.808583
1.007296
# mocking wierd JSON structure ret_dict = {"terms":{"category":[],"post_tag":[]}} for e in item: # is it a category or tag?? if "category" in e.tag: # get details slug = e.attrib["nicename"] name = htmlparser.unesca...
def item_dict(self, item)
create a default dict of values, including category and tag lookup
3.68191
3.531574
1.042569
if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback: d = fallback try: date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z')) except ValueError: date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S')) ...
def convert_date(d, custom_date_string=None, fallback=None)
for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000' shows up. ...
2.251609
2.086729
1.079014
if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ret_dict = {} # slugify post title if no slug exists ret_dict['slug']= item_dict.get('{wp}post_name') or re....
def translate_item(self, item_dict)
cleanup item keys to match API json format
3.94378
3.964671
0.994731
comment_dict = {} comment_dict['ID'] = e.find('./{wp}comment_id').text comment_dict['date'] = e.find('{wp}comment_date').text comment_dict['content'] = e.find('{wp}comment_content').text comment_dict['status'] = e.find('{wp}comment_approved').text comment_dict['s...
def translate_wp_comment(self, e)
<wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CD...
1.855118
1.776182
1.044441
items = self.chan.findall("item") #(e for e in chan.getchildren() if e.tag=='item') # turn item element into a generic dict item_dict_gen = (self.item_dict(item) for item in items) # transform the generic dict to one with the expected JSON keys all_the_data = [self.trans...
def get_posts_data(self)
given a WordPress xml export file, will return list of dictionaries with keys that match the expected json keys of a wordpress API call >>> xp = XML_parser('example_export.xml') >>> json_vals = {"slug","ID", "title","description", "content", "author", "terms", "date", } >>> data ...
6.555008
6.022273
1.088461
all_the_data = [] for item in self.chan.findall("item"): if not item.find('{wp}post_name').text == slug: continue item_dict = self.item_dict(item) if not item_dict or not item_dict.get('title'): continue slug = item...
def get_comments_data(self, slug)
Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' author: {'username': 'Name', 'URL': ''}
4.06856
4.018261
1.012518
content = re.sub(r'\n', '<br/>\n', content) content = re.sub(r' ', '&#160;&#160;', content) content = re.sub(r'&#160; ', '&#160;&#160;', content) return content
def _format_content(self, content)
Returns `content` with consecutive spaces converted to non-break spaces, and linebreak converted into HTML br elements. :param content: text to format :type content: `str` :rtype: `str`
2.301654
2.308577
0.997001
# Remove characters that should be escaped for XML input (but # which cause problems when escaped, since they become # tokens). text = re.sub(r'[<>&]', '', text) pattern = r'({})'.format(self._tokenizer.pattern) return re.sub(pattern, self._base_token_markup, tex...
def _prepare_text(self, text)
Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str`
10.507488
10.000832
1.050661
template = self._get_template() colours = generate_colours(len(ngrams)) for siglum in self._corpus.get_sigla(work): ngram_data = zip(labels, ngrams) content = self._generate_base(work, siglum) for ngrams_group in ngrams: content = self...
def generate(self, output_dir, work, ngrams, labels, minus_ngrams)
Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param output_dir: directory to write report to :type output_dir: `str` ...
4.088655
3.833322
1.066609
self._add_highlight = highlight for ngram in ngrams: pattern = self._get_regexp_pattern(ngram) content = re.sub(pattern, self._annotate_tokens, content) self._ngrams_count += 1 return content
def _highlight(self, content, ngrams, highlight)
Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of `str` :param highlight: whether to highlight or unhig...
4.662668
5.453848
0.854932
template = self._get_template() matches = pd.read_csv(matches_filename) for siglum in self._corpus.get_sigla(work): subm = matches[(matches[constants.WORK_FIELDNAME] != work) | (matches[constants.SIGLUM_FIELDNAME] != siglum)] content = ...
def generate(self, output_dir, work, matches_filename)
Generates HTML reports showing the text of each witness to `work` with its matches in `matches` highlighted. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type text_name: `str` :param matches_filename: fil...
4.076225
3.89185
1.047375
# For each packet in the pcap process the contents for item in self.input_stream: # Output object output = {} # Grab the fields I need timestamp = item['timestamp'] buf = item['raw_buf'] # Print out the timestamp in UTC...
def packet_meta_data(self)
Pull out the metadata about each packet from the input_stream Args: None Returns: generator (dictionary): a generator that contains packet meta data in the form of a dictionary
3.864106
3.796316
1.017857
print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']), len(flow['payload']), repr(flow['payload'])[:30]))
def print_flow_info(flow)
Print a summary of the flow information
5.601576
5.444584
1.028834
# For each packet, place it into either an existing flow or a new flow for packet in self.input_stream: # Compute flow tuple and add the packet to the flow flow_id = flow_utils.flow_tuple(packet) self._flows[flow_id].add_packet(packet) # Yield ...
def packets_to_flows(self)
Combine packets into flows
4.49209
4.322241
1.039297
base_directory = 'assets/{}'.format(self._report_name) for asset in resource_listdir(self._package_name, base_directory): filename = resource_filename( self._package_name, '{}/{}'.format(base_directory, asset)) shutil.copy2(filename, output_dir)
def _copy_static_assets(self, output_dir)
Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `str`
3.811446
3.705491
1.028594
loader = PackageLoader(self._package_name, 'assets/templates') env = Environment(extensions=['jinja2.ext.with_'], loader=loader) return env.get_template('{}.html'.format(self._report_name))
def _get_template(self)
Returns a template for this report. :rtype: `jinja2.Template`
4.184681
3.669326
1.14045
if template is None: template = self._get_template() report = template.render(context) output_file = os.path.join(report_dir, report_name) with open(output_file, 'w', encoding='utf-8') as fh: fh.write(report) if assets_dir: self._copy_...
def _write(self, context, report_dir, report_name, assets_dir=None, template=None)
Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. If `template` is supplied, uses that template instead of automatically finding it. This is useful i...
2.025614
2.125068
0.9532
# For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transport info if item['transport']: print(item['transport']['type'],...
def pull(self)
Print out summary information about each packet from the input_stream
3.517825
3.3086
1.063237
# For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('Timestamp: %s' % item['timestamp']) # Unpack the Ethernet frame (mac src/dst, ethertype) print('Ethernet Frame: %s --> %s ...
def pull(self)
Print out information about each packet from the input_stream
3.326606
3.192304
1.042071
settings = {} settings['SECRET_KEY'] = orm_config.get('secret_key', '') db_config = orm_config['database'] if db_config: settings['DATABASES'] = { 'default': database_settings(db_config) } from django_peeringdb.client_adaptor.setup import configure # Override d...
def load_backend(**orm_config)
Load the client adaptor module of django_peeringdb Assumes config is valid.
4.95307
4.16168
1.190161
self._logger.info('Adding label count') def add_label_count(df): # For each n-gram and label pair, we need the maximum count # among all witnesses to each work, and then the sum of those # across all works. work_maxima = df.groupby(constants.WORK...
def add_label_count(self)
Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work.
3.812347
3.138752
1.214606
self._logger.info('Adding label work count') def add_label_text_count(df): work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).any() df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[ constants....
def add_label_work_count(self)
Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followe...
3.174372
2.849524
1.114001
lcf = constants.LABEL_COUNT_FIELDNAME nf = constants.NGRAM_FIELDNAME ngram = row[constants.NGRAM_FIELDNAME] label_count = row[constants.LABEL_COUNT_FIELDNAME] if label_count == 1 and not smaller.empty: # Keep a result with a label count of 1 if its ...
def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize, join)
Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count is 1 and its constituent (n-1)-grams also have a label count of 1; or * there is a containing (n+1)-gram that has the same label count. :param ...
3.999268
3.31177
1.207592
temp_fd, temp_path = tempfile.mkstemp(text=True) try: self._prepare_bifurcated_extend_data(corpus, max_size, temp_path, temp_fd) finally: try: os.remove(temp_path) except OSError as e: ...
def bifurcated_extend(self, corpus, max_size)
Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` ...
3.777973
3.848674
0.98163
# In order to allow for additional columns to be present in # the input data (such as label count), copy the siglum # information into a new final column, then put the sigla # information into the siglum field and finally rename it. # # This means that in merge_s...
def collapse_witnesses(self)
Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run...
4.880149
4.396871
1.109914
self._matches.to_csv(fh, encoding='utf-8', float_format='%d', index=False) return fh
def csv(self, fh)
Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object
6.128435
7.593463
0.807067
self._logger.info('Excising results containing "{}"'.format(ngram)) if not ngram: return self._matches = self._matches[~self._matches[ constants.NGRAM_FIELDNAME].str.contains(ngram, regex=False)]
def excise(self, ngram)
Removes all rows whose n-gram contains `ngram`. This operation uses simple string containment matching. For tokens that consist of multiple characters, this means that `ngram` may be part of one or two tokens; eg, "he m" would match on "she may". :param ngram: n-gram to remove ...
5.553744
5.647861
0.983336
self._logger.info('Extending results') if self._matches.empty: return highest_n = self._matches[constants.SIZE_FIELDNAME].max() if highest_n == 1: self._logger.warning( 'Extending results that contain only 1-grams is unsupported; ' ...
def extend(self, corpus)
Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus`
4.831316
4.387698
1.101105
# Add data for each n-gram within each extended n-gram. Since # this treats each extended piece of text separately, the same # n-gram may be generated more than once, so the complete set # of new possible matches for this filename needs to combine # the counts for such. ...
def _generate_extended_matches(self, extended_ngrams, highest_n, work, siglum, label)
Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :param extended_ngrams: extended n-grams :type extended_ngrams: `list` of `str` :param highest_n: the highest degree of ...
3.892758
3.768967
1.032845
max_size = data[constants.SIZE_FIELDNAME].max() kept_ngrams = list(data[data[constants.SIZE_FIELDNAME] == min_size][ constants.NGRAM_FIELDNAME]) for size in range(min_size+1, max_size+1): pattern = FilteredWitnessText.get_filter_ngrams_pattern( ke...
def _generate_filter_ngrams(self, data, min_size)
Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` :rtype: `list` of `str`
3.354364
3.384688
0.991041
text = Text(ngram, self._tokenizer) substrings = [] for sub_size, ngrams in text.get_ngrams(1, size-1): for sub_ngram, count in ngrams.items(): substrings.extend([sub_ngram] * count) return substrings
def _generate_substrings(self, ngram, size)
Returns a list of all substrings of `ngram`. :param ngram: n-gram to generate substrings of :type ngram: `str` :param size: size of `ngram` :type size: `int` :rtype: `list`
4.226097
4.93115
0.857021
if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[ constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, ...
def group_by_ngram(self, labels)
Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order on :type labels: `list` of `str`
2.637197
2.585736
1.019902
if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, ...
def group_by_witness(self)
Groups results by witness, providing a single summary field giving the n-grams found in it, a count of their number, and the count of their combined occurrences.
2.77472
2.606124
1.064692
sample = results.iloc[0] ngram = sample[constants.NGRAM_FIELDNAME] label = sample[constants.LABEL_FIELDNAME] return not(results[ (results[constants.NGRAM_FIELDNAME] == ngram) & (results[constants.LABEL_FIELDNAME] != label)].empty)
def _is_intersect_results(results)
Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool`
3.96553
3.399249
1.16659
self._logger.info('Pruning results by n-gram') self._matches = self._matches[ ~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
def prune_by_ngram(self, ngrams)
Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str`
6.875976
5.336961
1.288369
self._logger.info('Pruning results by n-gram count') def calculate_total(group): work_grouped = group.groupby(constants.WORK_FIELDNAME, sort=False) total_count = work_grouped[constants.COUNT_FIELDNAME].max().sum() group['total_count'] = pd.Series([total_coun...
def prune_by_ngram_count(self, minimum=None, maximum=None, label=None)
Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all works is the maximum count across the witnesses for that work. If `label` ...
3.016593
2.848963
1.058839
self._logger.info('Pruning results by n-gram count per work') matches = self._matches keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique() if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] if minimum and maximum: ...
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None)
Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept...
2.01263
2.008188
1.002212
self._logger.info('Pruning results by n-gram size') if minimum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] >= minimum] if maximum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] <...
def prune_by_ngram_size(self, minimum=None, maximum=None)
Removes results rows whose n-gram size is outside the range specified by `minimum` and `maximum`. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int`
3.351416
3.014233
1.111864
self._logger.info('Pruning results by work count') count_fieldname = 'tmp_count' matches = self._matches if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] filtered = matches[matches[constants.COUNT_FIELDNAME] > 0] gr...
def prune_by_work_count(self, minimum=None, maximum=None, label=None)
Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in multiple witnesses of the same work are counted as a single work. If ...
2.480282
2.429984
1.020699
self._logger.info( 'Removing n-grams that are not attested in all labels') self._matches = self._reciprocal_remove(self._matches)
def reciprocal_remove(self)
Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.
13.528609
7.633213
1.772335
self._logger.info('Reducing the n-grams') # This does not make use of any pandas functionality; it # probably could, and if so ought to. data = {} labels = {} # Derive a convenient data structure from the rows. for row_index, row in self._matches.iterrows...
def reduce(self)
Removes results rows whose n-grams are contained in larger n-grams.
2.763931
2.648425
1.043613
# Find all substrings of `ngram` and reduce their count by the # count of `ngram`. Substrings may not exist in `data`. count = data[ngram]['count'] for substring in self._generate_substrings(ngram, data[ngram]['size']): try: substring_data = data[subs...
def _reduce_by_ngram(self, data, ngram)
Lowers the counts of all n-grams in `data` that are substrings of `ngram` by `ngram`\'s count. Modifies `data` in place. :param data: row data dictionary for the current text :type data: `dict` :param ngram: n-gram being reduced :type ngram: `str`
4.843377
4.093114
1.183299
for work, label in catalogue.items(): self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work, constants.LABEL_FIELDNAME] = label
def relabel(self, catalogue)
Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type cat...
7.902981
5.760334
1.371966
self._logger.info('Removing label "{}"'.format(label)) count = self._matches[constants.LABEL_FIELDNAME].value_counts().get( label, 0) self._matches = self._matches[ self._matches[constants.LABEL_FIELDNAME] != label] self._logger.info('Removed {} labelled ...
def remove_label(self, label)
Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str`
3.877007
3.592124
1.079308
self._matches.sort_values( by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME, constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME, constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME], ascending=[False, True, False, True, True, True], inpl...
def sort(self)
Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum.
5.627891
3.038974
1.851905
self._logger.info('Zero-filling results') zero_rows = [] work_sigla = {} grouping_cols = [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, constants.WORK_FIELDNAME] grouped = self._matches.groupby(grouping_cols, sor...
def zero_fill(self, corpus)
Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results :type corpus: `Corpus`
2.811484
2.714559
1.035706
# Grab the logger if not hasattr(get_logger, 'logger'): # Setup the default logging config get_logger.logger = logging.getLogger('chains') format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s' logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.IN...
def get_logger()
Setup logging output defaults
2.860127
2.768314
1.033166
# Spin up the packet capture if self._iface_is_file(): self.pcap = pcapy.open_offline(self.iface_name) else: try: # self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True) # snaplen (maximum number of bytes to ...
def read_interface(self)
Read Packets from the packet capture interface
4.400113
4.379385
1.004733
parser = argparse.ArgumentParser( description=constants.TACL_DESCRIPTION, formatter_class=ParagraphFormatter) subparsers = parser.add_subparsers(title='subcommands') generate_align_subparser(subparsers) generate_catalogue_subparser(subparsers) generate_counts_subparser(subparser...
def generate_parser()
Returns a parser configured with sub-commands and arguments.
2.635026
2.557702
1.030232
parser = subparsers.add_parser( 'align', description=constants.ALIGN_DESCRIPTION, epilog=constants.ALIGN_EPILOG, formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP) parser.set_defaults(func=align_results) utils.add_common_arguments(parser) parser.add_argument('-m'...
def generate_align_subparser(subparsers)
Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results.
2.656498
2.655231
1.000477
catalogue = tacl.Catalogue() catalogue.generate(args.corpus, args.label) catalogue.save(args.catalogue)
def generate_catalogue(args, parser)
Generates and saves a catalogue file.
7.21061
6.642395
1.085544
parser = subparsers.add_parser( 'catalogue', description=constants.CATALOGUE_DESCRIPTION, epilog=constants.CATALOGUE_EPILOG, formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP) utils.add_common_arguments(parser) parser.set_defaults(func=generate_catalogue) par...
def generate_catalogue_subparser(subparsers)
Adds a sub-command parser to `subparsers` to generate and save a catalogue file.
2.58215
2.618529
0.986107
parser = subparsers.add_parser( 'counts', description=constants.COUNTS_DESCRIPTION, epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.COUNTS_HELP) parser.set_defaults(func=ngram_counts) utils.add_common_arguments(parser) utils.add_db_argument...
def generate_counts_subparser(subparsers)
Adds a sub-command parser to `subparsers` to make a counts query.
2.518146
2.463049
1.022369
parser = subparsers.add_parser( 'diff', description=constants.DIFF_DESCRIPTION, epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.DIFF_HELP) parser.set_defaults(func=ngram_diff) group = parser.add_mutually_exclusive_group() group.add_argument('...
def generate_diff_subparser(subparsers)
Adds a sub-command parser to `subparsers` to make a diff query.
2.760203
2.72634
1.012421
parser = subparsers.add_parser( 'excise', description=constants.EXCISE_DESCRIPTION, help=constants.EXCISE_HELP) parser.set_defaults(func=excise) utils.add_common_arguments(parser) parser.add_argument('ngrams', metavar='NGRAMS', help=constants.EXCISE_NGRAMS_HE...
def generate_excise_subparser(subparsers)
Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.
1.963121
1.914395
1.025452
parser = subparsers.add_parser( 'highlight', description=constants.HIGHLIGHT_DESCRIPTION, epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter, help=constants.HIGHLIGHT_HELP) parser.set_defaults(func=highlight_text) utils.add_common_arguments(parser) parser....
def generate_highlight_subparser(subparsers)
Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result.
2.022817
2.024424
0.999206
parser = subparsers.add_parser( 'intersect', description=constants.INTERSECT_DESCRIPTION, epilog=constants.INTERSECT_EPILOG, formatter_class=ParagraphFormatter, help=constants.INTERSECT_HELP) parser.set_defaults(func=ngram_intersection) utils.add_common_arguments(parser) uti...
def generate_intersect_subparser(subparsers)
Adds a sub-command parser to `subparsers` to make an intersection query.
2.517648
2.531486
0.994534