INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Call if an element of this plottype is clicked.
Implement in sub class. | def clicked(self, event):
"""
Call if an element of this plottype is clicked.
Implement in sub class.
"""
group = event.artist._mt_group
indices = event.ind
# double click only supported on 1.2 or later
major, minor, _ = mpl_version.split('.')
if... |
Print useful information about the log file. | def run(self, arguments=None):
"""Print useful information about the log file."""
LogFileTool.run(self, arguments)
for i, self.logfile in enumerate(self.args['logfile']):
if i > 0:
print("\n ------------------------------------------\n")
if self.logfile.... |
Lazy evaluation of start and end of logfile.
Returns None for stdin input currently. | def filesize(self):
"""
Lazy evaluation of start and end of logfile.
Returns None for stdin input currently.
"""
if self.from_stdin:
return None
if not self._filesize:
self._calculate_bounds()
return self._filesize |
Lazy evaluation of the number of lines.
Returns None for stdin input currently. | def num_lines(self):
"""
Lazy evaluation of the number of lines.
Returns None for stdin input currently.
"""
if self.from_stdin:
return None
if not self._num_lines:
self._iterate_lines()
return self._num_lines |
Return all version changes. | def versions(self):
"""Return all version changes."""
versions = []
for v, _ in self.restarts:
if len(versions) == 0 or v != versions[-1]:
versions.append(v)
return versions |
Get next line, adjust for year rollover and hint datetime format. | def next(self):
"""Get next line, adjust for year rollover and hint datetime format."""
# use readline here because next() iterator uses internal readahead
# buffer so seek position is wrong
line = self.filehandle.readline()
line = line.decode('utf-8', 'replace')
if line ... |
Count number of lines (can be expensive). | def _iterate_lines(self):
"""Count number of lines (can be expensive)."""
self._num_lines = 0
self._restarts = []
self._rs_state = []
ln = 0
for ln, line in enumerate(self.filehandle):
line = line.decode("utf-8", "replace")
if (self._has_level is ... |
Calculate beginning and end of logfile. | def _calculate_bounds(self):
"""Calculate beginning and end of logfile."""
if self._bounds_calculated:
# Assume no need to recalc bounds for lifetime of a Logfile object
return
if self.from_stdin:
return False
# we should be able to find a valid log ... |
Internal helper function.
Find the current (or previous if prev=True) line in a log file based on
the current seek position. | def _find_curr_line(self, prev=False):
"""
Internal helper function.
Find the current (or previous if prev=True) line in a log file based on
the current seek position.
"""
curr_pos = self.filehandle.tell()
# jump back 15k characters (at most) and find last newli... |
Fast-forward file to given start_dt datetime obj using binary search.
Only fast for files. Streams need to be forwarded manually, and it will
miss the first line that would otherwise match (as it consumes the log
line). | def fast_forward(self, start_dt):
"""
Fast-forward file to given start_dt datetime obj using binary search.
Only fast for files. Streams need to be forwarded manually, and it will
miss the first line that would otherwise match (as it consumes the log
line).
"""
i... |
Get start end end date of logfile before starting to parse. | def setup(self):
"""Get start end end date of logfile before starting to parse."""
if self.mlogfilter.is_stdin:
# assume this year (we have no other info)
now = datetime.now()
self.startDateTime = datetime(now.year, 1, 1, tzinfo=tzutc())
self.endDateTime =... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
if self.fromReached and self.seek_to:
if self.seek_to != -1:
self.to... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
ns = logevent.nscanned
nr = logevent.nreturned
if ns is not None and nr is not ... |
Lazy evaluation of the number of events. | def num_events(self):
"""Lazy evaluation of the number of events."""
if not self._num_events:
self._num_events = self.coll_handle.count()
return self._num_events |
Make iterators. | def next(self):
"""Make iterators."""
if not self.cursor:
self.cursor = self.coll_handle.find().sort([("ts", ASCENDING)])
doc = self.cursor.next()
doc['thread'] = self.name
le = LogEvent(doc)
return le |
Calculate beginning and end of log events. | def _calculate_bounds(self):
"""Calculate beginning and end of log events."""
# get start datetime
first = self.coll_handle.find_one(None, sort=[("ts", ASCENDING)])
last = self.coll_handle.find_one(None, sort=[("ts", DESCENDING)])
self._start = first['ts']
if self._start... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
for word in self.words:
if re.search(word, logevent.line_str):
retur... |
Run each line through log2code and group by matched pattern. | def run(self):
"""Run each line through log2code and group by matched pattern."""
if ProfileCollection and isinstance(self.mloginfo.logfile,
ProfileCollection):
print("\n not available for system.profile collections\n")
return
... |
Convert shell syntax to json. | def shell2json(s):
"""Convert shell syntax to json."""
replace = {
r'BinData\(.+?\)': '1',
r'(new )?Date\(.+?\)': '1',
r'Timestamp\(.+?\)': '1',
r'ObjectId\(.+?\)': '1',
r'DBRef\(.+?\)': '1',
r'undefined': '1',
r'MinKey': '1',
r'MaxKey': '1',
... |
Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names. | def json2pattern(s):
"""
Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names.
"""
# make valid JSON by wrapping field names in quotes
s, _ = re.subn(r'([{,])\s*([^,{\s\'"]+)\s*:', ' \\1 "\\2" : ', s)
# handle shell values that are not valid JS... |
All rows need to be a list of dictionaries, all with the same keys. | def print_table(rows, override_headers=None, uppercase_headers=True):
"""All rows need to be a list of dictionaries, all with the same keys."""
if len(rows) == 0:
return
keys = list(rows[0].keys())
headers = override_headers or keys
if uppercase_headers:
rows = [dict(zip(keys,
... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
# if several filters are active, all have to agree
if self.components and logevent.compo... |
Set line_str.
Line_str is only writeable if LogEvent was created from a string,
not from a system.profile documents. | def set_line_str(self, line_str):
"""
Set line_str.
Line_str is only writeable if LogEvent was created from a string,
not from a system.profile documents.
"""
if not self.from_string:
raise ValueError("can't set line_str for LogEvent created from "
... |
Return line_str depending on source, logfile or system.profile. | def get_line_str(self):
"""Return line_str depending on source, logfile or system.profile."""
if self.from_string:
return ' '.join([s for s in [self.merge_marker_str,
self._datetime_str,
self._line_str] if s])
... |
Split string into tokens (lazy). | def split_tokens(self):
"""Split string into tokens (lazy)."""
if not self._split_tokens_calculated:
# split into items (whitespace split)
self._split_tokens = self._line_str.split()
self._split_tokens_calculated = True
return self._split_tokens |
Calculate duration if available (lazy). | def duration(self):
"""Calculate duration if available (lazy)."""
if not self._duration_calculated:
self._duration_calculated = True
# split_tokens = self.split_tokens
line_str = self.line_str
if (line_str
and line_str.endswith('ms')
... |
Extract datetime if available (lazy). | def datetime(self):
"""Extract datetime if available (lazy)."""
if not self._datetime_calculated:
self._datetime_calculated = True
# if no datetime after 10 tokens, break to avoid parsing
# very long lines
split_tokens = self.split_tokens[:10]
... |
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime Wed Dec 31 19:00:00.000
iso8601-utc 1970-01... | def _match_datetime_pattern(self, tokens):
"""
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime ... |
Extract thread name if available (lazy). | def thread(self):
"""Extract thread name if available (lazy)."""
if not self._thread_calculated:
self._thread_calculated = True
split_tokens = self.split_tokens
if not self.datetime_nextpos:
return None
if len(split_tokens) <= self.dateti... |
Extract operation if available (lazy).
Operations: query, insert, update, remove, getmore, command | def operation(self):
"""
Extract operation if available (lazy).
Operations: query, insert, update, remove, getmore, command
"""
if not self._operation_calculated:
self._operation_calculated = True
self._extract_operation_and_namespace()
return se... |
Extract namespace if available (lazy). | def namespace(self):
"""Extract namespace if available (lazy)."""
if not self._operation_calculated:
self._operation_calculated = True
self._extract_operation_and_namespace()
return self._namespace |
Helper method to extract both operation and namespace from a logevent.
It doesn't make sense to only extract one as they appear back to back
in the token list. | def _extract_operation_and_namespace(self):
"""
Helper method to extract both operation and namespace from a logevent.
It doesn't make sense to only extract one as they appear back to back
in the token list.
"""
split_tokens = self.split_tokens
if not self._date... |
Extract query pattern from operations. | def pattern(self):
"""Extract query pattern from operations."""
if not self._pattern:
# trigger evaluation of operation
if (self.operation in ['query', 'getmore', 'update', 'remove'] or
self.command in ['count', 'findandmodify']):
self._patter... |
Extract query pattern from operations. | def sort_pattern(self):
"""Extract query pattern from operations."""
if not self._sort_pattern:
# trigger evaluation of operation
if self.operation in ['query', 'getmore']:
self._sort_pattern = self._find_pattern('orderby: ')
return self._sort_pattern |
Extract the actual query (not pattern) from operations. | def actual_query(self):
"""Extract the actual query (not pattern) from operations."""
if not self._actual_query:
# trigger evaluation of operation
if (self.operation in ['query', 'getmore', 'update', 'remove'] or
self.command in ['count', 'findandmodify']):
... |
Extract the actual sort key (not pattern) from operations. | def actual_sort(self):
"""Extract the actual sort key (not pattern) from operations."""
if not self._actual_sort:
# trigger evaluation of operation
if self.operation in ['query', 'getmore']:
self._actual_sort = self._find_pattern('orderby: ',
... |
Extract query pattern from operations. | def command(self):
"""Extract query pattern from operations."""
if not self._command_calculated:
self._command_calculated = True
if self.operation == 'command':
try:
command_idx = self.split_tokens.index('command:')
command... |
Extract nscanned or keysExamined counter if available (lazy). | def nscanned(self):
"""Extract nscanned or keysExamined counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nscanned |
Extract counters if available (lazy).
Looks for nscannedObjects or docsExamined. | def nscannedObjects(self):
"""
Extract counters if available (lazy).
Looks for nscannedObjects or docsExamined.
"""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nscannedObjects |
Extract ntoreturn counter if available (lazy). | def ntoreturn(self):
"""Extract ntoreturn counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._ntoreturn |
Extract ntoreturn counter if available (lazy). | def writeConflicts(self):
"""Extract ntoreturn counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._writeConflicts |
Extract ninserted or nInserted counter if available (lazy). | def ninserted(self):
"""Extract ninserted or nInserted counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._ninserted |
Extract ndeleted or nDeleted counter if available (lazy). | def ndeleted(self):
"""Extract ndeleted or nDeleted counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._ndeleted |
Extract nupdated or nModified counter if available (lazy). | def nupdated(self):
"""Extract nupdated or nModified counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nupdated |
Extract numYields counter if available (lazy). | def numYields(self):
"""Extract numYields counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._numYields |
Extract planSummary if available (lazy). | def planSummary(self):
"""Extract planSummary if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._planSummary |
Extract planSummary including JSON if available (lazy). | def actualPlanSummary(self):
"""Extract planSummary including JSON if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._actualPlanSummary |
Extract read lock (r) counter if available (lazy). | def r(self):
"""Extract read lock (r) counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._r |
Extract write lock (w) counter if available (lazy). | def w(self):
"""Extract write lock (w) counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._w |
Extract counters like nscanned and nreturned from the logevent. | def _extract_counters(self):
"""Extract counters like nscanned and nreturned from the logevent."""
# extract counters (if present)
counters = ['nscanned', 'nscannedObjects', 'ntoreturn', 'nreturned',
'ninserted', 'nupdated', 'ndeleted', 'r', 'w', 'numYields',
... |
Extract log level if available (lazy). | def level(self):
"""Extract log level if available (lazy)."""
if not self._level_calculated:
self._level_calculated = True
self._extract_level()
return self._level |
Extract level and component if available (lazy). | def _extract_level(self):
"""Extract level and component if available (lazy)."""
if self._level is None:
split_tokens = self.split_tokens
if not split_tokens:
self._level = False
self._component = False
return
x = (sel... |
Trigger extraction of all information.
These values are usually evaluated lazily. | def parse_all(self):
"""
Trigger extraction of all information.
These values are usually evaluated lazily.
"""
tokens = self.split_tokens
duration = self.duration
datetime = self.datetime
thread = self.thread
operation = self.operation
nam... |
Convert LogEvent object to a dictionary. | def to_dict(self, labels=None):
"""Convert LogEvent object to a dictionary."""
output = {}
if labels is None:
labels = ['line_str', 'split_tokens', 'datetime', 'operation',
'thread', 'namespace', 'nscanned', 'ntoreturn',
'nreturned', 'ninse... |
Convert LogEvent object to valid JSON. | def to_json(self, labels=None):
"""Convert LogEvent object to valid JSON."""
output = self.to_dict(labels)
return json.dumps(output, cls=DateTimeEncoder, ensure_ascii=False) |
Parse system.profile doc, copy all values to member variables. | def _parse_document(self):
"""Parse system.profile doc, copy all values to member variables."""
self._reset()
doc = self._profile_doc
self._split_tokens_calculated = True
self._split_tokens = None
self._duration_calculated = True
self._duration = doc[u'millis']... |
Run this section and print out information. | def run(self):
"""Run this section and print out information."""
grouping = Grouping(group_by=lambda x: (x.namespace, x.operation,
x.pattern))
logfile = self.mloginfo.logfile
if logfile.start and logfile.end:
progress_start = s... |
Return datetime from a given string. | def string2dt(self, s, lower_bound=None):
"""Return datetime from a given string."""
original_s = s
result = {}
dt = None
# if s is completely empty, return start or end,
# depending on what parameter is evaluated
if s == '':
return self.end if lower... |
Run this section and print out information. | def run(self):
"""Run this section and print out information."""
if ProfileCollection and isinstance(self.mloginfo.logfile,
ProfileCollection):
print("\n not available for system.profile collections\n")
return
for version, l... |
Add a filter class to the parser. | def addFilter(self, filterclass):
"""Add a filter class to the parser."""
if filterclass not in self.filters:
self.filters.append(filterclass) |
Print the final line.
Provides various options (length, human, datetime changes, ...). | def _outputLine(self, logevent, length=None, human=False):
"""
Print the final line.
Provides various options (length, human, datetime changes, ...).
"""
# adapt timezone output if necessary
if self.args['timestamp_format'] != 'none':
logevent._reformat_times... |
Change milliseconds to hours min sec ms format. | def _msToString(self, ms):
"""Change milliseconds to hours min sec ms format."""
hr, ms = divmod(ms, 3600000)
mins, ms = divmod(ms, 60000)
secs, mill = divmod(ms, 1000)
return "%ihr %imin %isecs %ims" % (hr, mins, secs, mill) |
Change the ms part in the string if needed. | def _changeMs(self, line):
"""Change the ms part in the string if needed."""
# use the position of the last space instead
try:
last_space_pos = line.rindex(' ')
except ValueError:
return line
else:
end_str = line[last_space_pos:]
ne... |
Format the numbers so that there are commas inserted.
For example: 1200300 becomes 1,200,300. | def _formatNumbers(self, line):
"""
Format the numbers so that there are commas inserted.
For example: 1200300 becomes 1,200,300.
"""
# below thousands separator syntax only works for
# python 2.7, skip for 2.6
if sys.version_info < (2, 7):
return lin... |
Helper method for ordering log lines correctly during merge. | def _datetime_key_for_merge(self, logevent):
"""Helper method for ordering log lines correctly during merge."""
if not logevent:
# if logfile end is reached, return max datetime to never
# pick this line
return datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzutc())
... |
Helper method to merge several files together by datetime. | def _merge_logfiles(self):
"""Helper method to merge several files together by datetime."""
# open files, read first lines, extract first dates
lines = [next(iter(logfile), None) for logfile in self.args['logfile']]
# adjust lines by timezone
for i in range(len(lines)):
... |
Yield each line of the file, or the next line if several files. | def logfile_generator(self):
"""Yield each line of the file, or the next line if several files."""
if not self.args['exclude']:
# ask all filters for a start_limit and fast-forward to the maximum
start_limits = [f.start_limit for f in self.filters
if h... |
Parse the logfile.
Ask each filter if it accepts the line. It will only be printed if all
filters accept the line. | def run(self, arguments=None):
"""
Parse the logfile.
Ask each filter if it accepts the line. It will only be printed if all
filters accept the line.
"""
# add arguments from filter classes before calling superclass run
for f in self.filters:
for fa i... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
if self.active and logevent.duration is not None:
return logevent.duration <= self.f... |
Create mask list.
Consists of all tuples between which this filter accepts lines. | def setup(self):
"""
Create mask list.
Consists of all tuples between which this filter accepts lines.
"""
# get start and end of the mask and set a start_limit
if not self.mask_source.start:
raise SystemExit("Can't parse format of %s. Is this a log file or "... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
dt = logevent.datetime
if not dt:
return False
mask = next((mask fo... |
Presplit chunks for sharding.
Get information about the number of shards, then split chunks and
distribute over shards. Currently assumes shardkey to be hex string, for
example ObjectId or UUID.
host: host and port to connect to, e.g. "192.168.0.1:27017",
"localhost:30000"
database: data... | def presplit(host, database, collection, shardkey, shardnumber=None,
chunkspershard=1, verbose=False):
"""
Presplit chunks for sharding.
Get information about the number of shards, then split chunks and
distribute over shards. Currently assumes shardkey to be hex string, for
example Ob... |
Find source files. | def source_files(mongodb_path):
"""Find source files."""
for root, dirs, files in os.walk(mongodb_path):
for filename in files:
# skip files in dbtests folder
if 'dbtests' in root:
continue
if filename.endswith(('.cpp', '.c', '.h')):
yi... |
Run this section and print out information. | def run(self):
"""Run this section and print out information."""
if ProfileCollection and isinstance(self.mloginfo.logfile,
ProfileCollection):
print("\n not available for system.profile collections\n")
return
ip_opened = de... |
Run this section and print out information. | def run(self):
"""Run this section and print out information."""
titles = ['date', 'host', 'state/message']
table_rows = []
for host, state, logevent in self.mloginfo.logfile.rs_state:
stats = OrderedDict()
stats['date'] = logevent.datetime.strftime("%b %d %H:%M:... |
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with result.show_result directly and are instead
dynamically generated through javascript for performance pur... | def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with result.show_result directly and are instead
dynamically generated through javas... |
Returns a fixed length identifier based on a hash of a combined set of
playbook/task values which are as close as we can guess to unique for each
task. | def generate_identifier(result):
"""
Returns a fixed length identifier based on a hash of a combined set of
playbook/task values which are as close as we can guess to unique for each
task.
"""
# Determine the playbook file path to use for the ID
if result.task.playbook and result.task.playbo... |
It turns out the built-in SQLAlchemy function for query.count() is pretty
slow. Alternatively, use this optimized function instead. | def fast_count(query):
"""
It turns out the built-in SQLAlchemy function for query.count() is pretty
slow. Alternatively, use this optimized function instead.
"""
count_query = (query
.statement.with_only_columns([func.count()]).order_by(None))
count = query.session.execute(co... |
Given a file path, returns a JSON structure suitable for bootstrap-treeview
mock_os represents a faked filesystem generated from the playbook_treeview
method.
Credit: Mohammed Naser & David Moreau Simard | def generate_tree(root, paths, mock_os):
"""
Given a file path, returns a JSON structure suitable for bootstrap-treeview
mock_os represents a faked filesystem generated from the playbook_treeview
method.
Credit: Mohammed Naser & David Moreau Simard
"""
tree = []
dentries = mock_os.listdi... |
Creates a fake filesystem with playbook files and uses generate_tree() to
recurse and return a JSON structure suitable for bootstrap-treeview. | def playbook_treeview(playbook):
"""
Creates a fake filesystem with playbook files and uses generate_tree() to
recurse and return a JSON structure suitable for bootstrap-treeview.
"""
fs = fake_filesystem.FakeFilesystem()
mock_os = fake_filesystem.FakeOsModule(fs)
files = models.File.query.... |
Used by the FileContent model to automatically compute the sha1
hash of content before storing it to the database. | def content_sha1(context):
"""
Used by the FileContent model to automatically compute the sha1
hash of content before storing it to the database.
"""
try:
content = context.current_parameters['content']
except AttributeError:
content = context
return hashlib.sha1(encodeutils.... |
Calculates '(time_end-time_start)' and return the resulting
'datetime.timedelta' object. | def duration(self):
"""
Calculates '(time_end-time_start)' and return the resulting
'datetime.timedelta' object.
"""
if self.time_end is None or self.time_start is None:
return timedelta(seconds=0)
else:
return self.time_end - self.time_start |
Returns the about page | def main():
""" Returns the about page """
files = models.File.query
hosts = models.Host.query
facts = models.HostFacts.query
playbooks = models.Playbook.query
records = models.Data.query
tasks = models.Task.query
results = models.TaskResult.query
if current_app.config['ARA_PLAYBOOK... |
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with host.show_host directly and are instead
dynamically generated through javascript for performance purpose... | def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with host.show_host directly and are instead
dynamically generated through javascrip... |
Wrapper around Ansible's get_config backward/forward compatibility | def ara_config(key, env_var, default, section='ara', value_type=None):
"""
Wrapper around Ansible's get_config backward/forward compatibility
"""
# Bootstrap Ansible configuration
# Ansible >=2.4 takes care of loading the configuration file itself
path = find_ini_config_file()
config = confi... |
Returns a dictionary for the loaded configuration | def config(self):
""" Returns a dictionary for the loaded configuration """
return {
key: self.__dict__[key]
for key in dir(self)
if key.isupper()
} |
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with file.show_file directly and are instead
dynamically generated through javascript for performance purpose... | def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with file.show_file directly and are instead
dynamically generated through javascrip... |
Returns details of a file | def show_file(file_):
"""
Returns details of a file
"""
file_ = (models.File.query.get(file_))
if file_ is None:
abort(404)
return render_template('file.html', file_=file_) |
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revision which contains the latest stat... | def configure_db(app):
"""
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revi... |
Sets up an attribute to cache data in the app context | def configure_cache(app):
""" Sets up an attribute to cache data in the app context """
log = logging.getLogger('ara.webapp.configure_cache')
log.debug('Configuring cache')
if not getattr(app, '_cache', None):
app._cache = {} |
Converts non-rational parametric shapes to rational ones.
:param obj: B-Spline shape
:type obj: BSpline.Curve, BSpline.Surface or BSpline.Volume
:return: NURBS shape
:rtype: NURBS.Curve, NURBS.Surface or NURBS.Volume
:raises: TypeError | def bspline_to_nurbs(obj):
""" Converts non-rational parametric shapes to rational ones.
:param obj: B-Spline shape
:type obj: BSpline.Curve, BSpline.Surface or BSpline.Volume
:return: NURBS shape
:rtype: NURBS.Curve, NURBS.Surface or NURBS.Volume
:raises: TypeError
"""
# B-Spline -> NU... |
Extracts the non-rational components from rational parametric shapes, if possible.
The possibility of converting a rational shape to a non-rational one depends on the weights vector.
:param obj: NURBS shape
:type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume
:return: B-Spline shape
:rtype: BSpli... | def nurbs_to_bspline(obj, **kwargs):
""" Extracts the non-rational components from rational parametric shapes, if possible.
The possibility of converting a rational shape to a non-rational one depends on the weights vector.
:param obj: NURBS shape
:type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume
... |
Doolittle's Method for LU-factorization.
:param matrix_a: Input matrix (must be a square matrix)
:type matrix_a: list, tuple
:return: a tuple containing matrices (L,U)
:rtype: tuple | def doolittle(matrix_a):
""" Doolittle's Method for LU-factorization.
:param matrix_a: Input matrix (must be a square matrix)
:type matrix_a: list, tuple
:return: a tuple containing matrices (L,U)
:rtype: tuple
"""
# Initialize L and U matrices
matrix_u = [[0.0 for _ in range(len(matrix... |
Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) | def pool_context(*args, **kwargs):
""" Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) """
pool = Pool(*args, **kwargs)
try:
yield pool
except Exception as e:
raise e
finally:
pool.terminate() |
Export decorator
Please refer to the following SO article for details: https://stackoverflow.com/a/35710527 | def export(fn):
""" Export decorator
Please refer to the following SO article for details: https://stackoverflow.com/a/35710527
"""
mod = sys.modules[fn.__module__]
if hasattr(mod, '__all__'):
mod.__all__.append(fn.__name__)
else:
mod.__all__ = [fn.__name__]
return fn |
Reads files inside the input project directory. | def read_files(project, ext):
""" Reads files inside the input project directory. """
project_path = os.path.join(os.path.dirname(__file__), project)
file_list = os.listdir(project_path)
flist = []
flist_path = []
for f in file_list:
f_path = os.path.join(project_path, f)
if os.p... |
Copies files with extensions "ext" from "src" to "dst" directory. | def copy_files(src, ext, dst):
""" Copies files with extensions "ext" from "src" to "dst" directory. """
src_path = os.path.join(os.path.dirname(__file__), src)
dst_path = os.path.join(os.path.dirname(__file__), dst)
file_list = os.listdir(src_path)
for f in file_list:
if f == '__init__.py'... |
Creates the project directory for compiled modules. | def make_dir(project):
""" Creates the project directory for compiled modules. """
project_path = os.path.join(os.path.dirname(__file__), project)
# Delete the directory and the files inside it
if os.path.exists(project_path):
shutil.rmtree(project_path)
# Create the directory
os.mkdir(p... |
Checks if any of the elements of the input list is in sys.argv array. | def in_argv(arg_list):
""" Checks if any of the elements of the input list is in sys.argv array. """
for arg in sys.argv:
for parg in arg_list:
if parg == arg or arg.startswith(parg):
return True
return False |
Generates an equally spaced knot vector.
It uses the following equality to generate knot vector: :math:`m = n + p + 1`
where;
* :math:`p`, degree
* :math:`n + 1`, number of control points
* :math:`m + 1`, number of knots
Keyword Arguments:
* ``clamped``: Flag to choose from clamped ... | def generate(degree, num_ctrlpts, **kwargs):
""" Generates an equally spaced knot vector.
It uses the following equality to generate knot vector: :math:`m = n + p + 1`
where;
* :math:`p`, degree
* :math:`n + 1`, number of control points
* :math:`m + 1`, number of knots
Keyword Arguments:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.