content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convertMac(macAddress):
""" Performs conversion of Mac Address format to the colon type and return as string """
# Reference: https://forums.freebsd.org/threads/python-inserting-a-sign-after-every-n-th-character.26881/
# Convert to CAPS
stdMac = str(macAddress).upper()
# Checks if contains '-' ch... | 28089ecb2b70880a400c7e147e302be8bb888108 | 587,505 |
def select(*args):
"""Select specific columns from DataFrame.
Output will be DplyFrame type. Order of columns will be the same as input into
select.
>>> diamonds >> select(X.color, X.carat) >> head(3)
Out:
color carat
0 E 0.23
1 E 0.21
2 E 0.23
Grouping variables are implied... | 82b268858458599bb6deca00335a275defe4e57c | 587,508 |
def format_tasks(tasks):
"""Converts a list of tasks to a list of string representations.
Args:
tasks: A list of the tasks to convert.
Returns:
A list of string formatted tasks.
"""
return ['%d : %s (%s)' % (task.key.id(),
task.description,
('do... | 3fcf5b83714d61daf7c17d0f4d0c212d8114bd59 | 587,529 |
def get_angular_speed(linear_vel, turn_rad):
"""Relates path to the angular velocity."""
if turn_rad != 0:
return linear_vel / turn_rad
else:
return 0 | e87af29616d484e1446aaef1183eeed87ef4d229 | 587,530 |
def count_achievable_targets(numbers, start, end):
"""
Counts the number of targets within the range [start, end] that can be
achieved by adding x and y, where x and y are two distinct numbers in
`numbers`.
"""
count = 0
for target in range(start, end + 1):
for number in numbers:
... | 1717ad81ca9bfae8277b5cd30e31b8e18e87bfba | 587,531 |
from typing import Dict
def _join_words(w1: Dict, w2: Dict) -> Dict:
"""Join two word dicts.
Join the text of two words and correct x dimensions
Args:
w1: Left word
w2: Right word
Returns:
Dict: Joined word
"""
temp = w1
temp["text"] = w1["text"] + " " + w2["text... | c2c239c0274571a4700f808ad1fa6c4bab62b73a | 587,534 |
def magnitude(u):
"""returns the magnitude (length) of vector u"""
return (u[0]**2 + u[1]**2 + u[2]**2)**0.5 | 917f37eadfb57fd7025518fe2140e749746eba67 | 587,536 |
def get_form_by_action(response, action):
"""Gets a form give an action string or returns None."""
form = None
try:
form = next(
form for form in response.forms.values() if form.action == action)
except StopIteration:
pass
return form | c92a52eb43d1792fe2717be39d3835b11551c84c | 587,539 |
def hermite(m0,m1,t0,t1,u,domain=None):
"""Evaluate a cubic hermite curve at interpolation parameter u in [0,1].
Endpoints are m0 and m1, with derivatives t0 and t1. These are assumed to be Numpy arrays.
Alternatively, if `domain` != None, then this will use domain=(a,b)
as the interpolation ... | a627580ce95e4bda769715c544aab9960ac1d1ec | 587,540 |
import math
def point_on_sphere(r, s_deg, t_deg, center):
"""
Returns a point on sphere of radius r: see definition of polar (sperical)
coordinate system in 3D.
"""
sin = math.sin
cos = math.cos
s = s_deg*math.pi/180
t = t_deg*math.pi/180
x = center[0] + r * cos(s) * sin(t)
y = center[1] + r * sin... | 0844f96e33579e5196f6d88d4cdab8ec1c7983e2 | 587,541 |
def merge(*args, **kwargs):
"""
Merges several dictionaries. Checks for consistent values.
:param args: dictionaries
:return: merged dict
"""
ret = dict(args[0])
for d in args[1:] + (kwargs,):
for k in d:
if k in ret:
if d[k] != ret[k]:
... | e4b2ccba7a1611b5e48517db32138bdcb77442ec | 587,545 |
def plural(how_many):
"""Construct postfix for singular or plural."""
if how_many > 1 or how_many == 0:
return "s"
return "" | e690da2f9a6d8e00daef6ad7ce0a6ea5f3ab5df4 | 587,547 |
def remove_nones(dict_):
"""
Remove fields from the dict whose values are None.
Returns a new dict.
:type dict_: dict
:rtype dict
>>> remove_nones({'a': 4, 'b': None, 'c': None})
{'a': 4}
>>> sorted(remove_nones({'a': 'a', 'b': 0}).items())
[('a', 'a'), ('b', 0)]
>>> remove_non... | 76d53781dc796f51753ea9b0d5df5c8801ee6650 | 587,551 |
import csv
def csv_reader(fp, dialect='escaped'):
"""Returns a csv reader from stream-like `fp` with the correct dialet."""
if not dialect:
dialect = csv.Sniffer().sniff(fp.read(1024))
fp.seek(0)
return csv.reader(fp, dialect) | f9bf0e15a7ba23036bb6064096528d923e883d11 | 587,553 |
def create_numeric_suffix(base, count, zeros):
"""Create a string based on count and number of zeros decided by zeros
:param base: the basename for new map
:param count: a number
:param zeros: a string containing the expected number, coming from suffix option like "%05"
"""
spli = zero... | ca7107307ee38aa3bcd6e7d1f4dc9249862b97cd | 587,556 |
import yaml
def load_skeleton(fpath):
"""Load keypoint and parent specification defining skeletal stucture.
Parameters
----------
fpath: file-like object, string, or pathlib.Path
.yml file to read from
Returns
-------
keypoint_names: str list, len K
parents: i... | 7957ed5a5fcf6ea3a4a511b46a42a75ab8c77604 | 587,557 |
def is_vertex_field_name(field_name):
"""Return True if the field's name indicates it is a non-root vertex field."""
return field_name.startswith('out_') or field_name.startswith('in_') | 0d19000a3f34cd78677b41e52cdeee835186888b | 587,561 |
import re
def create_metadata_filename_regex(metadata, study_id):
"""Create regular expressions for study metadata files.
Parameters
----------
metadata : str, required
Type of metadata file ('sample' or 'prep'), found in the study_path,
from which to extract attributes.
study_id ... | d741db5afb592a22035cfa47f739f910049081f1 | 587,564 |
def project_coordinates(coordinates, projection, **kwargs):
"""
Apply projection to given coordinates
Allows to apply projections to any number of coordinates, assuming
that the first ones are ``longitude`` and ``latitude``.
Examples
--------
>>> # Define a custom projection function
... | 2f7779f78f5173b40cf564f66a368741e699a648 | 587,566 |
from typing import Union
import json
def decode_json(json_input: Union[str, None] = None):
"""
Simple wrapper of json.load and json.loads.
If json_input is None the output is an empty dictionary.
If the input is a string that ends in .json it is decoded using json.load.
Otherwise it is decoded us... | 44a2c596a4796c2ca05ee6297fd2d77256e6afb2 | 587,567 |
def left_shift(data, dim="t2", shift_points=0):
"""Remove points from the left of data
Args:
data (dnpdata): Data container for data
+---------------+------+---------+--------------------------------------------------+
| parameter | type | default | description ... | 169419806ea9a4f52f2eae3c79764c2929893480 | 587,568 |
def capfirst(x):
"""Capitalize the first letter of a string. Kindly borrowed from Django"""
return x and str(x)[0].upper() + str(x)[1:] | d4e269a8e097ddd3ee72e8413dfca30f0c43807a | 587,571 |
def extract_module( asdl_str ):
"""Return the module name and the module string of the given asdl
string."""
module_name_start = asdl_str.index( 'module' ) + len( 'module' )
module_name_end = asdl_str.index( '{' )
module_str_end = asdl_str.index( '}' )
module_name = asdl_str[ module_name_start : module_nam... | 197ea501ceb0cc3a9cd13f3796af95fbc59843e0 | 587,577 |
def uniq(lst):
"""
this is like list(set(lst)) except that it gets around
unhashability by stringifying everything. If str(a) ==
str(b) then this will get rid of one of them.
"""
seen = {}
result = []
for item in lst:
if str(item) not in seen:
result.append(item)
... | 706ec44f340fbfca36cb1a605391e9fc32d38ca0 | 587,579 |
def roundodd(num):
"""
Round the given number to the nearest odd number.
"""
rounded = round(num)
if rounded % 2 != 0:
return rounded
else:
if rounded > num:
return rounded - 1
else:
return rounded + 1 | b2c6a1205069fd4e7323a5e62814bd31ae0b4123 | 587,581 |
def convert_char_to_int(char, limit=256):
"""
Take a character and return an integer value while ensuring the values returned do not go above the limit.
:param str char: A single character.
:param int limit: An integer representing the largest value which will start requiring reducing char value.
(d... | 3cceb8771345e412d9316815a647cba8652959cb | 587,583 |
def one_minus(x):
"""Returns elementwise '1 - x' of any argument."""
return 1 - x | 19ccf60be99ae274713adec62073972896b3a9d7 | 587,585 |
def verify_names(*, chk_names, ref_names):
"""
Verifies that all names in chk_names also are in ref_names and in the same order.
Names that appear multiple times in chk_names should appear the same number of times in ref_names.
"""
i_chk = iter(chk_names)
i_ref = iter(ref_names)
chk = next(... | 9cd5d5a36ac9990fc755438dd02689afb6c0ee6c | 587,587 |
def symmetric_tour_list(n_cities, start_index = 0):
"""
Returns a numpy array representiung a symmetric tour of cities
length = n_cities + 1
First and last cities are index 'start_index' e.g. for
start_index = 0 then for 5 cities tour =
[0, 1, 2, 3, 4, 0]
"""
tour = [x for x in range(n_... | cbd56e827dba952e18a1e5b1b5996777c932e7c0 | 587,590 |
def _is_galactic(source_class):
"""Re-group sources into rough categories.
Categories:
- 'galactic'
- 'extra-galactic'
- 'unknown'
- 'other'
Source identifications and associations are treated identically,
i.e. lower-case and upper-case source classes are not distinguished.
Refere... | 8e8769f6f2862fff7e983469fca19e87f3f42dfb | 587,594 |
def add_trip_velocity(df):
"""Adding new variable for trip velocity (in miles per hour)."""
print("adding trip velocity")
df['trip_velocity'] = df.trip_distance / df.trip_duration_hours
return df | af4d92ed1b71e01919a5344860a39a14c2b4cb6f | 587,595 |
import re
def extract_top_level_domain_from_uri(uri):
"""
Extract host's top level domain from URIs like 'https://amy.carpentries.org/api/v1/organizations/earlham.ac.uk/' to 'earlham.ac.uk'.
When subdomains are used, as in 'https://amy.carpentries.org/api/v1/organizations/cmist.manchester.ac.uk/' we are o... | 22d965028116d1faaae6de6bc7d7dd877c50b9a2 | 587,600 |
import re
def get_error_message(error, language):
"""Filters the stack trace from stderr and returns only the error message."""
if error == '':
return None
elif language == "python":
if any(e in error for e in ["KeyboardInterrupt", "SystemExit", "GeneratorExit"]): # Non-compiler errors
... | 135cf44a35afa2d234112720ad50d7fa97ff0678 | 587,602 |
def constant_benchmark_theta(benchmark_name):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying a single parameter benchmark.
Parameters
----------
benchmark_name : str
Name of the benchmark (as in `madminer.core.MadMiner.add_benchmark`)
... | a1ec1e9df7e9b5062bd79d850b18d746648d1836 | 587,605 |
from typing import List
from typing import Tuple
import random
def _sample_public_client_ids(
num_clients: int,
client_data: List,
round_num: int,
epoch: int,
) -> Tuple[List, int]: # pylint: disable=g-bare-generic
"""Returns a random subset of client ids."""
del round_num # Unused.
return ran... | e0aa39689deff7691bf4a10e8f23d5b09b643f53 | 587,608 |
def loss_batch(model, loss_func, xb, yb, opt=None, metric=None):
"""Calculates the loss and metric value for a batch of data,
and optionally performs gradient descent if an optimizer is provided."""
preds = model(xb)
loss = loss_func(preds, yb)
if opt is not None:
loss.backward() # Compute... | a3630c3f61090b3148288c23a56511f0fb275737 | 587,611 |
def aizawa(XYZ, t, a=0.95, b=0.7, c=0.6, d=3.5, e=0.25, dz=0.1):
"""
The Aizawa Attractor.
x0 = (0.1,0,0)
"""
x, y, z = XYZ
x_dt = (z - b) * x - d * y
y_dt = d * x + (z - b) * y
z_dt = c + a * z - (z**3) / 3 - (x**2 + y**2) * (1 + e * z) + dz * z * x**3
return x_dt, y_dt, z_dt | d0ab7ef6a88b8ff038232e779d51b1aa30744e66 | 587,615 |
def sample_taxon_list(genome_table, abund_table):
"""
Create [sample,taxon] list of lists
Parameters
----------
genome_table : pd.DataFrame
abund_table : pd.DataFrame
"""
# joining tables
df = abund_table.merge(genome_table, on=['Taxon'])
# convert to a list of lists
sample_t... | 1311e55efbaf384b5664947479e6b84c580517c6 | 587,619 |
def cal_nodes(cut_off_value, labels):
"""Creates nodes for the hierarchical value map (vis.js network) based on Args
Args:
cut_off_value ([int]): [cutoff-value]
labels ([dict]): [labels]
Returns:
[Array]: [nodes]
"""
nodes = []
for l in labels:
if (l.get('acv')=... | ca9438795ff136b949a3f66fe052b3a502aa41a0 | 587,620 |
def get_samples(outlier_removed_file):
""" Read samples from the outlier removed file
outlier_removed_file : str ; the outlier removed file
returns : list ; the sample names of the outliers
"""
outlier_samples = []
with open(outlier_removed_file,'r') as IN:
for line in IN:
... | 8cb2b50fd4daa70cf70e9388bceaac8682bac3fb | 587,624 |
import ast
def safe_eval_maths(expr):
"""
Safely evaluates a maths expression,
such as (2**32-1) or (400|0x1000)
Will throw a ValueError exception on error
Note: This is still susceptible to memory or CPU exhaustion by putting
in large numbers.
"""
allowed = (ast.Expression, ast... | 54dcf13679dffa13c02bb7920f7d24b1626e3285 | 587,625 |
def get_flat_function(List, idx):
"""Get the idx index of List. If idx >= len(List), return the last element"""
if idx < 0:
return List[0]
elif idx < len(List):
return List[idx]
else:
return List[-1] | 6bbd31d88faab82179fef70a3e5122e021a664e8 | 587,626 |
def prok(effect_col):
""" Remove splice and intron signal events, not meaningful for prokaryotes"""
return ','.join([ii for ii in effect_col.split(',') if 'splice' not in ii and 'intron' not in ii]) | ff42185c129b74cb1f0ebbbb4caf05978fc0da3c | 587,627 |
def score(matches):
"""Assign winning amplicon set id based on match stats"""
# naive: take max of all bins
m = 0
winner = None
for k, v in matches.items():
if v >= m:
m = v
winner = k
return winner | b295ec9bd5e55bc4814f34ce0b5e6d0c4717cd35 | 587,629 |
def get_y(path, height):
"""Gets the y value from the image filename"""
return (float(int(path.split("_")[2])) - height/2) / (height/2) | beca50e5f106732ab6c34d1df9dac182fb2498d4 | 587,631 |
def get_index_from_tensor_name(tensor_name):
"""
Get the index of the tensor of a certain op.
Args:
tensor_name (str): The tensor name
Returns:
int: The index of the tensor
"""
return int(tensor_name.split(':')[1]) | dc429ca35a2e35e536298b4a355acbdc8076f41e | 587,633 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
res = []
fil = open(path, "r")
for i in fil:
res.append(i[:-1])
return res | 76e124bfdc605a066e3ddd6358e123839dfcf6b6 | 587,634 |
def lemmatizer_fun(lemmatizer, token, token_tag=None):
"""lemmatize token with tag of token in sentence
if token has not tag lemmatized With no tag method
Arguments:
lemmatizer {obj} -- instance of WordNetLemmatizer
token {str} -- token
Keyword Arguments:
token_tag {str} -- tag... | a64597b3a5e3e76b31bb3c3e8f5cf6d34f892e12 | 587,642 |
import json
def get_ner_tag_mapping(path):
"""
get ner_tag_mapping callable
----------------------------
:param path: [str] to ner_tag_mapping json
:return: [callable] ner_tag_mapping that applies ner_tag_mapping (loaded from json) or identical mapping
"""
def without_bio(tag):
""... | be60496f1a93acbe08daaf5ad2a749ed2f099029 | 587,645 |
def get_broker_items(broker_row_data, bip_codes):
"""Returns lists with data for broker items: execution groups, applications, message flows."""
output_list = broker_row_data.split('\n')
exec_groups = list()
applications = list()
message_flows = list()
for record in output_list:
if recor... | ecc3fa8abb1967b6e8cc92e0608e0e1b97e4aa89 | 587,646 |
import torch
def encodeOneHot(tensor, n_dim):
"""
One hot encoding for a given tensor
:param tensor: (torch Tensor)
:param n_dim: (int) Number of dimensions
:return: (torch.Tensor)
"""
encoded_tensor = torch.Tensor(tensor.shape[0], n_dim).zero_().to(tensor.device)
return encoded_tensor... | f55e3af3611245c3a69b1b725ed2babec00677c5 | 587,650 |
import glob
def list_data_files(data_path ="./data/*.csv"):
"""List available file to do the data analysis and group in a dict according the data frequency.
Files should have the following structure:
WIN$N_10M_2013.11.08_2021.01.22_.csv
{ativo}_{frequencia}_{data_inicio}_{data_fim}_.csv
... | d309b1e212abc1a0c851ea8715d5a845c61580c8 | 587,652 |
import hashlib
def _normalize_and_hash(s):
"""Normalizes and hashes a string with SHA-256.
Args:
s: The string to perform this operation on.
Returns:
A normalized (lowercase, remove whitespace) and SHA-256 hashed string.
"""
return hashlib.sha256(s.strip().lower().encode()).hexdi... | f10733b8a179b4af01f7048e607776120824298f | 587,656 |
def port_drop_ppm(port):
"""
Return packet drops from the port stats.
"""
rx_sum = sum([j - i for i, j in zip(port.rx_cyc[:-1], port.rx_cyc[1:])])
rxd_sum = sum(
[j - i for i, j in zip(port.rx_drop_cyc[:-1], port.rx_drop_cyc[1:])])
tx_sum = sum([j - i for i, j in zip(port.tx_cyc[:-1], p... | 369ee41db98efba379fd47901ec5a8b77ab7396c | 587,657 |
def get_dict_value(data, key):
""" Returns dict value for a given key (case insensitive) """
for key_name in data.keys():
if key_name.lower() == key.lower():
return data[key_name]
return None | ddb4915e008ec9f72a97e8f8e88bb5b20d2be7dc | 587,658 |
import json
def load_settings(file):
"""
Load the settings file and parse it with JSON
:param file: Location of the settings file
:return: Dict result of parsing
"""
with open(file, "r+") as file:
data = json.load(file)
return data | b65b58cd563fd780f9a1d0c1cdf232acc05cb239 | 587,662 |
def normalize_keyword(keyword):
"""Normalize keyword for became id
- Replace white space with '-'
- Convert to lowercase"""
return keyword.lower().replace(' ', '-') | cdc2f4359360e0a75372057328c23b3e26f4a0fa | 587,667 |
def noop_preprocessing_fn(inputs):
"""No-op preprocessing fn for Transform.
This is provided as a convenience for pipelines that don't do any data
preprocessing but require a Transform component anyway (e.g. because the
trainer expects a transform graph as input).
Args:
inputs: Dict of input tensors.
... | afffb578d41ef815994af90c325d615c37c297e8 | 587,668 |
from typing import Union
def resistance(voltage: Union[int, float], current: Union[int, float]) -> float:
"""Calculate resistance, in Ohms (\u03A9), based on Ohm's Law.
Args:
voltage (Union[int, float]): The voltage, in volts (V).
current (Union[int, float]): The current, in Amperes (A).
... | 3c258a7e195255fb03d5590d61e723d0314f6d3c | 587,669 |
import re
def _progress_stdout_handler(progress_cb):
"""
:return: stdout handler which looks for percentage done reports
and makes an appropriate call to the progress callback.
The handler uses a regex to look for a 'percentage'
output and calls the progress handler with the number
f... | d8a4446c793e44b30ecd1f261d190c037ea562b6 | 587,673 |
from typing import Tuple
from typing import List
def longest_repetition(chars: str) -> Tuple:
"""
For a given string s find the character c (or C)
with longest consecutive repetition and return: (c, l)
where l (or L) is the length of the repetition.
If there are two or more characters with
th... | 2499d506674987e5bc32bba2150bbda9d775daa7 | 587,677 |
from importlib import import_module
def dynamic_import(attribute, module_path):
"""Import attribute from module found at module_path at runtime.
Args:
attribute: the attribute of the module to import (class, function, ...)
module_path: the path to the module.
Returns:
attribute f... | 42d7c534a30b430dfea90c2d86f697ae5d449306 | 587,678 |
def gettext(text):
"""Dummy `gettext` replacement to make string extraction
tools scrape strings marked for translation """
return text | e2c19411c3c990b76b55cf37d87d7f11ad6c4186 | 587,679 |
def get_sample_name(filename: str) -> str:
"""Get sample name from filename."""
split = filename.split("_")
return "_".join(split[:2] + split[3:]) | c40457e8b7ee76818ed26749e3ff52d0df105549 | 587,680 |
def encode_variable(d, i, j):
"""This function creates the variable (the integer) representing the
fact that digit d appears in position i, j.
Of course, to obtain the complement variable, you can just negate
(take the negative) of the returned integer.
Note that it must be: 1 <= d <= 9, 0 <= i <= 8... | 3c59dd05a00d4ac51e835900dad10d7265e2fc91 | 587,682 |
def get_next_page_count(value):
"""
Expects ``value`` to be an instance of ``Paginator.Page``.
Returns the number of items on the next page, if any; does not check
for the existence of the next page.
"""
p = value.paginator.page(value.next_page_number())
return p.end_index() - p.start_inde... | 2f6d6d42b5475045301c9cc3ad4ded6b6b35a7f6 | 587,685 |
def piecewise_func(parameters, x):
"""
Defines the piecewise function
f = { b if x < a
{ c*(x - a) + b if x >= a
where a, b and c are parameters given by parameters[0], [1] and [2] respectively
"""
if x < parameters[0]:
return parameters[1]
return paramete... | f9acbfbb7af50ff5bd48f0f15dd9560ed15bfbdb | 587,689 |
from typing import Any
from typing import List
def is_typing_list(data_type: Any) -> bool:
"""
Return `True` if data_type is `typing.List` or a subscription of it.
Examples
--------
```python3
assert is_typing_list(typing.List)
assert is_typing_list(typing.List[int])
assert not is_typ... | 5da5e598c570e21947f2765095d01f8d7c7e33de | 587,690 |
def csv_row_to_enquiry_filter_kwargs(csv_row: dict) -> dict:
"""
Converts a CSV ``row`` into a ``dict`` representing
:class:`app.enquiries.models.Enquiry` query `kwargs`
e.g. ``enquiry__enquirer__first_name``.
:param csv_row: The CSV row
:type csv_row: dict
:returns: ``dict`` of queryset f... | e1f8f4b328cda894efce142acfaf9cc9f5faa344 | 587,691 |
def enrich_with_delta(record: dict, previous_record: dict) -> dict:
"""Enriches a record with delta time fields.
Parameters
----------
record : dict
The statistics record from PocketCasts as a dict.
previous_record : dict
The most current record in Airtable.
Returns
-------... | a57eb8357de59c9d9a1a7da63ce0c3eaa65c870b | 587,694 |
def has_duplicate(x):
"""
Checks if any value in x occurs more than once
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: bool
"""
return len(x) != len(set(x)) | af1a46b9ee41db50735432dae555b909e015a026 | 587,695 |
def step_input(CurrTime, Amp, StartTime = 0.0):
"""
Function to create a step input
Arguments:
CurrTime : The current timestep (will also take an array)
Amp : The size of the step input
StartTime : The time that the step should occur
Returns:
The step input for the CurrTime tim... | ea30e0e9717ffdc79d525291693adbe6129349c4 | 587,696 |
def load_keywords_from_json(input_json):
"""Converts keywords from json to python
:param input_json: json input with "keywords" array
:return: keywords converted to python
"""
return input_json["keywords"] | e260e5316398373597f06089ef1aecacb0532986 | 587,702 |
def get_asset_registry(data):
""" Return the asset registry if its available"""
if "AssetRegistry" in data and "AssetImportData" in data["AssetRegistry"]:
return data["AssetRegistry"] | 284998ad1e5fd80be30588a13ccf9a0718580b1c | 587,706 |
def computeInterestingness(IC, DL, **kwargs):
"""function to compute interestingness of a pattern
Args:
IC (float): Information Content
DL (float): Description Length
kwargs:
mode (int): 1 if I = IC/DL, 2 if I = IC - DL, default is 1
Returns:
float: Interestingness sco... | 5f2a0d63686ba9c52e75f820f71dd426ff56a450 | 587,708 |
def code_from_10_length_numbers(numbers: list[int], start_index: int,
n_loop: int) -> str:
"""
From a 10-length list of number, a starting index and a limit of loop,
return a code.
The start index is used to get a value. This value is add to the code, then
used as an... | 40a7d10c7922588cad4dd8ea72f9b9b3a769bd7e | 587,711 |
def _pgsql_numerical_version_to_string(version_num):
"""Convert numerical PostgreSQL version to string."""
if version_num < 100000:
major = version_num // 10000
minor = version_num % 10000 // 100
patch = version_num % 100
return f"{major}.{minor}.{patch}"
# version 10+
m... | c57ac45697a7dd318a2b952f4ba9ef5bcfdfe29e | 587,714 |
def entity_with_comment(entity_a):
"""
A simple entity that contains pre-defined key and comment.
"""
entity_a.key = "key_entity_a"
entity_a.comment = "example comment"
return entity_a | 3efa38e2c42d047af783998cd96eb84cab7aee64 | 587,717 |
import re
def getLength(st):
""" Searching "content-length" from rtsp strings using regular expressions
"""
pat=re.compile("Content-Length: \d*")
pat2=re.compile('\d+')
mstring=pat.findall(st)[0] # matched string.. "Content-Length: 614"
num=int(pat2.findall(mstring)[0])
return num | 4a800ed8c79e973486680f7a658bb5a6ed3695c6 | 587,719 |
from pathlib import Path
import tempfile
def mktempdir(prefix: str) -> Path:
"""Create a directory in ``$TMPDIR`` with the given prefix"""
return Path(tempfile.mkdtemp(prefix=prefix)) | 78fba31e56c39186c6e9a703459000edc4583be8 | 587,727 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
def get_entity(entity_id: str, entities: List[Dict[str, Any]]) -> Dict:
"""
Retrieves entity from list of entities given the entity id.
Parameters
----------
entity_id: String identifier of the rele... | 28dbc7475ce1bfb38fe44ba6dcd273735af80cf8 | 587,733 |
def get_snr(snr_min, emission_line, default=3):
"""Convenience function to get the minimum SNR for a certain emission line.
If ``snr_min`` is a dictionary and ``emision_line`` is one of the keys,
returns that value. If the emission line is not included in the dictionary,
returns ``default``. If ``snr_m... | 590c496cabf86aeabcb118c98abea3634317b88f | 587,734 |
import logging
def remove_overly_null_columns(df, percentage_null=.25):
"""
Purpose:
Remove columns with the count of null values
exceeds the passed in percentage. This defaults
to 25%.
Args:
df (Pandas DataFrame): DataFrame to remove columns
... | d7f6b4351a7d614f2dac4e6e909906c6327f404e | 587,742 |
def remove_subcomplexes(cxs, max_size=3):
"""
Given a list of complexes, return a list without any complexes sized
max_size or lower that are a subset of another complex.
"""
cxs_copy = list(cxs)
return [c for c in cxs if len(c) > max_size or len([c2 for c2 in cxs_copy
if c.issubset(c2) ... | 9ed822f6db49ae24fcfcd8535822ff2c7c2bdc1e | 587,743 |
def has_few_assignments(example, minimum=4):
"""Check if file uses symbol '=' less than `minimum` times."""
lines = example["content"].splitlines()
counter = 0
for line in lines:
counter += line.lower().count("=")
if counter > minimum:
return {"has_few_assignments": False}
... | 19ae0dcf55dad463c56912223ccbed9798c09820 | 587,745 |
def two_pad(in_time):
"""
Takes in a number of 1 or 2 digits, returns a string of two digits.
"""
assert isinstance(in_time,int)
assert (in_time < 100 and in_time >= 0)
return "0" + str(in_time) if str(in_time).__len__() == 1 else str(in_time) | fa8014c7e14205a55406e3052486c3723343db41 | 587,746 |
def bernoulli_param(N, T, I_T, F_N):
""" Bernoulli parameter definition (Maximum Likelihood)
Args:
N : Total number of people in the city
T : Number of people in the test sample
I_T : Number of infected people in the test sample
F_N : Total number of fatalities in the ci... | ab2c2283c8ec2abbb2bd94db131fcbf98a98a42a | 587,747 |
import torch
def split_heads(x, num_heads):
"""split x into multi heads
Args:
x: [batch_size, length, depth]
Returns:
y: [[batch_size, length, depth / num_heads] x heads]
"""
sz = x.size()
# x -> [batch_size, length, heads, depth / num_heads]
x = x.view(sz[0], sz[1], num_he... | 94fed67d837439cc41c77dae004e7370ae567b5e | 587,750 |
def get_n_s(num):
"""
Get a string for a float at .2f
"""
if num == None:
return 'None'
return "%.2f"%num | 3111d9c2c1d443c013bab9b8e65efafb11b2106c | 587,752 |
import typing
import pathlib
def is_path_obj(obj: typing.Any) -> bool:
"""Is given object 'input' a pathlib.Path object?
:param obj: a pathlib.Path object or something
:return: True if 'obj' is a pathlib.Path object
>>> obj = pathlib.Path(__file__)
>>> assert is_path_obj(obj)
>>> assert not ... | 178342dc5301d2440b78411a2737f889b49c73f9 | 587,761 |
def dict_fetch_all(cursor):
"""
Return all rows from a cursor as a dict.
By default, the Python DB API will return results without their field names, which means you end up with a
list of values, rather than a dict. At a small performance and memory cost, we can return results as a
dict.
Using ... | 8aeefdfcccd0c9b3999c3ebfcec2e72a90b90050 | 587,762 |
def mongo_load(database, collection_key, id_key):
"""Load data from MongoDB database.
Args:
database (:class:`pymongo.database.Database`): MongoDB database to save
results to.
collection_key (str): name of collection.
id_key (str): id key to look up data.
Returns:
... | 7310bff33f744f4f5e7371ab4ea21dde76126973 | 587,763 |
import math
def evaluate_almost_equal(metrics, results, abs_tol=None, rel_tol=None):
"""
Evaluate for each given metric if values in results are almost equal
Parameters
----------
metrics: List[str], metrics names
results: dict, results to be evaluated
abs_tol: float, absolute error tolera... | 9d6745d9e6f15d68285cb227f830a83bccf6e2f0 | 587,765 |
def _vector_to_matrix(Rv, k):
"""
Returns a matrix from reforming a vector.
"""
U = Rv.reshape((-1, k))
return U | 5754414500732a83d7ce461a46c17547a6473d37 | 587,768 |
import keyword
def is_correct_variable_name(string: str) -> bool:
"""
Check if string is a valid variable name and is not a reserved keyword.
:param string: string to check
:return: True/False
"""
return string.isidentifier() and not keyword.iskeyword(string) | 68cf772b78ccaaafd8a22ea4db430a83868723f0 | 587,770 |
def premier(x):
"""
Prédicat indiquant si un nombre est premier
:param x: Nombre entier positif
:returns: True si l'entier `x` est premier, False sinon
"""
if x < 2:
return False
for y in range(2, x):
if (x % y) == 0:
return False
return True | 45b81789ceb561c7cbf07ae0608590ea83b9589c | 587,772 |
import itertools
def unpack_default(iterable, length=3, default=None):
"""
Unpacks given iterable maintaining given length and filling missing
entries with given default.
Parameters
----------
iterable : object
Iterable.
length : int
Iterable length.
default : object
... | e7770c53077ce35cfdf4ba92a4bb9708282e6f6a | 587,773 |
def coding_problem_02(l):
"""
Given an array of integers, return a new array such that each element at index i of
the new array is the product of all the numbers in the original array except the one at i.
Solve it without using division and in O(n).
Example:
>>> coding_problem_02([1, 2, 3, 4, 5... | b9dbe95f91a5607f284e929e80786f774facf873 | 587,777 |
def format_timedelta(td):
"""Format td in seconds to HHH:MM:SS."""
td = int(td)
hours, remainder = divmod(td, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:03}:{:02}:{:02}'.format(hours, minutes, seconds) | b8febccac40fe17a061e0cdba255b9a8b420cabb | 587,780 |
def InitItemMutator(*item):
"""Initialize an item in a dict/list if it does not exists or is None. If more than one item, create the full hierarchy"""
def m(current, value):
# plist, plast = item[:len(item)-1], item[len(item)-1]
plist, plast = item[:-1], item[-1]
if current is None:
... | b9810131230e600b94edf010745e1d39afe81cbd | 587,781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.