code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shortest path
from node u to node v. The average shortest path length is the
characteristic path length of the network.
Parameters
----------
L : NxN np.ndarray... | def distance_wei(G) | The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shortest path
from node u to node v. The average shortest path length is the
characteristic path length of the network.
Parameters
----------
L : NxN np.ndarray
Dir... | 5.756661 | 2.366784 | 2.432272 |
'''
The global efficiency is the average of inverse shortest path length,
and is inversely related to the characteristic path length.
The local efficiency is the global efficiency computed on the
neighborhood of the node, and is related to the clustering coefficient.
Parameters
----------
... | def efficiency_bin(G, local=False) | The global efficiency is the average of inverse shortest path length,
and is inversely related to the characteristic path length.
The local efficiency is the global efficiency computed on the
neighborhood of the node, and is related to the clustering coefficient.
Parameters
----------
A : NxN ... | 3.698128 | 2.630857 | 1.405674 |
'''
Walks are sequences of linked nodes, that may visit a single node more
than once. This function finds the number of walks of a given length,
between any two nodes.
Parameters
----------
CIJ : NxN np.ndarray
binary directed/undirected connection matrix
Returns
-------
... | def findwalks(CIJ) | Walks are sequences of linked nodes, that may visit a single node more
than once. This function finds the number of walks of a given length,
between any two nodes.
Parameters
----------
CIJ : NxN np.ndarray
binary directed/undirected connection matrix
Returns
-------
Wq : NxNxQ... | 4.331817 | 1.728741 | 2.505763 |
'''
The binary reachability matrix describes reachability between all pairs
of nodes. An entry (u,v)=1 means that there exists a path from node u
to node v; alternatively (u,v)=0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the le... | def reachdist(CIJ, ensure_binary=True) | The binary reachability matrix describes reachability between all pairs
of nodes. An entry (u,v)=1 means that there exists a path from node u
to node v; alternatively (u,v)=0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shor... | 4.127903 | 2.27784 | 1.812201 |
P = np.linalg.solve(np.diag(np.sum(adjacency, axis=1)), adjacency)
n = len(P)
D, V = np.linalg.eig(P.T)
aux = np.abs(D - 1)
index = np.where(aux == aux.min())[0]
if aux[index] > 10e-3:
raise ValueError("Cannot find eigenvalue of 1. Minimum eigenvalue " +
... | def mean_first_passage_time(adjacency) | Calculates mean first passage time of `adjacency`
The first passage time from i to j is the expected number of steps it takes
a random walker starting at node i to arrive for the first time at node j.
The mean first passage time is not a symmetric measure: `mfpt(i,j)` may be
different from `mfpt(j,i)`.... | 4.178525 | 4.013391 | 1.041146 |
'''
Do rounding such that .5 always rounds to 1, and not bankers rounding.
This is for compatibility with matlab functions, and ease of testing.
'''
if ((x > 0) and (x % 1 >= 0.5)) or ((x < 0) and (x % 1 > 0.5)):
return int(np.ceil(x))
else:
return int(np.floor(x)) | def teachers_round(x) | Do rounding such that .5 always rounds to 1, and not bankers rounding.
This is for compatibility with matlab functions, and ease of testing. | 5.169937 | 1.936102 | 2.670281 |
'''
This is equivalent to np.random.choice(n, 4, replace=False)
Another fellow suggested np.random.random_sample(n).argpartition(4) which is
clever but still substantially slower.
'''
rng = get_rng(seed)
k = rng.randint(n**4)
a = k % n
b = k // n % n
c = k // n ** 2 % n
d = ... | def pick_four_unique_nodes_quickly(n, seed=None) | This is equivalent to np.random.choice(n, 4, replace=False)
Another fellow suggested np.random.random_sample(n).argpartition(4) which is
clever but still substantially slower. | 5.70135 | 4.014211 | 1.420292 |
'''
This is an efficient implementation of matlab's "dummyvar" command
using sparse matrices.
input: partitions, NxM array-like containing M partitions of N nodes
into <=N distinct communities
output: dummyvar, an NxR matrix containing R column variables (indicator
variables) with ... | def dummyvar(cis, return_sparse=False) | This is an efficient implementation of matlab's "dummyvar" command
using sparse matrices.
input: partitions, NxM array-like containing M partitions of N nodes
into <=N distinct communities
output: dummyvar, an NxR matrix containing R column variables (indicator
variables) with N entries, w... | 6.346187 | 2.931501 | 2.164825 |
if seed is None or seed == np.random:
return np.random.mtrand._rand
elif isinstance(seed, np.random.RandomState):
return seed
try:
rstate = np.random.RandomState(seed)
except ValueError:
rstate = np.random.RandomState(random.Random(seed).randint(0, 2**32-1))
ret... | def get_rng(seed=None) | By default, or if `seed` is np.random, return the global RandomState
instance used by np.random.
If `seed` is a RandomState instance, return it unchanged.
Otherwise, use the passed (hashable) argument to seed a new instance
of RandomState and return it.
Parameters
----------
seed : hashable... | 2.550849 | 2.594292 | 0.983254 |
'''
The assortativity coefficient is a correlation coefficient between the
degrees of all nodes on two opposite ends of a link. A positive
assortativity coefficient indicates that nodes tend to link to other
nodes with the same or similar degree.
Parameters
----------
CIJ : NxN np.ndarr... | def assortativity_bin(CIJ, flag=0) | The assortativity coefficient is a correlation coefficient between the
degrees of all nodes on two opposite ends of a link. A positive
assortativity coefficient indicates that nodes tend to link to other
nodes with the same or similar degree.
Parameters
----------
CIJ : NxN np.ndarray
b... | 3.294679 | 1.607119 | 2.050053 |
'''
The assortativity coefficient is a correlation coefficient between the
strengths (weighted degrees) of all nodes on two opposite ends of a link.
A positive assortativity coefficient indicates that nodes tend to link to
other nodes with the same or similar strength.
Parameters
----------... | def assortativity_wei(CIJ, flag=0) | The assortativity coefficient is a correlation coefficient between the
strengths (weighted degrees) of all nodes on two opposite ends of a link.
A positive assortativity coefficient indicates that nodes tend to link to
other nodes with the same or similar strength.
Parameters
----------
CIJ : N... | 3.383315 | 1.668682 | 2.027538 |
'''
The k-core is the largest subnetwork comprising nodes of degree at
least k. This function computes the k-core for a given binary directed
connection matrix by recursively peeling off nodes with degree lower
than k, until no such nodes remain.
Parameters
----------
CIJ : NxN np.ndarr... | def kcore_bd(CIJ, k, peel=False) | The k-core is the largest subnetwork comprising nodes of degree at
least k. This function computes the k-core for a given binary directed
connection matrix by recursively peeling off nodes with degree lower
than k, until no such nodes remain.
Parameters
----------
CIJ : NxN np.ndarray
b... | 4.466394 | 1.763293 | 2.532985 |
'''
The k-core is the largest subnetwork comprising nodes of degree at
least k. This function computes the k-core for a given binary
undirected connection matrix by recursively peeling off nodes with
degree lower than k, until no such nodes remain.
Parameters
----------
CIJ : NxN np.nda... | def kcore_bu(CIJ, k, peel=False) | The k-core is the largest subnetwork comprising nodes of degree at
least k. This function computes the k-core for a given binary
undirected connection matrix by recursively peeling off nodes with
degree lower than k, until no such nodes remain.
Parameters
----------
CIJ : NxN np.ndarray
... | 4.183613 | 1.665794 | 2.511483 |
'''
Local assortativity measures the extent to which nodes are connected to
nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014
formula to allowed weighted/signed networks.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negat... | def local_assortativity_wu_sign(W) | Local assortativity measures the extent to which nodes are connected to
nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014
formula to allowed weighted/signed networks.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
... | 2.815807 | 1.770259 | 1.590619 |
'''
The rich club coefficient, R, at level k is the fraction of edges that
connect nodes of degree k or higher out of the maximum number of edges
that such nodes might share.
Parameters
----------
CIJ : NxN np.ndarray
binary directed connection matrix
klevel : int | None
... | def rich_club_bd(CIJ, klevel=None) | The rich club coefficient, R, at level k is the fraction of edges that
connect nodes of degree k or higher out of the maximum number of edges
that such nodes might share.
Parameters
----------
CIJ : NxN np.ndarray
binary directed connection matrix
klevel : int | None
sets the ma... | 3.758694 | 2.054194 | 1.829765 |
'''
The rich club coefficient, R, at level k is the fraction of edges that
connect nodes of degree k or higher out of the maximum number of edges
that such nodes might share.
Parameters
----------
CIJ : NxN np.ndarray
binary undirected connection matrix
klevel : int | None
... | def rich_club_bu(CIJ, klevel=None) | The rich club coefficient, R, at level k is the fraction of edges that
connect nodes of degree k or higher out of the maximum number of edges
that such nodes might share.
Parameters
----------
CIJ : NxN np.ndarray
binary undirected connection matrix
klevel : int | None
sets the ... | 3.270103 | 1.716236 | 1.905392 |
'''
Parameters
----------
CIJ : NxN np.ndarray
weighted directed connection matrix
klevel : int | None
sets the maximum level at which the rich club coefficient will be
calculated. If None (default), the maximum level is set to the
maximum degree of the adjacency matr... | def rich_club_wd(CIJ, klevel=None) | Parameters
----------
CIJ : NxN np.ndarray
weighted directed connection matrix
klevel : int | None
sets the maximum level at which the rich club coefficient will be
calculated. If None (default), the maximum level is set to the
maximum degree of the adjacency matrix
Retu... | 4.232376 | 3.11705 | 1.357815 |
'''
The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on node strengths instead of node
degrees.
Parameters
... | def score_wu(CIJ, s) | The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on node strengths instead of node
degrees.
Parameters
--------... | 5.627903 | 2.071018 | 2.717457 |
try:
return list(array).index(self.pad_value)
except ValueError:
return len(array) | def find_pad_index(self, array) | Find padding index.
Args:
array (list): integer list.
Returns:
idx: padding index.
Examples:
>>> array = [1, 2, 0]
>>> self.find_pad_index(array)
2 | 3.433372 | 4.777613 | 0.718638 |
lens = [self.find_pad_index(row) for row in y]
return lens | def get_length(self, y) | Get true length of y.
Args:
y (list): padded list.
Returns:
lens: true length of y.
Examples:
>>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]]
>>> self.get_length(y)
[1, 2, 3] | 11.838353 | 18.766808 | 0.630813 |
y = [[self.id2label[idx] for idx in row[:l]]
for row, l in zip(y, lens)]
return y | def convert_idx_to_name(self, y, lens) | Convert label index to name.
Args:
y (list): label index list.
lens (list): true length of y.
Returns:
y: label name list.
Examples:
>>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'}
>>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]]
... | 4.016612 | 6.884893 | 0.583395 |
y_pred = self.model.predict_on_batch(X)
# reduce dimension.
y_true = np.argmax(y, -1)
y_pred = np.argmax(y_pred, -1)
lens = self.get_length(y_true)
y_true = self.convert_idx_to_name(y_true, lens)
y_pred = self.convert_idx_to_name(y_pred, lens)
... | def predict(self, X, y) | Predict sequences.
Args:
X (list): input data.
y (list): tags.
Returns:
y_true: true sequences.
y_pred: predicted sequences. | 2.607158 | 2.689478 | 0.969392 |
score = f1_score(y_true, y_pred)
print(' - f1: {:04.2f}'.format(score * 100))
print(classification_report(y_true, y_pred, digits=4))
return score | def score(self, y_true, y_pred) | Calculate f1 score.
Args:
y_true (list): true sequences.
y_pred (list): predicted sequences.
Returns:
score: f1 score. | 2.631655 | 3.435667 | 0.765981 |
# for nested list
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
prev_tag = 'O'
prev_type = ''
begin_offset = 0
chunks = []
for i, chunk in enumerate(seq + ['O']):
if suffix:
tag = chunk[-1]
... | def get_entities(seq, suffix=False) | Gets entities from sequence.
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
>>> from seqeval.metrics.sequence_labeling import get_entities
>>> seq = ['B-PER', 'I-PER', 'O', 'B-LOC']
>>> get_entities(seq)
... | 2.192916 | 2.096879 | 1.0458 |
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': ch... | def end_of_chunk(prev_tag, tag, prev_type, type_) | Checks if a chunk ended between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_end: boolean. | 1.536627 | 1.618354 | 0.9495 |
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': ... | def start_of_chunk(prev_tag, tag, prev_type, type_) | Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean. | 1.680201 | 1.776091 | 0.946011 |
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
nb_true = len(true_entities)
p = nb_correct / nb_pred if nb_pred > 0 else 0
r = nb_correct / nb_true if nb_t... | def f1_score(y_true, y_pred, average='micro', suffix=False) | Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (... | 1.569039 | 2.096663 | 0.748351 |
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
nb_correct = sum(y_t==y_p for y_t, y_p in zip(y_true, y_pred))
nb_true = len(y_true)
score = nb_correct / nb_true
r... | def accuracy_score(y_true, y_pred) | Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array... | 1.852974 | 2.14585 | 0.863515 |
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
score = nb_correct / nb_pred if nb_pred > 0 else 0
return score | def precision_score(y_true, y_pred, average='micro', suffix=False) | Compute the precision.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample.
The best value is 1 and the worst value is 0.
A... | 2.043265 | 3.226726 | 0.633232 |
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score | def recall_score(y_true, y_pred, average='micro', suffix=False) | Compute the recall.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Args:
... | 2.061201 | 3.229084 | 0.638324 |
performace_dict = dict()
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
performace_dict['TP'] = sum(y_t == y_p for y_t, y_p in zip(y_true, y_pred)
... | def performance_measure(y_true, y_pred) | Compute the performance metrics: TP, FP, FN, TN
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
performance_dict : dict
Example:
>>> from seqeval.metrics import performance_measure
... | 1.653895 | 1.681199 | 0.98376 |
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
name_width = 0
d1 = defaultdict(set)
d2 = defaultdict(set)
for e in true_entities:
d1[e[0]].add((e[1], e[2]))
name_width = max(name_width, len(e[0]))
for e in pred_entiti... | def classification_report(y_true, y_pred, digits=2, suffix=False) | Build a text report showing the main classification metrics.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a classifier.
digits : int. Number of digits for formatting output floating point values.
Returns:
rep... | 1.631171 | 1.664434 | 0.980016 |
if isinstance(td, numbers.Real):
td = datetime.timedelta(seconds=td)
return td.total_seconds() | def _timedelta_to_seconds(td) | Convert a datetime.timedelta object into a seconds interval for
rotating file ouput.
:param td: datetime.timedelta
:return: time in seconds
:rtype: int | 3.383373 | 4.214242 | 0.802843 |
adapter = _LOGGERS.get(name)
if not adapter:
# NOTE(jd) Keep using the `adapter' variable here because so it's not
# collected by Python since _LOGGERS contains only a weakref
adapter = KeywordArgumentAdapter(logging.getLogger(name), kwargs)
_LOGGERS[name] = adapter
retu... | def getLogger(name=None, **kwargs) | Build a logger with the given name.
:param name: The name for the logger. This is usually the module
name, ``__name__``.
:type name: string | 9.426425 | 10.516461 | 0.89635 |
root_logger = logging.getLogger(None)
# Remove all handlers
for handler in list(root_logger.handlers):
root_logger.removeHandler(handler)
# Add configured handlers
for out in outputs:
if isinstance(out, str):
out = output.preconfigured.get(out)
if out i... | def setup(level=logging.WARNING, outputs=[output.STDERR], program_name=None,
capture_warnings=True) | Setup Python logging.
This will setup basic handlers for Python logging.
:param level: Root log level.
:param outputs: Iterable of outputs to log to.
:param program_name: The name of the program. Auto-detected if not set.
:param capture_warnings: Capture warnings from the `warnings' module. | 2.34559 | 2.589242 | 0.905899 |
for logger, level in loggers_and_log_levels:
if isinstance(level, str):
level = level.upper()
logging.getLogger(logger).setLevel(level) | def set_default_log_levels(loggers_and_log_levels) | Set default log levels for some loggers.
:param loggers_and_log_levels: List of tuple (logger name, level). | 2.207919 | 2.734063 | 0.80756 |
swag_opts = {}
if ctx.type == 'file':
swag_opts = {
'swag.type': 'file',
'swag.data_dir': ctx.data_dir,
'swag.data_file': ctx.data_file
}
elif ctx.type == 's3':
swag_opts = {
'swag.type': 's3',
'swag.bucket_name': ctx.b... | def create_swag_from_ctx(ctx) | Creates SWAG client from the current context. | 2.044177 | 1.991229 | 1.02659 |
if not ctx.file:
ctx.data_file = data_file
if not ctx.data_dir:
ctx.data_dir = data_dir
ctx.type = 'file' | def file(ctx, data_dir, data_file) | Use the File SWAG Backend | 3.51649 | 3.2785 | 1.072591 |
if not ctx.data_file:
ctx.data_file = data_file
if not ctx.bucket_name:
ctx.bucket_name = bucket_name
if not ctx.region:
ctx.region = region
ctx.type = 's3' | def s3(ctx, bucket_name, data_file, region) | Use the S3 SWAG backend. | 2.281693 | 2.278301 | 1.001489 |
if ctx.namespace != 'accounts':
click.echo(
click.style('Only account data is available for listing.', fg='red')
)
return
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all()
_table = [[result['name'], result.get('id')] for result in accounts]
click.ec... | def list(ctx) | List SWAG account info. | 5.339768 | 4.67078 | 1.143228 |
swag = create_swag_from_ctx(ctx)
accounts = swag.get_service_enabled(name)
_table = [[result['name'], result.get('id')] for result in accounts]
click.echo(
tabulate(_table, headers=["Account Name", "Account Number"])
) | def list_service(ctx, name) | Retrieve accounts pertaining to named service. | 5.894555 | 5.120251 | 1.151224 |
if ctx.type == 'file':
if ctx.data_file:
file_path = ctx.data_file
else:
file_path = os.path.join(ctx.data_file, ctx.namespace + '.json')
# todo make this more like alemebic and determine/load versions automatically
with open(file_path, 'r') as f:
... | def migrate(ctx, start_version, end_version) | Transition from one SWAG schema to another. | 4.053816 | 4.010408 | 1.010824 |
data = []
if ctx.type == 'file':
if ctx.data_file:
file_path = ctx.data_file
else:
file_path = os.path.join(ctx.data_dir, ctx.namespace + '.json')
with open(file_path, 'r') as f:
data = json.loads(f.read())
swag_opts = {
'swag.type':... | def propagate(ctx) | Transfers SWAG data from one backend to another | 3.860934 | 3.538641 | 1.091078 |
swag = create_swag_from_ctx(ctx)
data = json.loads(data.read())
for account in data:
swag.create(account, dry_run=ctx.dry_run) | def create(ctx, data) | Create a new SWAG item. | 6.227707 | 5.389903 | 1.15544 |
enabled = False if disabled else True
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all(search_filter=path)
log.debug('Searching for accounts. Found: {} JMESPath: `{}`'.format(len(accounts), path))
for a in accounts:
try:
if not swag.get_service(name, search_filter="... | def deploy_service(ctx, path, name, regions, disabled) | Deploys a new service JSON to multiple accounts. NAME is the service name you wish to deploy. | 4.232579 | 4.072337 | 1.039349 |
swag = create_swag_from_ctx(ctx)
for k, v in json.loads(data.read()).items():
for account in v['accounts']:
data = {
'description': 'This is an AWS owned account used for {}'.format(k),
'id': account['account_id'],
'contacts': ... | def seed_aws_data(ctx, data) | Seeds SWAG from a list of known AWS accounts. | 5.648676 | 5.337643 | 1.058272 |
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all()
_ids = [result.get('id') for result in accounts]
client = boto3.client('organizations')
paginator = client.get_paginator('list_accounts')
response_iterator = paginator.paginate()
count = 0
for response in response_iterator... | def seed_aws_organization(ctx, owner) | Seeds SWAG from an AWS organziation. | 3.136531 | 3.038494 | 1.032265 |
logger.debug('Loading item from s3. Bucket: {bucket} Key: {key}'.format(
bucket=bucket,
key=data_file
))
# If the file doesn't exist, then return an empty dict:
try:
data = _get_from_s3(client, bucket, data_file)
except ClientError as ce:
if ce.response['Error'... | def load_file(client, bucket, data_file) | Tries to load JSON data from S3. | 2.725006 | 2.565884 | 1.062014 |
logger.debug('Writing {number_items} items to s3. Bucket: {bucket} Key: {key}'.format(
number_items=len(items),
bucket=bucket,
key=data_file
))
if not dry_run:
return _put_to_s3(client, bucket, data_file, json.dumps(items)) | def save_file(client, bucket, data_file, items, dry_run=None) | Tries to write JSON data to data file in S3. | 2.965835 | 2.824596 | 1.050003 |
logger.debug('Creating new item. Item: {item} Path: {data_file}'.format(
item=item,
data_file=self.data_file
))
items = load_file(self.client, self.bucket_name, self.data_file)
items = append_item(self.namespace, self.version, item, items)
save_f... | def create(self, item, dry_run=None) | Creates a new item in file. | 3.412635 | 3.249219 | 1.050294 |
logger.debug('Updating item. Item: {item} Path: {data_file}'.format(
item=item,
data_file=self.data_file
))
self.delete(item, dry_run=dry_run)
return self.create(item, dry_run=dry_run) | def update(self, item, dry_run=None) | Updates item info in file. | 3.362245 | 3.107551 | 1.08196 |
logger.debug('Fetching items. Path: {data_file}'.format(
data_file=self.data_file
))
return load_file(self.client, self.bucket_name, self.data_file) | def get_all(self) | Gets all items in file. | 6.916444 | 5.905971 | 1.171094 |
logger.debug('Health Check on S3 file for: {namespace}'.format(
namespace=self.namespace
))
try:
self.client.head_object(Bucket=self.bucket_name, Key=self.data_file)
return True
except ClientError as e:
logger.debug('Error encount... | def health_check(self) | Uses head object to make sure the file exists in S3. | 5.518123 | 4.549799 | 1.212828 |
logger.debug('Deleting item. Item: {item} Table: {namespace}'.format(
item=item,
namespace=self.namespace
))
if not dry_run:
self.table.delete_item(Key={'id': item['id']})
return item | def delete(self, item, dry_run=None) | Deletes item in file. | 4.194571 | 4.179071 | 1.003709 |
logger.debug('Updating item. Item: {item} Table: {namespace}'.format(
item=item,
namespace=self.namespace
))
if not dry_run:
self.table.put_item(Item=item)
return item | def update(self, item, dry_run=None) | Updates item info in file. | 4.660406 | 4.426467 | 1.05285 |
logger.debug('Fetching items. Table: {namespace}'.format(
namespace=self.namespace
))
rows = []
result = self.table.scan()
while True:
next_token = result.get('LastEvaluatedKey', None)
rows += result['Items']
if next_to... | def get_all(self) | Gets all items in file. | 3.477647 | 3.291455 | 1.056569 |
logger.debug('Health Check on Table: {namespace}'.format(
namespace=self.namespace
))
try:
self.get_all()
return True
except ClientError as e:
logger.exception(e)
logger.error('Error encountered with Database. Assume ... | def health_check(self) | Gets a single item to determine if Dynamo is functioning. | 7.427935 | 6.193407 | 1.199329 |
options = {}
for key, val in config.items():
if key.startswith('swag.backend.'):
options[key[12:]] = val
if key.startswith('swag.'):
options[key[5:]] = val
if options.get('type') == 's3':
return S3OptionsSchema(strict=True).load(options).data
elif op... | def parse_swag_config_options(config) | Ensures that options passed to the backend are valid. | 2.244843 | 2.178895 | 1.030267 |
def wrapper(fn):
def deprecated_method(*args, **kargs):
warnings.warn(message, DeprecationWarning, 2)
return fn(*args, **kargs)
# TODO: use decorator ? functools.wrapper ?
deprecated_method.__name__ = fn.__name__
deprecated_method.__doc__ = "%s\n\n%s" % ... | def deprecated(message) | Deprecated function decorator. | 3.001265 | 2.927637 | 1.025149 |
for key in sub_dict.keys():
if key not in dictionary:
return False
if (type(sub_dict[key]) is not dict) and (sub_dict[key] != dictionary[key]):
return False
if (type(sub_dict[key]) is dict) and (not is_sub_dict(sub_dict[key], dictionary[key])):
return... | def is_sub_dict(sub_dict, dictionary) | Legacy filter for determining if a given dict is present. | 1.585336 | 1.563143 | 1.014198 |
for account in get_all_accounts(bucket, region, json_path)['accounts']:
if 'aws' in account['type']:
if account['name'] == account_name:
return account
elif alias:
for a in account['alias']:
if a == account_name:
... | def get_by_name(account_name, bucket, region='us-west-2', json_path='accounts.json', alias=None) | Given an account name, attempts to retrieve associated account info. | 2.65664 | 2.737844 | 0.97034 |
for account in get_all_accounts(bucket, region, json_path)['accounts']:
if 'aws' in account['type']:
if account['metadata']['account_number'] == account_number:
return account | def get_by_aws_account_number(account_number, bucket, region='us-west-2', json_path='accounts.json') | Given an account number (or ID), attempts to retrieve associated account info. | 2.93157 | 2.993581 | 0.979285 |
swag_opts = {
'swag.type': 's3',
'swag.bucket_name': bucket,
'swag.bucket_region': region,
'swag.data_file': json_path,
'swag.schema_version': 1
}
swag = SWAGManager(**parse_swag_config_options(swag_opts))
accounts = swag.get_all()
accounts = [account fo... | def get_all_accounts(bucket, region='us-west-2', json_path='accounts.json', **filters) | Fetches all the accounts from SWAG. | 3.77418 | 3.467073 | 1.088578 |
try:
with open(data_file, 'r', encoding='utf-8') as f:
return json.loads(f.read())
except JSONDecodeError as e:
return [] | def load_file(data_file) | Tries to load JSON from data file. | 2.78169 | 2.669593 | 1.04199 |
if dry_run:
return
with open(data_file, 'w', encoding='utf-8') as f:
if sys.version_info > (3, 0):
f.write(json.dumps(data))
else:
f.write(json.dumps(data).decode('utf-8')) | def save_file(data_file, data, dry_run=None) | Writes JSON data to data file. | 2.002866 | 1.912265 | 1.047379 |
logger.debug('Deleting item. Item: {item} Path: {data_file}'.format(
item=item,
data_file=self.data_file
))
items = load_file(self.data_file)
items = remove_item(self.namespace, self.version, item, items)
save_file(self.data_file, items, dry_run=... | def delete(self, item, dry_run=None) | Deletes item in file. | 3.619984 | 3.493322 | 1.036258 |
logger.debug('Fetching items. Path: {data_file}'.format(
data_file=self.data_file
))
return load_file(self.data_file) | def get_all(self) | Gets all items in file. | 7.790462 | 6.248349 | 1.246803 |
logger.debug('Health Check on file for: {namespace}'.format(
namespace=self.namespace
))
return os.path.isfile(self.data_file) | def health_check(self) | Checks to make sure the file is there. | 10.294732 | 7.356252 | 1.399453 |
if namespace == 'accounts':
if version == 2:
schema = v2.AccountSchema(strict=True, context=context)
return schema.load(item).data
elif version == 1:
return v1.AccountSchema(strict=True).load(item).data
raise InvalidSWAGDataException('Schema version i... | def validate(item, namespace='accounts', version=2, context=None) | Validate item against version schema.
Args:
item: data object
namespace: backend namespace
version: schema version
context: schema context object | 3.328918 | 3.399098 | 0.979354 |
self.version = kwargs['schema_version']
self.namespace = kwargs['namespace']
self.backend = get(kwargs['type'])(*args, **kwargs)
self.context = kwargs.pop('schema_context', {}) | def configure(self, *args, **kwargs) | Configures a SWAG manager. Overrides existing configuration. | 6.883242 | 6.97028 | 0.987513 |
return self.backend.create(validate(item, version=self.version, context=self.context), dry_run=dry_run) | def create(self, item, dry_run=None) | Create a new item in backend. | 6.506313 | 5.72955 | 1.135571 |
return self.backend.delete(item, dry_run=dry_run) | def delete(self, item, dry_run=None) | Delete an item in backend. | 4.070331 | 3.40309 | 1.196069 |
return self.backend.update(validate(item, version=self.version, context=self.context), dry_run=dry_run) | def update(self, item, dry_run=None) | Update an item in backend. | 6.668077 | 5.990669 | 1.113077 |
items = self.backend.get_all()
if not items:
if self.version == 1:
return {self.namespace: []}
return []
if search_filter:
items = jmespath.search(search_filter, items)
return items | def get_all(self, search_filter=None) | Fetch all data from backend. | 4.250572 | 3.996511 | 1.063571 |
if not accounts_list:
accounts = self.get_all(search_filter=search_filter)
else:
accounts = accounts_list
if self.version == 1:
accounts = accounts['accounts']
enabled = []
for account in accounts:
if self.version == 1:
... | def get_service_enabled(self, name, accounts_list=None, search_filter=None, region=None) | Get a list of accounts where a service has been enabled. | 2.72645 | 2.644813 | 1.030867 |
if self.version == 1:
service_filter = "service.{name}".format(name=name)
return jmespath.search(service_filter, self.get(search_filter))
else:
service_filter = "services[?name=='{}']".format(name)
return one(jmespath.search(service_filter, self.g... | def get_service(self, name, search_filter) | Fetch service metadata. | 2.94136 | 2.919153 | 1.007607 |
service_filter = "services[?name=='{}'].metadata.name".format(name)
return one(jmespath.search(service_filter, self.get(search_filter))) | def get_service_name(self, name, search_filter) | Fetch account name as referenced by a particular service. | 7.048717 | 6.506659 | 1.083308 |
search_filter = "[?name=='{}']".format(name)
if alias:
if self.version == 1:
search_filter = "accounts[?name=='{name}' || contains(alias, '{name}')]".format(name=name)
elif self.version == 2:
search_filter = "[?name=='{name}' || contains... | def get_by_name(self, name, alias=None) | Fetch all accounts with name specified, optionally include aliases. | 3.545602 | 3.053985 | 1.160976 |
items = []
if version_start == 1 and version_end == 2:
for item in data['accounts']:
items.append(v2.upgrade(item))
if version_start == 2 and version_end == 1:
for item in data:
items.append(v2.downgrade(item))
items = {'accounts': items}
return item... | def run_migration(data, version_start, version_end) | Runs migration against a data set. | 3.283743 | 3.239978 | 1.013508 |
environ = 'test'
if 'prod' in account['tags']:
environ = 'prod'
owner = 'netflix'
if not account['ours']:
owner = 'third-party'
services = []
if account['metadata'].get('s3_name'):
services.append(
dict(
name='s3',
metada... | def upgrade(account) | Transforms data from a v1 format to a v2 format | 2.135894 | 2.116345 | 1.009237 |
d_account = dict(schema_version=1, metadata={'email': account['email']},
tags=list(set([account['environment']] + account.get('tags', []))))
v1_services = {}
for service in account.get('services', []):
if service['name'] == 's3':
if service['metadata'].get('nam... | def downgrade(account) | Transforms data from v2 format to a v1 format | 2.515836 | 2.459906 | 1.022737 |
fields_to_validate = ['type', 'environment', 'owner']
for field in fields_to_validate:
value = data.get(field)
allowed_values = self.context.get(field)
if allowed_values and value not in allowed_values:
raise ValidationError('Must be one of {}... | def validate_type(self, data) | Performs field validation against the schema context
if values have been provided to SWAGManager via the
swag.schema_context config object.
If the schema context for a given field is empty, then
we assume any value is valid for the given schema field. | 3.40011 | 3.136919 | 1.083901 |
deleted_status = 'deleted'
region_status = data.get('status')
account_status = data.get('account_status')
for region in region_status:
if region['status'] != deleted_status and account_status == deleted_status:
raise ValidationError('Account Status ca... | def validate_account_status(self, data) | Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted | 3.825084 | 3.089755 | 1.237989 |
region_schema = RegionSchema()
supplied_regions = data.get('regions', {})
for region in supplied_regions.keys():
result = region_schema.validate(supplied_regions[region])
if len(result.keys()) > 0:
raise ValidationError(result) | def validate_regions_schema(self, data) | Performs field validation for regions. This should be
a dict with region names as the key and RegionSchema as the value | 3.045683 | 2.62948 | 1.158284 |
kwargs = {}
if coord.units.is_time_reference():
kwargs['value_format'] = get_date_format(coord)
else:
kwargs['unit'] = str(coord.units)
return Dimension(coord.name(), **kwargs) | def coord_to_dimension(coord) | Converts an iris coordinate to a HoloViews dimension. | 4.559172 | 3.746581 | 1.216889 |
import iris
order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
axis = iris.util.guess_coord_axis(coord)
return (order.get(axis, 0), coord and coord.name()) | def sort_coords(coord) | Sorts a list of DimCoords trying to ensure that
dates and pressure levels appear first and the
longitude and latitude appear last in the correct
order. | 5.079932 | 4.784752 | 1.061692 |
dim = dataset.get_dimension(dim, strict=True)
if dim in dataset.vdims:
coord_names = [c.name() for c in dataset.data.dim_coords]
data = dataset.data.copy().data
data = cls.canonicalize(dataset, data, coord_names)
return data.T.flatten() if flat el... | def values(cls, dataset, dim, expanded=True, flat=True, compute=True) | Returns an array of the values along the supplied dimension. | 3.713135 | 3.677017 | 1.009823 |
import iris
if not isinstance(dims, list): dims = [dims]
dims = [dataset.get_dimension(d, strict=True) for d in dims]
constraints = [d.name for d in dims]
slice_dims = [d for d in dataset.kdims if d not in dims]
# Update the kwargs appropriately for Element gro... | def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs) | Groups the data by one or more dimensions returning a container
indexed by the grouped dimensions containing slices of the
cube wrapped in the group_type. This makes it very easy to
break up a high-dimensional dataset into smaller viewable chunks. | 3.864412 | 3.936878 | 0.981593 |
import iris
from iris.experimental.equalise_cubes import equalise_attributes
cubes = []
for c, cube in datasets.items():
cube = cube.copy()
cube.add_aux_coord(iris.coords.DimCoord([c], var_name=dim.name))
cubes.append(cube)
cubes = ir... | def concat_dim(cls, datasets, dim, vdims) | Concatenates datasets along one dimension | 2.475118 | 2.539071 | 0.974812 |
dim = dataset.get_dimension(dimension, strict=True)
values = dataset.dimension_values(dim.name, False)
return (np.nanmin(values), np.nanmax(values)) | def range(cls, dataset, dimension) | Computes the range along a particular dimension. | 3.453307 | 3.1659 | 1.090782 |
new_dataset = dataset.data.copy()
for name, new_dim in dimensions.items():
if name == new_dataset.name():
new_dataset.rename(new_dim.name)
for coord in new_dataset.dim_coords:
if name == coord.name():
coord.rename(new_d... | def redim(cls, dataset, dimensions) | Rename coords on the Cube. | 3.26163 | 2.852873 | 1.143279 |
return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp) | def length(cls, dataset) | Returns the total number of samples in the dataset. | 9.589006 | 9.10297 | 1.053393 |
if not vdim:
raise Exception("Cannot add key dimension to a dense representation.")
raise NotImplementedError | def add_dimension(cls, columns, dimension, dim_pos, values, vdim) | Adding value dimensions not currently supported by iris interface.
Adding key dimensions not possible on dense interfaces. | 23.55876 | 9.202007 | 2.560176 |
import iris
def get_slicer(start, end):
def slicer(cell):
return start <= cell.point < end
return slicer
constraint_kwargs = {}
for dim, constraint in selection.items():
if isinstance(constraint, slice):
constr... | def select_to_constraint(cls, dataset, selection) | Transform a selection dictionary to an iris Constraint. | 3.148003 | 2.956843 | 1.06465 |
import iris
constraint = cls.select_to_constraint(dataset, selection)
pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
indexed = cls.indexed(dataset, selection)
extracted = dataset.data.extract(constraint)
if indexed and not extracted.dim_coords:
... | def select(cls, dataset, selection_mask=None, **selection) | Apply a selection to the data. | 3.989912 | 3.869428 | 1.031138 |
geotype = getattr(gv_element, type(element).__name__, None)
if crs is None or geotype is None or isinstance(element, _Element):
return element
return geotype(element, crs=crs) | def convert_to_geotype(element, crs=None) | Converts a HoloViews element type to the equivalent GeoViews
element if given a coordinate reference system. | 4.838383 | 4.3176 | 1.120619 |
crss = [crs for crs in element.traverse(lambda x: x.crs, [_Element])
if crs is not None]
if not crss:
return {}
crs = crss[0]
if any(crs != ocrs for ocrs in crss[1:]):
raise ValueError('Cannot %s Elements in different '
'coordinate reference syst... | def find_crs(op, element) | Traverses the supplied object looking for coordinate reference
systems (crs). If multiple clashing reference systems are found
it will throw an error. | 4.951342 | 4.861199 | 1.018543 |
return element.map(lambda x: convert_to_geotype(x, kwargs.get('crs')), Element) | def add_crs(op, element, **kwargs) | Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system. | 13.727289 | 9.112581 | 1.506411 |
if isinstance(element, (Overlay, NdOverlay)):
return any(element.traverse(is_geographic, [_Element]))
if kdims:
kdims = [element.get_dimension(d) for d in kdims]
else:
kdims = element.kdims
if len(kdims) != 2 and not isinstance(element, (Graph, Nodes)):
return Fals... | def is_geographic(element, kdims=None) | Utility to determine whether the supplied element optionally
a subset of its key dimensions represent a geographic coordinate
system. | 4.420888 | 4.676623 | 0.945316 |
feature = self.data
if scale is not None:
feature = feature.with_scale(scale)
if bounds:
extent = (bounds[0], bounds[2], bounds[1], bounds[3])
else:
extent = None
geoms = [g for g in feature.intersecting_geometries(extent) if g is not... | def geoms(self, scale=None, bounds=None, as_element=True) | Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEarthFeature:
'10m', '50m', '110m'
GSHHSFeature:
... | 2.58093 | 2.616573 | 0.986378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.