code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# First the 'general' project
self.sec_project_activity(self.GLOBAL_PROJECT)
self.sec_project_community(self.GLOBAL_PROJECT)
self.sec_project_process(self.GLOBAL_PROJECT)
if not self.projects:
# Don't generate per project data
return
... | def sec_projects(self) | Generate the report projects related sections: the general project is included always and add
to the global report, and an specific report for each project is generated if configured.
:return: | 5.3707 | 5.134418 | 1.046019 |
secs = OrderedDict()
secs['Overview'] = self.sec_overview
secs['Communication Channels'] = self.sec_com_channels
secs['Detailed Activity by Project'] = self.sec_projects
return secs | def sections(self) | Get the sections of the report and howto build them.
:return: a dict with the method to be called to fill each section of the report | 9.843314 | 9.767202 | 1.007793 |
logger.info("Generating the report data and figs from %s to %s",
self.start, self.end)
for section in self.sections():
logger.info("Generating %s", section)
self.sections()[section]()
logger.info("Data and figs done") | def create_data_figs(self) | Generate the data and figs files for the report
:return: | 5.898103 | 5.28793 | 1.11539 |
if interval not in ['quarter']:
raise RuntimeError("Interval not support in build_period_name", interval)
name = pdate.strftime('%Y-%m-%d') + ' ' + interval
months_in_quarter = 3
end_quarter_month = None
if interval == 'quarter':
if offset:
... | def build_period_name(cls, pdate, interval='quarter', offset=None, start_date=False) | Build the period name for humans (eg, 18-Q2) to be used in the reports.
Just supporting quarters right now.
The name is built using the last month for the quarter.
:param pdate: the date (datetime) which defines the period
:param interval: the time interval (string) used in the report
... | 3.355924 | 3.334837 | 1.006323 |
with open(filepath) as file:
s = file.read()
s = s.replace(to_replace, replacement)
with open(filepath, 'w') as file:
file.write(s) | def replace_text(filepath, to_replace, replacement) | Replaces a string in a given file with another string
:param file: the file in which the string has to be replaced
:param to_replace: the string to be replaced in the file
:param replacement: the string which replaces 'to_replace' in the file | 1.87574 | 2.748034 | 0.682575 |
if not file_type:
file_type = "*.tex"
for file in glob.iglob(os.path.join(directory, file_type)):
self.replace_text(file, to_replace, replacement) | def replace_text_dir(self, directory, to_replace, replacement, file_type=None) | Replaces a string with its replacement in all the files in the directory
:param directory: the directory in which the files have to be modified
:param to_replace: the string to be replaced in the files
:param replacement: the string which replaces 'to_replace' in the files
:param file_t... | 2.353522 | 3.030637 | 0.776577 |
logger.info("Generating the report from %s to %s", self.start, self.end)
self.create_data_figs()
self.create_pdf()
logger.info("Report completed") | def create(self) | Generate the data and figs for the report and fill the LaTeX templates with them
to generate a PDF file with the report.
:return: | 7.004978 | 5.342761 | 1.311116 |
# for each user, check if they have files available
# return user name list
total_list = []
name_list = []
get_sub = False
for path, subdir, dir_files in os.walk(file_dir):
if not get_sub:
total_list = subdir[:]
get_sub = True
else:
break
... | def get_names(file_dir, files) | Get the annotator name list based on a list of files
Args:
file_dir: AMR file folder
files: a list of AMR names, e.g. nw_wsj_0001_1
Returns:
a list of user names who annotate all the files | 3.678164 | 3.59328 | 1.023623 |
match_total = 0
test_total = 0
gold_total = 0
for fi in file_list:
file1 = dir_pre + user1 + "/" + fi + ".txt"
file2 = dir_pre + user2 + "/" + fi + ".txt"
if not os.path.exists(file1):
print("*********Error: ", file1, "does not exist*********", file=ERROR_LOG)
... | def compute_files(user1, user2, file_list, dir_pre, start_num) | Compute the smatch scores for a file list between two users
Args:
user1: user 1 name
user2: user 2 name
file_list: file list
dir_pre: the file location prefix
start_num: the number of restarts in smatch
Returns:
smatch f score. | 1.761727 | 1.732975 | 1.016591 |
col_paddings = []
for i in range(len(table[0])):
col_paddings.append(get_max_width(table,i))
for row in table:
print(row[0].ljust(col_paddings[0] + 1), end="")
for i in range(1, len(row)):
col = str(row[i]).rjust(col_paddings[i]+2)
print(col, end='')
... | def pprint_table(table) | Print a table in pretty format | 2.219946 | 2.174542 | 1.02088 |
parser = argparse.ArgumentParser(description="Smatch table calculator -- arguments")
parser.add_argument("--fl", type=argparse.FileType('r'), help='AMR ID list file')
parser.add_argument('-f', nargs='+', help='AMR IDs (at least one)')
parser.add_argument("-p", nargs='*', help="User list (can be non... | def build_arg_parser() | Build an argument parser using argparse. Use it when python version is 2.7 or later. | 6.544081 | 6.369625 | 1.027389 |
usage_str = "Smatch table calculator -- arguments"
parser = optparse.OptionParser(usage=usage_str)
parser.add_option("--fl", dest="fl", type="string", help='AMR ID list file')
parser.add_option("-f", dest="f", type="string", action="callback", callback=cb, help="AMR IDs (at least one)")
parser.... | def build_arg_parser2() | Build an argument parser using optparse. Use it when python version is 2.5 or 2.6. | 4.203671 | 4.07188 | 1.032366 |
arguments = [value]
for arg in parser.rargs:
if arg[0] != "-":
arguments.append(arg)
else:
del parser.rargs[:len(arguments)]
break
if getattr(parser.values, option.dest):
arguments.extend(getattr(parser.values, option.dest))
setattr(parser... | def cb(option, value, parser) | Callback function to handle variable number of arguments in optparse | 2.13693 | 2.205242 | 0.969023 |
if not os.path.exists(args.fd):
print("Not a valid path", args.fd, file=ERROR_LOG)
return [], [], False
if args.fl is not None:
# we already ensure the file can be opened and opened the file
file_line = args.fl.readline()
amr_ids = file_line.strip().split()
elif ... | def check_args(args) | Parse arguments and check if the arguments are valid | 3.16655 | 3.128285 | 1.012232 |
with open(filename, mode) as f:
csv_data.replace("_", r"\_")
f.write(csv_data) | def create_csv(filename, csv_data, mode="w") | Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file. It can
be 'w', 'a', etc. Default is 'w' | 4.168075 | 5.422725 | 0.768631 |
if data_source in self.index_dict:
index = self.index_dict[data_source]
else:
index = self.class2index[self.ds2class[data_source]]
return Index(index_name=index) | def get_metric_index(self, data_source) | This function will return the elasticsearch index for a corresponding
data source. It chooses in between the default and the user inputed
es indices and returns the user inputed one if it is available.
:param data_source: the data source for which the index has to be returned
:returns: ... | 4.463762 | 4.255961 | 1.048826 |
logger.debug("Calculating Overview metrics.")
data_path = os.path.join(self.data_dir, "overview")
if not os.path.exists(data_path):
os.makedirs(data_path)
overview_config = {
"activity_metrics": [],
"author_metrics": [],
"bmi_me... | def get_sec_overview(self) | Generate the "overview" section of the report. | 3.704346 | 3.646727 | 1.0158 |
logger.debug("Calculating Project Activity metrics.")
data_path = os.path.join(self.data_dir, "activity")
if not os.path.exists(data_path):
os.makedirs(data_path)
for ds in self.data_sources:
metric_file = self.ds2class[ds]
metric_index = s... | def get_sec_project_activity(self) | Generate the "project activity" section of the report. | 3.7119 | 3.607179 | 1.029031 |
logger.debug("Calculating Project Community metrics.")
data_path = os.path.join(self.data_dir, "community")
if not os.path.exists(data_path):
os.makedirs(data_path)
project_community_config = {
"author_metrics": [],
"people_top_metrics": []... | def get_sec_project_community(self) | Generate the "project community" section of the report. | 2.816135 | 2.746957 | 1.025184 |
if not data_frames:
logger.error("No dataframes provided to create CSV")
sys.exit(1)
assert(len(data_frames) == len(headers))
dataframes = []
for index, df in enumerate(data_frames):
df = df.rename(columns={"value": headers[index].replace("_... | def create_csv_fig_from_df(self, data_frames=[], filename=None, headers=[], index_label=None,
fig_type=None, title=None, xlabel=None, ylabel=None, xfont=10,
yfont=10, titlefont=15, fig_size=(8, 10), image_type="eps") | Joins all the datafarames horizontally and creates a CSV and an image file from
those dataframes.
:param data_frames: a list of dataframes containing timeseries data from various metrics
:param filename: the name of the csv and image file
:param headers: a list of headers to be applied ... | 2.534731 | 2.527308 | 1.002937 |
logger.info("Generating the report data and figs from %s to %s",
self.start_date, self.end_date)
self.get_sec_overview()
self.get_sec_project_activity()
self.get_sec_project_community()
self.get_sec_project_process()
logger.info("Data and f... | def create_data_figs(self) | Generate the data and figs files for the report
:return: | 5.596353 | 5.125398 | 1.091886 |
logger.info("Generating the report from %s to %s", self.start_date, self.end_date)
self.create_data_figs()
self.create_pdf()
logger.info("Report completed") | def create(self) | Generate the data and figs for the report and fill the LaTeX templates with them
to generate a PDF file with the report.
:return: | 5.905649 | 4.63933 | 1.272953 |
tmp = self.get_var(name).copy()
# sometimes we want to slice in 1 dimension, sometimes in more
# always slice in arrays
start = np.atleast_1d(start)
count = np.atleast_1d(count)
slices = [np.s_[i:(i+n)] for i,n in zip(start, count)]
tmp[slices] = var
... | def set_var_slice(self, name, start, count, var) | Overwrite the values in variable name with data
from var, in the range (start:start+count).
Start, count can be integers for rank 1, and can be
tuples of integers for higher ranks.
For some implementations it can be equivalent and more efficient to do:
`get_var(name)[start[0]:sta... | 3.602309 | 3.309176 | 1.088582 |
tmp = self.get_var(name).copy()
tmp.flat[index] = var
self.set_var(name, tmp) | def set_var_index(self, name, index, var) | Overwrite the values in variable "name" with data
from var, at the flattened (C-contiguous style)
indices. Indices is a vector of 0-based
integers, of the same length as the vector var.
For some implementations it can be equivalent
and more efficient to do:
`get_var(name)... | 3.508816 | 2.302538 | 1.52389 |
'''Create all tables in the given database'''
logging.getLogger(__name__).debug("Creating missing database tables")
database.connect()
database.create_tables([User,
Group,
UserToGroup,
GroupToCapability,
... | def create_tables(database) | Create all tables in the given database | 5.998267 | 6.215022 | 0.965124 |
'''Create user admin and grant him all permission
If the admin user already exists the function will simply return
'''
logging.getLogger(__name__).debug("Populating with default users")
if not User.select().where(User.name == 'admin').exists():
admin = User.create(name='admin', password='ad... | def populate_with_defaults() | Create user admin and grant him all permission
If the admin user already exists the function will simply return | 3.904998 | 3.326628 | 1.173861 |
'''Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy`
'''
if not dbURL:
dbURL = 'sqlite:///:memory:'
logging.getLogger(__name__).debug("Initializing database: {}".format... | def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None) | Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy` | 4.337999 | 2.797618 | 1.550605 |
whitelist = (' -' + string.ascii_letters + string.digits)
if type(s) == six.binary_type:
s = six.text_type(s, 'utf-8', 'ignore')
table = {}
for ch in [ch for ch in s if ch not in whitelist]:
if ch not in table:
try:
replacement = unicodedata.normalize('... | def normalize(s, replace_spaces=True) | Normalize non-ascii characters to their closest ascii counterparts | 2.693367 | 2.699813 | 0.997613 |
prefix = 'ROBOT_'
variables = []
def safe_str(s):
if isinstance(s, six.text_type):
return s
else:
return six.text_type(s, 'utf-8', 'ignore')
for key in os.environ:
if key.startswith(prefix) and len(key) > len(prefix):
variables.append(saf... | def get_robot_variables() | Return list of Robot Framework -compatible cli-variables parsed
from ROBOT_-prefixed environment variable | 2.591908 | 2.365254 | 1.095827 |
logger.debug('Configuring ' + hex(self.get_address())
+ ' ch: ' + str(self.get_channel())
+ ' res: ' + str(self.get_resolution())
+ ' gain: ' + str(self.get_gain()))
self.bus.write_byte(self.address, self.config) | def configure(self) | Configure the device.
Send the device configuration saved inside the MCP342x object to the target device. | 3.74545 | 3.413052 | 1.09739 |
c = self.config
c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot
c |= MCP342x._not_ready_mask # Convert
logger.debug('Convert ' + hex(self.address) + ' config: ' + bin(c))
self.bus.write_byte(self.address, c) | def convert(self) | Initiate one-shot conversion.
The current settings are used, with the exception of continuous mode. | 8.145382 | 6.397293 | 1.273254 |
es = Elasticsearch(elastic_url)
search = Search(using=es, index=index)
agg = A("min", field="grimoire_creation_date")
search.aggs.bucket("1", agg)
search = search.extra(size=0)
response = search.execute()
start_date = response.to_dict()['aggregations']['1']['value_as_string'][:10]
r... | def get_first_date_of_index(elastic_url, index) | Get the first/min date present in the index | 2.968016 | 2.815109 | 1.054317 |
query_filters = []
for name in filters:
if name[0] == '*' and not inverse:
# An inverse filter and not inverse mode
continue
if name[0] != '*' and inverse:
# A direct filter and inverse mode
continue
... | def __get_query_filters(cls, filters={}, inverse=False) | Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filters to be applied
:param inverse: if True include all the inverse filt... | 5.41285 | 4.415394 | 1.225904 |
if not start and not end:
return ''
start_end = {}
if start:
start_end["gte"] = "%s" % start.isoformat()
if end:
start_end["lte"] = "%s" % end.isoformat()
query_range = {date_field: start_end}
return query_range | def __get_query_range(cls, date_field, start=None, end=None) | Create a filter dict with date_field from start to end dates.
:param date_field: field with the date value
:param start: date with the from value. Should be a datetime.datetime object
of the form: datetime.datetime(2018, 5, 25, 15, 17, 39)
:param end: date with the to valu... | 2.355767 | 2.54685 | 0.924973 |
query_basic = Search()
query_filters = cls.__get_query_filters(filters)
for f in query_filters:
query_basic = query_basic.query(f)
query_filters_inverse = cls.__get_query_filters(filters, inverse=True)
# Here, don't forget the '~'. That is what makes this a... | def __get_query_basic(cls, date_field=None, start=None, end=None,
filters={}) | Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime object
:param end: date with the to value, should be a datetime.datetime object
:param filters: dict with the ... | 3.007124 | 3.053761 | 0.984728 |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("terms", field=field, size=cls.AGG_SIZE, order={"_count": "desc"})
return (agg_id, query_agg) | def __get_query_agg_terms(cls, field, agg_id=None) | Create a es_dsl aggregation object based on a term.
:param field: field to be used to aggregate
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"terms": {
"field": <field>,
"size:": <size>,... | 3.29013 | 2.909323 | 1.130892 |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("max", field=field)
return (agg_id, query_agg) | def __get_query_agg_max(cls, field, agg_id=None) | Create an es_dsl aggregation object for getting the max value of a field.
:param field: field from which the get the max value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"max": {
"field": <field>
... | 4.014676 | 4.007885 | 1.001695 |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("percentiles", field=field)
return (agg_id, query_agg) | def __get_query_agg_percentiles(cls, field, agg_id=None) | Create an es_dsl aggregation object for getting the percentiles value of a field.
In general this is used to get the median (0.5) percentile.
:param field: field from which the get the percentiles values
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
... | 4.061584 | 4.081306 | 0.995168 |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("avg", field=field)
return (agg_id, query_agg) | def __get_query_agg_avg(cls, field, agg_id=None) | Create an es_dsl aggregation object for getting the average value of a field.
:param field: field from which the get the average value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"avg": {
"field": <field>
... | 4.052525 | 4.02756 | 1.006198 |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("cardinality", field=field, precision_threshold=cls.ES_PRECISION)
return (agg_id, query_agg) | def __get_query_agg_cardinality(cls, field, agg_id=None) | Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"cardinality": {
... | 4.292956 | 3.797986 | 1.130324 |
bounds = {}
if start or end:
# Extend bounds so we have data until start and end
start_ts = None
end_ts = None
if start:
# elasticsearch is unable to convert date with microseconds into long
# format for processing,... | def __get_bounds(cls, start=None, end=None) | Return a dict with the bounds for a date_histogram agg.
:param start: date from for the date_histogram agg, should be a datetime.datetime object
:param end: date to for the date_histogram agg, should be a datetime.datetime object
:return: a dict with the DSL bounds for a date_histogram aggregat... | 3.133646 | 3.296288 | 0.950659 |
if not interval:
interval = '1M'
if not time_zone:
time_zone = 'UTC'
if not field:
field_agg = ''
else:
if agg_type == "cardinality":
agg_id, field_agg = cls.__get_query_agg_cardinality(field, agg_id=cls.A... | def __get_query_agg_ts(cls, field, time_field, interval=None,
time_zone=None, start=None, end=None,
agg_type='count', offset=None) | Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field to get the time series values
:param time_field: field with the date
:param interval: interval to be used to generate the time series values, such as:(year(y),
quarte... | 3.085309 | 3.00172 | 1.027847 |
query_basic = cls.__get_query_basic(date_field=date_field,
start=start, end=end,
filters=filters)
# size=0 gives only the count and not the hits
query = query_basic.extra(size=0)
ret... | def get_count(cls, date_field=None, start=None, end=None, filters={}) | Build the DSL query for counting the number of items.
:param date_field: field with the date
:param start: date from which to start counting, should be a datetime.datetime object
:param end: date until which to count items, should be a datetime.datetime object
:param filters: dict with ... | 5.58684 | 5.430628 | 1.028765 |
# This gives us the basic structure of the query, including:
# Normal and inverse filters and range.
s = cls.__get_query_basic(date_field=date_field, start=start, end=end, filters=filters)
# Get only the aggs not the hits
# Default count starts from 0
s = s.extr... | def get_agg(cls, field=None, date_field=None, start=None, end=None,
filters={}, agg_type="terms", offset=None, interval=None) | Compute the aggregated value for a field.
:param field: field to get the time series values
:param date_field: field with the date
:param interval: interval to be used to generate the time series values, such as:(year(y),
quarter(q), month(M), week(w), day(d), hour(h), m... | 2.566608 | 2.612267 | 0.982521 |
if fields_arg is None:
return None
if isinstance(fields_arg, dict):
return tuple(sorted([k for k in list(fields_arg.keys()) if fields_arg[k]]))
else:
return tuple(sorted(fields_arg)) | def _flatten_fetched_fields(fields_arg) | this method takes either a kwargs 'fields', which can be a dict :
{"_id": False, "store": 1, "url": 1} or a list : ["store", "flag", "url"]
and returns a tuple : ("store", "flag").
it HAS to be a tuple, so that it is not updated by the different instances | 2.322709 | 2.119204 | 1.096029 |
# We fetched with fields=None, we should have fetched them all
if self._fetched_fields is None or self._initialized_with_doc:
return
if force_refetch:
missing_fields = fields
else:
missing_fields = [f for f in fields if f not in self._fetche... | def ensure_fields(self, fields, force_refetch=False) | Makes sure we fetched the fields, and populate them if not. | 4.150445 | 4.083437 | 1.01641 |
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
for k, v in db_fields.items():
self[k] = v | def refetch_fields(self, missing_fields) | Refetches a list of fields from the DB | 4.207765 | 4.322734 | 0.973404 |
self.mongokat_collection.update_one({"_id": self["_id"]}, {"$unset": {
f: 1 for f in fields
}})
for f in fields:
if f in self:
del self[f] | def unset_fields(self, fields) | Removes this list of fields from both the local object and the DB. | 4.292861 | 3.952649 | 1.086072 |
old_doc = self.mongokat_collection.find_one({"_id": self['_id']}, read_use="primary")
if not old_doc:
raise OperationFailure('Can not reload an unsaved document.'
' %s is not found in the database. Maybe _id was a string and not ObjectId?' % self... | def reload(self) | allow to refresh the document, so after using update(), it could reload
its value from the database.
Be carreful : reload() will erase all unsaved values.
If no _id is set in the document, a KeyError is raised. | 8.822001 | 7.539211 | 1.170149 |
if not self._initialized_with_doc and not force:
raise Exception("Cannot save a document not initialized from a Python dict. This might remove fields from the DB!")
self._initialized_with_doc = False
if '_id' not in self:
if uuid:
self['_id'] =... | def save(self, force=False, uuid=False, **kwargs) | REPLACES the object in DB. This is forbidden with objects from find() methods unless force=True is given. | 6.149656 | 5.697234 | 1.079411 |
# Backwards compat, deprecated argument
if "dotnotation" in kwargs:
del kwargs["dotnotation"]
if data is None:
data = dotdict(self)
if "_id" not in data:
raise KeyError("_id must be set in order to do a save_partial()")
... | def save_partial(self, data=None, allow_protected_fields=False, **kwargs) | Saves just the currently set fields in the database. | 4.666843 | 4.600485 | 1.014424 |
global opinel_arg_dir
profile_name = 'default'
# h4ck to have an early read of the profile name
for i, arg in enumerate(sys.argv):
if arg == '--profile' and len(sys.argv) >= i + 1:
profile_name = sys.argv[i + 1]
#if not os.path.isdir(opinel_arg_dir):
# os.makedir... | def read_default_args(tool_name) | Read default argument values for a given tool
:param tool_name: Name of the script to read the default arguments for
:return: Dictionary of default arguments (shared + tool-specific) | 3.040211 | 3.115774 | 0.975748 |
if test_input != None:
if type(test_input) == list and len(test_input):
choice = test_input.pop(0)
elif type(test_input) == list:
choice = ''
else:
choice = test_input
else:
# Coverage: 4 missed statements
try:
choice =... | def prompt(test_input = None) | Prompt function that works for Python2 and Python3
:param test_input: Value to be returned when testing
:return: Value typed by user (or passed in argument when testing) | 3.53389 | 3.922501 | 0.900928 |
while True:
if activate:
prompt_string = 'Enter the next value: '
else:
prompt_string = 'Enter your MFA code (or \'q\' to abort): '
mfa_code = prompt_4_value(prompt_string, no_confirm = True, input = input)
try:
if mfa_code == 'q':
... | def prompt_4_mfa_code(activate = False, input = None) | Prompt for an MFA code
:param activate: Set to true when prompting for the 2nd code when activating a new MFA device
:param input: Used for unit testing
:return: The MFA code | 3.876443 | 4.206437 | 0.92155 |
return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, regex_format = mfa_serial_format, input = input) | def prompt_4_mfa_serial(input = None) | Prompt for an MFA serial number
:param input: Used for unit testing
:return: The MFA serial number | 6.85815 | 8.402316 | 0.816221 |
if not os.path.exists(filename) or force_write:
return True
return prompt_4_yes_no('File \'{}\' already exists. Do you want to overwrite it'.format(filename), input = input) | def prompt_4_overwrite(filename, force_write, input = None) | Prompt whether the file should be overwritten
:param filename: Name of the file about to be written
:param force_write: Skip confirmation prompt if this flag is set
:param input: Used for unit testing
:return: Boolean ... | 3.146046 | 4.408988 | 0.713553 |
if choices and display_choices and not display_indices:
question = question + ' (' + '/'.join(choices) + ')'
lap_n = 0
while True:
if lap_n >= max_laps:
printError('Automatically abording prompt loop after 5 failures')
return None
lap_n += 1
can_r... | def prompt_4_value(question, choices = None, default = None, display_choices = True, display_indices = False, authorize_list = False, is_question = False, no_confirm = False, required = True, regex = None, regex_format = '', max_laps = 5, input = None, return_index = False) | Prompt for a value
. .
:param question: Question to be asked
:param choices: List of authorized answers
:param default: Value suggested by default
:param display_choices: Dis... | 3.7138 | 3.804028 | 0.976281 |
count = 0
while True:
printError(question + ' (y/n)? ')
choice = prompt(input).lower()
if choice == 'yes' or choice == 'y':
return True
elif choice == 'no' or choice == 'n':
return False
else:
count += 1
printError('\'%... | def prompt_4_yes_no(question, input = None) | Prompt for a yes/no or y/n answer
.
:param question: Question to be asked
:param input: Used for unit testing
:return: True for yes/y, False for no/n | 2.65922 | 2.679472 | 0.992442 |
if path is None:
return default
dot = path.rindex('.')
module_name = path[:dot]
class_name = path[dot + 1:]
try:
_class = getattr(import_module(module_name), class_name)
return _class
except (ImportError, AttributeError) as e:
raise FeedparserError("{}: ... | def safe_import_module(path, default=None) | Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if import fails, it can be None, a callable or whatever you need.
Return a object or None | 2.929039 | 3.160906 | 0.926645 |
if name not in engines:
raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(name))
renderer = safe_import_module(engines[name])
return renderer | def get_feed_renderer(engines, name) | From engine name, load the engine path and return the renderer class
Raise 'FeedparserError' if any loading error | 6.777935 | 5.083056 | 1.333437 |
''' Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
Cursor positi... | def clear_line(mode=2) | Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
Cursor position does ... | 6.301568 | 2.417483 | 2.606665 |
''' Clear the terminal/console screen. (Also aliased to clear.)
Arguments:
mode: | 0 | 'forward' - Clear cursor to end of screen, cursor stays.
| 1 | 'backward' - Clear cursor to beginning of screen, ""
| 2 | 'full' - Clear entire visible screen, ... | def clear_screen(mode=2) | Clear the terminal/console screen. (Also aliased to clear.)
Arguments:
mode: | 0 | 'forward' - Clear cursor to end of screen, cursor stays.
| 1 | 'backward' - Clear cursor to beginning of screen, ""
| 2 | 'full' - Clear entire visible screen, cursor t... | 9.835022 | 2.132235 | 4.612542 |
''' Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals.
'''
if os.name == 'nt':
from .windows import cls
cls()
else:
text = sc.reset
_wr... | def reset_terminal() | Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals. | 17.518822 | 3.711164 | 4.720573 |
''' Set the title of the terminal window/tab/icon.
Arguments:
title: str
mode: | 0 | 'both' - Set icon/taskbar and window/tab title
| 1 | 'icon' - Set only icon/taskbar title
| 2 | 'title' - Set only window/tab title
'''
if os.nam... | def set_title(title, mode=0) | Set the title of the terminal window/tab/icon.
Arguments:
title: str
mode: | 0 | 'both' - Set icon/taskbar and window/tab title
| 1 | 'icon' - Set only icon/taskbar title
| 2 | 'title' - Set only window/tab title | 6.285393 | 3.206949 | 1.959929 |
''' Strip ANSI escape sequences from a portion of text.
https://stackoverflow.com/a/38662876/450917
Arguments:
line: str
osc: bool - include OSC commands in the strippage.
c1: bool - include C1 commands in the strippage.
Notes:
Enabling c1... | def strip_ansi(text, c1=False, osc=False) | Strip ANSI escape sequences from a portion of text.
https://stackoverflow.com/a/38662876/450917
Arguments:
line: str
osc: bool - include OSC commands in the strippage.
c1: bool - include C1 commands in the strippage.
Notes:
Enabling c1 and osc... | 7.741964 | 1.95946 | 3.951071 |
''' Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None - immediately under i/o ... | def wait_key(keys=None) | Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None - immediately under i/o redirect... | 7.943342 | 1.781566 | 4.45863 |
''' Analogous to the ancient
`DOS pause <https://en.wikipedia.org/wiki/List_of_DOS_commands#PAUSE>`_
command, with a modifiable message.
Arguments:
message: str
Returns:
str, None: One character or ESC - depending on key hit.
None - immediately... | def pause(message='Press any key to continue…') | Analogous to the ancient
`DOS pause <https://en.wikipedia.org/wiki/List_of_DOS_commands#PAUSE>`_
command, with a modifiable message.
Arguments:
message: str
Returns:
str, None: One character or ESC - depending on key hit.
None - immediately under i... | 13.791172 | 2.607092 | 5.289868 |
root = etree.Element('query', nsmap={None: 'http://basex.org/rest'})
text = etree.SubElement(root, 'text')
text.text = etree.CDATA(query.strip())
return root | def build_query_fragment(query) | <query xmlns="http://basex.org/rest">
<text><![CDATA[ (//city/name)[position() <= 5] ]]></text>
</query> | 4.12715 | 2.467609 | 1.67253 |
renderer_name = kwargs.get('renderer', settings.FEED_DEFAULT_RENDERER_ENGINE)
renderer_template = kwargs.get('template', None)
expiration = kwargs.get('expiration', 0)
renderer = get_feed_renderer(settings.FEED_RENDER_ENGINES, renderer_name)
return renderer().render(url, template=renderer_... | def feedparser_render(url, *args, **kwargs) | Render a feed and return its builded html
Usage: ::
{% feedparser_render 'http://localhost/sample.xml' %}
Or with all accepted arguments: ::
{% feedparser_render 'http://localhost/sample.xml' renderer='CustomRenderer' template='foo/custom.html' expiration=3600 %} | 3.899057 | 3.754879 | 1.038397 |
service = 'ec2containerservice' if service == 'ecs' else service # Of course things aren't that easy...
# Get list of regions from botocore
regions = Session().get_available_regions(service, partition_name = partition_name)
if len(chosen_regions):
return list((Counter(regions) & Counter(cho... | def build_region_list(service, chosen_regions = [], partition_name = 'aws') | Build the list of target region names
:param service:
:param chosen_regions:
:param partition_name:
:return: | 5.951263 | 7.177762 | 0.829125 |
api_client = None
try:
client_params = {}
client_params['service_name'] = service.lower()
session_params = {}
session_params['aws_access_key_id'] = credentials['AccessKeyId']
session_params['aws_secret_access_key'] = credentials['SecretAccessKey']
session_par... | def connect_service(service, credentials, region_name = None, config = None, silent = False) | Instantiates an AWS API client
:param service:
:param credentials:
:param region_name:
:param config:
:param silent:
:return: | 1.807467 | 1.880361 | 0.961234 |
results = {}
for entity in entities:
results[entity] = []
while True:
try:
marker_found = False
response = callback(**params)
for entity in entities:
if entity in response:
results[entity] = results[entity] + respon... | def handle_truncated_response(callback, params, entities) | Handle truncated responses
:param callback:
:param params:
:param entities:
:return: | 2.358624 | 2.459128 | 0.95913 |
resolution = meta.get('resolution', 300)
width = meta.get('width', 1080)
bgcolor = Color(meta.get('bgcolor', 'white'))
stream = BytesIO()
with Image(blob=filehandle.stream, resolution=resolution) as img:
img.background_color = bgcolor
img.alpha_channel = False
img.forma... | def pdftojpg(filehandle, meta) | Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of the image for resizing, defaults to 1080
... | 2.481867 | 2.293628 | 1.082071 |
filename = secure_filename(meta.get('filename', filehandle.filename))
basename, _ = os.path.splitext(filename)
meta['original_filename'] = filehandle.filename
filehandle.filename = filename + '.jpg'
return filehandle | def change_filename(filehandle, meta) | Changes the filename to reflect the conversion from PDF to JPG.
This method will preserve the original filename in the meta dictionary. | 3.260161 | 3.063677 | 1.064134 |
if meta.get('avoid_name_collision', True):
filename = filehandle.filename
original, ext = os.path.splitext(filehandle.filename)
counter = count()
while os.path.exists(get_save_path(filename)):
fixer = str(next(counter))
filename = '{}_{}{}'.format(origina... | def avoid_name_collisions(filehandle, meta) | Manipulates a filename until it's unique. This can be disabled by
setting meta['avoid_name_collision'] to any falsey value. | 3.166391 | 2.927095 | 1.081752 |
"Uses werkzeug.FileStorage instance to save the converted image."
fullpath = get_save_path(filehandle.filename)
filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)) | def pdf_saver(filehandle, *args, **kwargs) | Uses werkzeug.FileStorage instance to save the converted image. | 6.401444 | 3.901897 | 1.640598 |
if local_file:
if data_file.startswith('/'):
src_file = data_file
else:
src_dir = os.getcwd()
src_file = os.path.join(src_dir, data_file)
else:
src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
if not os.path.isdi... | def load_data(data_file, key_name = None, local_file = False, format = 'json') | Load a JSON data file
:param data_file:
:param key_name:
:param local_file:
:return: | 1.891702 | 1.970809 | 0.959861 |
targets = []
data = load_data(filename, local_file = local_file)
if 'source' in data:
# Filtered IP ranges
conditions = data['conditions']
local_file = data['local_file'] if 'local_file' in data else False
data = load_data(data['source'], local_file = local_file, key_nam... | def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []) | Returns the list of IP prefixes from an ip-ranges file
:param filename:
:param local_file:
:param conditions:
:param ip_only:
:return: | 2.61647 | 2.622943 | 0.997532 |
contents = ''
with open(file_path, mode) as f:
contents = f.read()
return contents | def read_file(file_path, mode = 'rt') | Read the contents of a file
:param file_path: Path of the file to be read
:return: Contents of the file | 2.544571 | 4.23926 | 0.60024 |
try:
if prompt_4_overwrite(filename, force_write):
with open(filename, 'wt') as f:
print('%s' % json.dumps(blob, indent=4 if debug else None, separators=(',', ': '), sort_keys=True, cls=CustomJSONEncoder), file=f)
except Exception as e:
printException(e)
... | def save_blob_as_json(filename, blob, force_write, debug) | Creates/Modifies file and saves python object as JSON
:param filename:
:param blob:
:param force_write:
:param debug:
:return: | 3.647586 | 4.041704 | 0.902487 |
filename = 'ip-ranges-%s.json' % profile_name
ip_ranges = {}
ip_ranges['createDate'] = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
# Unique prefixes
unique_prefixes = {}
for prefix in prefixes:
if type(prefix) == dict:
unique_prefixes[prefix['ip_prefix']] = pre... | def save_ip_ranges(profile_name, prefixes, force_write, debug, output_format = 'json') | Creates/Modifies an ip-range-XXX.json file
:param profile_name:
:param prefixes:
:param force_write:
:param debug:
:return: | 2.276684 | 2.330641 | 0.976849 |
script_dir = os.path.dirname(script_path)
opinel_min_version = opinel_max_version = boto3_min_version = boto3_max_version = None
# Requirements file is either next to the script or in data/requirements
if not requirements_file:
requirements_file = os.path.join(script_dir, 'data/requirements... | def check_requirements(script_path, requirements_file = None) | Check versions of opinel and boto3
:param script_path:
:return: | 1.875499 | 1.732952 | 1.082257 |
assert 'zodb' not in app.extensions, \
'app already initiated for zodb'
app.extensions['zodb'] = _ZODBState(self, app)
app.teardown_request(self.close_db) | def init_app(self, app) | Configure a Flask application to use this ZODB extension. | 6.242081 | 5.049201 | 1.236251 |
if self.is_connected:
if exception is None and not transaction.isDoomed():
transaction.commit()
else:
transaction.abort()
self.connection.close() | def close_db(self, exception) | Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request. | 4.756752 | 4.488263 | 1.05982 |
assert 'ZODB_STORAGE' in app.config, \
'ZODB_STORAGE not configured'
storage = app.config['ZODB_STORAGE']
if isinstance(storage, basestring):
factory, dbargs = zodburi.resolve_uri(storage)
elif isinstance(storage, tuple):
factory, dbargs = ... | def create_db(self, app) | Create a ZODB connection pool from the *app* configuration. | 3.564062 | 3.00942 | 1.184302 |
assert flask.has_request_context(), \
'tried to connect zodb outside request'
if not self.is_connected:
connector = flask.current_app.extensions['zodb']
flask._request_ctx_stack.top.zodb_connection = connector.db.open()
transaction.begin()
... | def connection(self) | Request-bound database connection. | 6.047997 | 5.692046 | 1.062535 |
if not quiet:
printInfo('Adding user to group %s...' % group)
iam_client.add_user_to_group(GroupName = group, UserName = user) | def add_user_to_group(iam_client, user, group, quiet = False) | Add an IAM user to an IAM group
:param iam_client:
:param group:
:param user:
:param user_info:
:param dry_run:
:return: | 3.059661 | 3.622073 | 0.844726 |
groups_data = []
if type(groups) != list:
groups = [ groups ]
for group in groups:
errors = []
try:
printInfo('Creating group %s...' % group)
iam_client.create_group(GroupName = group)
except Exception as e:
if e.response['Error']['Co... | def create_groups(iam_client, groups) | Create a number of IAM group, silently handling exceptions when entity already exists
.
:param iam_client: AWS API client for IAM
:param groups: Name of IAM groups to be created.
:return: None | 3.322475 | 3.500769 | 0.94907 |
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_serial)
except Exception as e:
printException(e)
printError('Failed to delete MFA device %s' % mfa_serial)
pass | def delete_virtual_mfa_device(iam_client, mfa_serial) | Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return: | 2.520395 | 2.759953 | 0.913202 |
category_regex = []
authorized_empty_regex = 1
if len(category_regex_args) and len(category_groups) != len(category_regex_args):
printError('Error: you must provide as many regex as category groups.')
return None
for regex in category_regex_args:
if len(regex) < 1:
... | def init_group_category_regex(category_groups, category_regex_args) | Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex | 3.22634 | 3.45618 | 0.933499 |
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_nearest_color_hexstr(index,
... | def _get_extended_palette_entry(self, name, index, is_hex=False) | Compute extended entry, once on the fly. | 6.311754 | 5.744239 | 1.098797 |
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'truecolor' in self._palette_support: # build entry
... | def _get_true_palette_entry(self, name, digits) | Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3') | 4.567045 | 3.775463 | 1.209665 |
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[0] == 'F': # Foreground
if i... | def _index_to_ansi_values(self, index) | Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values. | 4.759431 | 2.680778 | 1.775392 |
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name.upper(), ';'.join(values))
setattr(self, nam... | def _create_entry(self, name, values, fbterm=False) | Render first values as string and place as first code,
save, and return attr. | 9.322613 | 3.617788 | 2.576882 |
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to end:
... | def write(self, data) | This could be a bit less clumsy. | 7.661487 | 6.626203 | 1.156241 |
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = outfile
sys.stdout = _L... | def set_output(self, outfile) | Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last. | 14.413324 | 5.84831 | 2.464528 |
''' Check bounds for errors and update label accordingly. '''
label = ''
# label format, based on time - when slow, go to higher-res display
delta = time.time() - self.start
if delta > self.timedelta2:
self.label_fmt = '%5.2f%%'
elif delta > self.timedelta1:
... | def _update_status(self) | Check bounds for errors and update label accordingly. | 3.752487 | 3.474562 | 1.079989 |
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' | def _render(self) | Standard rendering of bar graph. | 9.998677 | 8.461439 | 1.181676 |
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{self._last}' | def _render_internal_label(self) | Render with a label inside the bar graph. | 10.668771 | 8.022219 | 1.329903 |
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return ncc | def _get_ncc(self, width, ratio) | Get the number of complete chars.
This one figures the remainder for the partial char as well. | 10.014733 | 4.183658 | 2.393774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.