content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def despecced(text):
"""
Args:
text (str): Text of form <name>==<version>, or just <name>
Returns:
(str, str | None): Name and version
"""
version = None
if text and "==" in text:
text = text.strip()
i = text.index("==")
version = text[i + 2:].strip() or ... | 853976eb37444a9c205b2e8cc27afa6645beff62 | 585,961 |
def read_file(filename: str, mode: str = "r") -> str:
"""Read content from a file."""
with open(filename, mode) as file:
file_content = file.read()
return file_content | df114161faf53ec293ef4bf8be4d425a2972b229 | 585,962 |
def map_keys(func, dictionary: dict) -> dict:
"""
Map the keys of a dict
"""
return { func(key):value for key, value in dictionary.items()} | 73b1ce2044c08182638c71a3bf190deef60c08a9 | 585,963 |
import pkg_resources
def get_nmdc_schema_package_version() -> str:
"""
Returns the version of the nmdc_schema package.
Returns
-------
str
The version of the nmdc_schema package.
"""
return pkg_resources.get_distribution("nmdc_schema").version | 5fd2cfaa1d67c1d7ec5b00c48e0b466f9835feaf | 585,966 |
def find_all(tofind, string):
"""Returns number of times a certain substring is found"""
found = [i for i in range(len(string)) if string.startswith(tofind, i)]
num_found = len(found)
return num_found | a02b12e6a7f6a579624407f8678027fd6c17d458 | 585,967 |
def standardize_water(mol_traj):
"""Ensure that a water molecule has the correct MDTraj Topology.
The PDB format doesn't require CONECT records for a water molecule,
but MDTraj correctly recognize water molecules bonds only if they
adopt specific residue and atom names. This function standardize
th... | 0aaa5e1c71caa18c4b5ca3331f05130c6f4a4437 | 585,969 |
def episode_stats(env, policy):
""" Gather Episode Statistics - Just for Taxi Environment
Args:
env: ai gym environment
policy: policy object with sample() method
"""
obs = env.reset()
observes, actions, rewards = [], [], []
done = False
illegal_action_count = 0
success_... | 678df1672b21b28fc1b446f3724a86612cbb9ff9 | 585,970 |
def tri_reflect_x(a, b, c):
"""Reflects the given triangle through the y-axis
and returns the co-ordinates of the new triangle"""
return (c, b, a) | 869593a1e1e0d8cfdb8067e6d477b95219ed3948 | 585,972 |
def combine_to_id64(system, body):
"""
Combines a system ID64 and body ID to create an ID64 representing that body
Args:
system: An ID64 representing a system
body: A zero-indexed body ID
Returns:
A combined ID64 representing the specified body within the specified system
"""
return (system & (... | a35cd1cd477dedfe951984bb61b672aeec053a39 | 585,973 |
def _sorted_list(iterable, reverse=False):
"""
Transform an iterable to a sorted list.
"""
a = list(iterable)
a.sort()
if reverse:
a.reverse()
return a | f51fdc8961c51e4b120de43d002655fb53d1d0ea | 585,974 |
def count_file_lines(filename): # Might be a bit faster with a call to "wc -l"
""" Count the number of lines in a given file """
i = 0
with open(filename) as f:
for i, _ in enumerate(f, 1):
pass
return i | 18a9892a5393d67ed68680ce1012f3f8828d36ac | 585,977 |
def session_id_header(request):
"""Returns the HTTP_MU_SESSION_ID header from the given request"""
return request.headers.get('MU_SESSION_ID') | de93cd020318f88ac159424d1bb4c0f41a6bc54c | 585,979 |
def to_bool(value: str) -> bool:
"""
Converts a string argument to the bool representation (or throws a ValueError if the value is not
one of '[Tt]rue' or '[Ff]alse'.
"""
if value in ["True", "true", True]:
return True
if value in ["False", "false", False]:
return False
raise... | 579df9985701e8081e8c753206c72d2c0afc6851 | 585,981 |
def mask(n: int) -> int:
"""
Return a bitmask of length n.
>>> bin(mask(5))
'0b11111'
"""
return (2 << (n - 1)) - 1 if n >= 0 else 0 | 65aa70047ddc22d965591e12f4eff35227a97027 | 585,982 |
import torch
def pairwise_squared_distance_matrix(x):
"""Pairwise squared distance among a matrix's rows.
This saves a bit of computation vs. using cross_squared_distance_matrix(x,x)
Args:
x: `[n, d]` float `Tensor`
Returns:
squared_dists: `[n, n]` float `Tensor`, where
squa... | af74b2360af8de7db7541820e91dacfe832ec32e | 585,988 |
def get_dashboard_choices(api_response):
"""
Given a response from the Grafana API, find a list of dashboard name choices
:param api_response: response data from the Grafana API
:return: list of dashboard URIs and names
"""
return [(dash['uri'], dash['title']) for dash in api_response] | fdafd13abfe3390311a1e870cb9dab38e1c53d12 | 585,992 |
def turn(facing, direction):
"""Returns the new facing given a cardinal facing and a left/right direction"""
clockwise = "NESW"
if direction == "L":
facing = clockwise[(clockwise.index(facing) - 1) % 4]
if direction == "R":
facing = clockwise[(clockwise.index(facing) + 1) % 4]
return... | 6ea8de37ba769400838a0d0cdd30768de954bf35 | 585,993 |
def sign_in_handler(sender, message, bot_id, app_id):
"""Return attendance google form"""
if '!attendance' in message:
return "https://docs.google.com/forms/u/0/d/e/1FAIpQLScYQDbMuOAH4EVpUlCAPxRhmPMJGXoYnR0Loo3fIrDzp6ZgTg/formResponse"
return None | 140323cab7d89442d2ef286dff64e90835bdf5e9 | 585,998 |
def calc_diff(frame0, frame1):
"""
Calculates the difference image between two frames.
"""
im = frame1 - frame0
im = im/2./255. # Scaling
im += 0.5 # Shift the no change to gray value.
return im | 699c49fc8860bd0da88bd47485a82437461ad007 | 585,999 |
import re
def load_config(file):
""" Load a config file of the format key=value. """
config = {}
f = open(file, 'r')
for line in f.readlines():
if re.match("\s*$", line) or re.match("\s*\#", line):
continue
m = re.match("\s*(\S+)\s*=\s*(.+)$", line)
if m:
... | 56dfce8332453d3357c74c0f27af6b229eae6196 | 586,000 |
import json
def load_hyp(filepath):
"""
Load hyper-parameters from filepath
Args:
filepath: filepath of .json file loaded into dict.
Returns:
dict: hyper-parameters
"""
with open(filepath, 'r') as f:
return json.load(f) | e567e1b68c1c54fac699ced55e9ba9f93702feed | 586,003 |
def _squeeze_output(out):
"""
Remove single-dimensional entries from array and convert to scalar,
if necessary.
"""
out = out.squeeze()
if out.ndim == 0:
out = out[()]
return out | b9314de44d8c40530518848ca0108ad778573101 | 586,010 |
from typing import Dict
from typing import List
def _compare_dict(old: Dict, new: Dict, keys: List[str]) -> bool:
"""Function for comparing a flat dictionary across specified keys
:param Dict old: baseline dict
:param Dict new: comparative dict
:param List[str] keys: The keys to compare
:return:... | 6360bf5ab2df2a20cf0283c64a8f958a4c6285ee | 586,012 |
def normalized_error(value_1,value_2,uncertainty,expansion_factor=1):
"""normalized error returns the scalar normalized error (delta value/ (expansion_factor*uncertainty))"""
return (value_2-value_1)/(uncertainty*expansion_factor) | 8f1604c72adf9796dc25059310980c7fbd47b973 | 586,013 |
import base64
def b64encode(s: str):
"""
Encode a string *s* to base64
"""
return base64.b64encode(s.encode("ascii")).decode("ascii") | b4fca7b6562ce32baa932e9dea87234b766a7a47 | 586,014 |
def mat_splice(matrix, r, c):
"""
Function which returns a matrix with the first r rows and first c
columns of the original matrix
"""
result = list()
for i in range(r):
row = matrix[i]
result.append(row[:c])
return result | 38ef44bce0291afcebc75082e5295e2db3f5e751 | 586,017 |
def set_entry_attribute(entry, attribute, value, overwrite=False):
"""Set an entry attribute."""
if value and (not getattr(entry, attribute) or overwrite):
entry = entry._replace(**{attribute: value})
return entry | e44de5f10d2178f8c340a128fbc8a21474efab5c | 586,020 |
from typing import Counter
def removeSingles(data, hosts, labels, target_class):
"""
Remove entries from the dataset where the tactic/technique only occurs once.
GIVEN:
data (list) list of events
hosts (list) one of ["Attacker", "Victim"]
labels (dict) human-a... | 31d13eac0b6e745342cb8e7f257d271916f0a74a | 586,024 |
def overlapping_in_bed( fname, r_chr, r_start, r_stop ):
"""
Get from a bed all intervals that overlap the region defined by
r_chr, r_start, r_stop.
"""
rval = []
for line in open( fname ):
if line.startswith( "#" ) or line.startswith( "track" ):
continue
fields = lin... | dd1e42dac4c53c3e1741393a40c87c318cb57650 | 586,027 |
def activation_channels_apoz(activation):
"""Calculate the APoZ of each of an activation's channels.
APoZ is the Average Percentage of Zeros (or simply: average sparsity) and is defined in:
"Network Trimming: A Data-Driven Neuron Pruning Approach towards Efficient Deep Architectures".
The activation u... | 72ae832075ed4ef37e0a64383dddf9a30f2c1735 | 586,029 |
import json
def better_object(parser: dict):
"""Converts the json object to a more readable object.
Parameters
----------
parser : dict
Returns
-------
str
deserialized json as string
"""
return json.dumps(parser, sort_keys=True, indent=4, ensure_ascii=False) | 0e2a6b8dc60b54c6a320b5249867b6397d133276 | 586,032 |
def create_tables(name,string_columns):
"""Returns string used to produce
CREATE statement.
Parameters
----------
name : string
indicates the name of the table to create.
string_columns : string
list of columns to create.
Returns
-------
query : string
"""
c... | 963c1760955c1feda9ab89b0d01e21737a45d5f5 | 586,033 |
import json
def parse_user_seq(line):
"""Parses a sequence of ids from a line of the ml_user_sequences dataset."""
sequence_string = line.strip('()').split(',', 1)[1]
return json.loads(sequence_string) | f1bf2e8a0233b27d28f927fcc19395276f571566 | 586,035 |
import inspect
import functools
def wrap_decorator(fn, index=None):
"""
Returns a version of the function wrapped in such a way as to allow both decorator and non-decorator syntax.
If the first argument of the wrapped function is a callable, the wrapped function is called as-is.
Otherwise, returns a... | a1b4d7a7824795cd73fe3811eebbf64a25071166 | 586,038 |
import json
def _my_service_function(meth, param1, param2):
"""This is an example function.
:param param1: Input Genome
:type param1: kbtypes.Genome
:ui_name param1: Genome ID (what the user sees)
:param param2: Some text
:type param2: kbtypes.Unicode
:ui_name param2: Text
:return: Wo... | 4dc5ebdb68701f97d1d59e0b86ea06fbb9e99699 | 586,042 |
def gen_title_rst(txt):
""" Generate rst title from a cmake comment. """
# Just add a few useful directives
txt = ".. highlight:: cmake\n\n" + txt
return txt | 0fe2daa2b3c5514bcea0a7f62cf9fc07c98946e1 | 586,049 |
def repo_visibility(repo):
"""Convert repo to its visibility attribute as string
:param repo: Repository to show its visibility as string
:type repo: ``repocribro.models.Repository``
:return: Text representation of repo visibility
:rtype: str
"""
if repo.is_public:
return 'Public'
... | a63670502e6f36fcb4189d383b9e6876272811a6 | 586,051 |
def reverse_lookup(D, val):
"""
Find all keys in a dictionary D with the specified value.
"""
if type(D) != dict:
raise TypeError("First argument must be a dictionary")
return [key for key in D.keys() if D[key] == val] | b2937b173d6c774aba78bde8bd4ebd8a0d6c808d | 586,052 |
def axis_slice(a, start=None, stop=None, step=None, axis=-1):
"""Take a slice along axis 'axis' from 'a'.
Parameters
----------
a : numpy.ndarray
The array to be sliced.
start, stop, step : int or None
The slice parameters.
axis : int
The axis of `a` to be sliced.
E... | 7accdbead466e0e775d4e0398fbb0365e5603aab | 586,056 |
def _render_text_module_mapping(mapping):
"""Renders the text format proto for a module mapping.
Args:
mapping: A single module mapping `struct`.
Returns:
A string containing the module mapping for the target in protobuf text
format.
"""
module_name = mapping.module_name
prot... | a1f0e79fafeba5664e5c79327bf7d75f419477b7 | 586,060 |
import shlex
def ResolveRspLinks(inputs):
"""Return a list of files contained in a response file.
Args:
inputs: A command containing rsp files.
Returns:
A set containing the rsp file content."""
rspfiles = [a[1:] for a in inputs if a.startswith('@')]
resolved = set()
for rspfile in rspfiles:
... | d03a866a89b54ad05336c2f4a6be1570a5546bfb | 586,061 |
import torch
def gaussian_loss(z, mu, sigma):
"""
Calculate the negative log-likelihood of a given sample Y for a Gaussian with parameters mu and sigma.
Note that this equation is specific for a single one-dimensional Gaussian mixture component.
:param z: Target sample
:param mu: Mean of the Gauss... | 499699ef2965e0968b133acd2c0b3ea31d27a0f3 | 586,062 |
def validate_eye_color(passport: dict) -> bool:
"""
Return True if value of eyecolor is equal to amb blu brn gry grn hzl oth
DOCTEST
>>> validate_eye_color(passport={"ecl": "brn", "byr": "1937"})
True
>>> validate_eye_color(passport={"ecl": "wat", "byr": "1937"})
False
"""
eye_col... | c2372fad971e4aa5f1a7770facd59285f96a7480 | 586,063 |
def fitness_metric(agent, environment, raw_fitness, path):
""" Returns the raw fitness of an agent evaluation. """
return raw_fitness | 1b6f255f4eb33d739c56a090fca0c0044edfe2e6 | 586,070 |
def wrap_qmes(qmes):
"""Converts qmes into a dict of {q:{m:e}}"""
d = {}
for q, m, e in qmes:
if q not in d:
d[q] = {}
d[q][m] = e
return d | e48f64a839cd6f00316497b6b906efdc16a7a2f3 | 586,075 |
def get_name(index):
"""
排序用的辅助函数
:param index:
:return: index对象的name属性值
"""
return index.name | 07c00c6c4b62c040cdba70509928c604fcb412d2 | 586,078 |
def secs_to_text(secs):
""" Convert number of seconds to human string - *d*h*m*s """
secs = int(secs)
min_time = 60
hour_time = 3600
day_time = 3600*24
days = 0
hours = 0
mins = 0
if secs >= day_time:
days = int(secs / day_time)
secs = secs % day_time
if secs ... | a6a523e28907db39c147c34752a5d3b32a156323 | 586,085 |
def get_unnamed_cols(df):
"""
Get a list of all unnamed columns, used to drop them.
:param df:
:return:
"""
return [col for col in df.columns if "Unnamed" in col] | 9b02a69f716faf4d01d526b377d427b1f63a45f9 | 586,086 |
def running(demo_mode, step, max_step):
"""
Returns whether the demo should continue to run or not. If demo_mode is
set to true, the demo should run indefinitely, so the function returns
true. Otherwise, the function returns true only if step <= max_step
:param demo_mode: true if running in demo mod... | b4c01cd714cbde6f2ff31a442376d3dc090e39f1 | 586,087 |
def sign(x):
"""
Objective: take the sign of x
e.g.,
>>>sign(-1.2)
-1
>>>sign(5)
1
"""
if x>0: return 1
elif x<0: return -1
else: return 0 | 795b8813b95321168de5b7fc5d84b5b474325062 | 586,096 |
def freq(series, value):
"""
Takes a pandas series and a value and returns the fraction of the series that presents a certain value.
"""
Ntotal = len(series)
Nsel = float(len(series.loc[series==value]))
return Nsel/Ntotal | b1259eba64178889e76d0dacf3eca66118ccdbc9 | 586,099 |
import unicodedata
def run_strip_accents(text):
"""
统一字符串中的字母表示方法,并去除无法处理的特殊字符
:param text: str
:return: str
"""
text = unicodedata.normalize("NFD", text) # 文本标准化,统一相同字符的不同表示
output = []
for char in text:
cate = unicodedata.category(char) # Mark, Nonspacing
if cate =... | 5945ffe13f2a5a21e7d90a21c659194e3b3136e7 | 586,100 |
def physOrgNewsFilter(href):
"""Determine if PhysOrg article or other link instead
"""
return(href.startswith('http://phys.org/news/')) | 8a4e0027c46bce794fda21378d669a0c9d66a6ed | 586,102 |
def hex_fig(n, uppercase=True):
"""
Return the hexadecimal figure of `n`.
:param n: 0 <= int < 16
:param uppercase: bool
:return: str (one character from 0123456789ABCDEF or 0123456789abcdef)
"""
assert isinstance(n, int), type(n)
assert 0 <= n < 16
assert isinstance(uppercase, boo... | 47b7b2af2e3b047b1bd0dd707ec007e7d83592a1 | 586,103 |
def break_down_filename(image):
"""
filename: g04i2c08.png
|| ||||
test feature (in this case gamma) ------+| ||||
parameter of test (here gamma-value) ----+ ||||
interlaced or non-interlaced --------------+|||
color-type ... | ad191464538c8270594ea016daa680dce52c9638 | 586,105 |
def convert_to_html(txt, num=-1):
"""
Convert a line of a csv file to a line of an html table
:param txt: a String containing a line from a csv file
:param num: an integer identifying which line this is (starting at 0)
:return this_line: A line of an html table equivalent to txt
"""
this_lin... | 0965d9b19a010cd6731caf7b31d088520b9fa5c4 | 586,106 |
def in_purchases_auth(user, recipe):
"""Check if a recipe is in purchases."""
return recipe.purchases.filter(user=user).exists() | a5f38db82851995bb1e1554c222a070bbbb87422 | 586,107 |
import re
def title_to_slug(book_title: str) -> str:
"""Converts a book title to an alphanumeric slug."""
book_slug: str = book_title.lower()
book_slug = book_slug.replace(" ", "qqq")
book_slug = re.sub(r'\W+', '', book_slug)
book_slug = book_slug.replace('qqq', '_')
return book_slug | 5241ef7d263540208b3ae38500040bbd152f4cd9 | 586,115 |
def drange(min_, max_):
"""Generate list of float values in a specified range.
Parameters
----------
min_ : float
Min value
max_ : float
Max value
Returns
-------
range_ : list
list of float values in the min_ max_ range
"""
step = float(max_ - mi... | 381876c460f51ce9d896132bcbf29faec9488593 | 586,119 |
def nice64(src):
""" Returns src base64-encoded and formatted nicely for our XML. """
return src.encode('base64').replace('\n', '') | 39a0d4359215e546d7a7c98d23822b7b6b8e716a | 586,123 |
def get_robot_speeds(wl, wr, r, d):
"""Computes robot linear and angular speeds"""
u = r/2.0 * (wr + wl)
w = r/d * (wr - wl)
return u, w | 2282d77485bac78a51053c4e7dc9431e9fd7e543 | 586,127 |
from datetime import datetime
def naive(dt: datetime) -> datetime:
"""Remove the timezone from a datetime instance."""
return datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute,
dt.second, dt.microsecond) | b8211333ae8112687dba6b654a5a3cd1412d7490 | 586,130 |
def get_motioneye_entity_unique_id(
config_entry_id: str, camera_id: int, entity_type: str
) -> str:
"""Get the unique_id for a motionEye entity."""
return f"{config_entry_id}_{camera_id}_{entity_type}" | 9026153254ab4fdc94ba2b3d8ff1cdd20910ed94 | 586,131 |
def get_segment_coordinates(center, segment_length, sequence_length):
"""Return max(0, c - s/2) - min(L, c + L/2).
Where c=center, s=segment_length, L=sequence_length.
"""
half = int(segment_length / 2)
start = max(0, min(center - half, sequence_length - segment_length))
end = start + segment_... | fea310cb82b410bad24047b0b3e0bcd790717543 | 586,132 |
def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if js is None:
return default
if key not in js:
return default
... | b38ea51a87b426b31d3f51af3572fdd677408a37 | 586,134 |
def insert_cpf(a):
"""
Cast a string of digits to the formatted 000.000.000-00 CPF standard.
"""
cpf = a[:3]+'.'+a[3:6]+'.'+a[6:9]+'-'+a[9:]
return cpf | 04e1d19259222123530c88f406b8f24ec0ea5126 | 586,138 |
def extract_date_from_config_string(configString):
"""Takes a string of a date as written in a Cisco configuration file and extracts the usable parts of it"""
splitString = configString.split(' at ')[1].split(' by ')[0]
dateEnd = ' '.join(splitString.split(' ')[2:])
dateStart = ''.join(splitString.split... | a36eda2f19e3f54e2bae4726e58b93e980369830 | 586,139 |
import torch
def laplace_cdf(s, beta, noise_std = 0):
"""CDF of the Laplace distribution with zero mean and beta scale."""
beta_recip = 1. / beta
x = s * beta_recip
if noise_std:
x = x + noise_std * torch.randn(x.shape, dtype=x.dtype, device=x.device)
return torch.sigmoid(x) | a42b3fcd20b7d87c5719bd60455ab2f2799fe7f3 | 586,142 |
def stackhunter(cookie = 0x7afceb58):
"""Args: [cookie = 0x7afceb58]
Returns an an egghunter, which searches from esp and upwards
for a cookie. However to save bytes, it only looks at a single
4-byte alignment. Use the function stackhunter_helper to
generate a suitable cookie prefix for you.
Th... | 8c405fee5b7432a57b2a8ef8f50d293d9a3d9906 | 586,143 |
def get_bucket_and_object(resource_name):
"""Given an audit log resourceName, parse out the bucket name and object
path within the bucket.
Returns: (str, str) -- ([bucket name], [object name])
"""
pathparts = resource_name.split("buckets/", 1)[1].split("/", 1)
bucket_name = pathparts[0]
... | 777a63f6380a22e70e94c564fbecc04bf74d9754 | 586,144 |
from typing import List
def group_anagrams(strs: List[str]) -> List[List[str]]:
"""
LeetCode 49: Group Anagrams
Given an array of strings, group anagrams together.
"""
str_map = {}
res = []
for s in strs:
temp = ''.join(sorted(s))
if temp not in str_map:
str_map... | 847b448f194d798bbc5f201c2864cd1dd0d6c40c | 586,147 |
def img_src_finder(pipeline_index,
soup,
finder_image_urls=[],
*args, **kwargs):
"""
Find image URL in <img>'s src attribute
"""
now_finder_image_urls = []
for img in soup.find_all('img'):
src = img.get('src', None)
if src:
... | 75e24e182e6cb2dcaf4f4e8dc95d1206fec4f998 | 586,150 |
import random
def create_random_list(list):
""" Create a random list of up to 20 integers between 1 and 20. """
for i in range(0, random.randint(1, 20)):
n = random.randint(1, 21)
list.append(n)
return list | a0da6875a32667632f1394a3e1c7f95c82dc5783 | 586,151 |
from typing import MutableMapping
def flatten(d, parent_key="", sep="_"):
"""
Flatten dictionary by compressing keys.
See: https://stackoverflow.com/questions/6027558/
flatten-nested-python-dictionaries-compressing-keys
d : dictionary
sep : separator for flattening keys
Returns
... | 279bdd62f5eb57a3207ad18037190eb1dda18bda | 586,157 |
def signum(number):
"""Self-explanatory."""
if(number < 0): return -1
elif(number > 0): return 1
else: return 0 | 499880f21eeb922ed443a566c29674fc267c47fa | 586,158 |
def istr(value):
"""
Utility for returning a str representation of the given value.
Return '-' if value is None
@parem value : the given value that need to be converted to string
"""
if value is None:
return "-"
return str(value) | 883dec0e1be8b58823a4bacfaef7054ef1fcb0f7 | 586,160 |
def insitu_xtl(Cl, D, F, f, fa):
"""
insitu_xtl calculates the concentration of the remaining melt as described
in Langmuir (1989) and Rollinson 1993 Eq. 4.21 whereby crystallization
predominantly takes place at the sidewalls of a magma reservoir. Rather than
crystals being extracted from the liqu... | 524346673fa1d66364e44a56ec32ef2faa142def | 586,161 |
def verify_social_media_platform(platform_name: str) -> bool:
"""
A helper function to make verifying social media platform strings easier
Parameters
----------
platform_name: str
The name of the social media platform to be verified.
Valid inputs are: 'f', 't', 'i', 'a'
Returns... | c6a52430ff5c2d0c6bf71fe3d8717b7628ccc897 | 586,164 |
def _get_class_type(cls):
"""
type(cls) has an inconsistent behavior between 3.6 and 3.7 because of
changes in the typing module. We therefore rely on __origin__, present only
in classes from typing to extract the origin of the class for comparison,
otherwise default to the type sent directly
:p... | cfbe2233cad2c7669de85d1679c094e985360731 | 586,165 |
import re
def clean_line(description):
"""Formats catapult-server custom tags into readable strings.
Args:
description (str): Line to format.
Returns:
str: Formatted line.
"""
description = re.sub(r'\\c ([a-zA-Z_]*)', r'<code class="docutils literal"><span class="pre">\1</span></... | dd5afe88eb4b0bc2f71689a45a02e781b591a65a | 586,169 |
def translate(value, from_min, from_max, to_min, to_max):
"""
Translates the value passed as a parameter into a corresponding value
in the right range.
"""
# Figure out how 'wide' each range is
left_span = from_max - from_min
right_span = to_max - to_min
# Convert the left range into a ... | 87badc426496ca8b6e130b602be3c81988386ed5 | 586,174 |
def get_scilife_to_customer_name(project_name, p_con, s_con, get_barcode_seq=False):
"""Get scilife to customer name mapping optionally with barcodes, represented as a
dictionary.
:param project_name: project name
:param p_con: object of type <ProjectSummaryConnection>
:param s_con: object of type ... | 9b2346d3bc1de94c42f5321651b0b4828e8100de | 586,175 |
import hashlib
def create_hash_id(input):
"""
Creates hash identifier.
Parameters
==========
input : str
Input to be hashed to form an identifier.
Returns
=======
hash_id : str
Identifier formed by hashing the inputs.
"""
input_bytes = bytes(input, encoding="u... | e9319728a58b9afc947bb2ddc6fc3701d7ec861a | 586,177 |
from functools import reduce
import operator
def product_sequence(series, f):
"""Calculates the product sequence of a `series` of numbers
aka "Capital-pi notation"
Π(f(n)) = f(k0) * f(k1) * f(k2) * ... * f(kn)
https://en.wikipedia.org/wiki/Arithmetic_function#Notation
"""
values = (f(value)... | 20cbbb1dd72978e837656b215a3aad63c071b628 | 586,179 |
import binascii
def string_to_hex(val: str, min_length: int = 0) -> str:
"""
Create a hex representation of val. The end of the result will be padded
with "0" until min_length is reached.
Args:
val: The string to convert.
min_length: The minimum length of result. "0" will be used as
... | 224f84d3b972d1ad653f10aab295c546b3cdd7d0 | 586,187 |
def manhattan(pos1, pos2):
"""
Función para calcular la distancia manhattan entre
dos coordenas de una matriz
:param pos1: primera coordenada
:type pos1: Tuple[int, int]
:param pos2: segunda coordenada
:type pos2: Tuple[int, int]
:rtype: int
:return: distance
"""
di... | ce771c9f8f126f1262573cfc2013ebb46d24c8a0 | 586,188 |
import re
def _regex_or(options):
"""Create a regex pattern matching any of the provided strings."""
# An or joining non capturing groups of escaped strings
clause = "|".join(f"(?:{re.escape(part)})" for part in options)
if len(options) > 1:
# Wrap the whole thing in another non-capturing gr... | fd71e000563b2f8438ce4101192501104d4313ec | 586,189 |
def get_beta_parameters(confusion):
""" Extract the beta parameters from a confusion matrix.
Parameters
----------
confusion : array, shape = [n_classes, n_classes]
Where entry c_{ij} is the number of observations in class i but
are classified as class j.
Re... | 28864b1c1c1f15b9cbfb571c995e6e7689ef26cc | 586,190 |
def sets_to_mapping(s):
"""
Input: {cluster_name: set([cluster_items])} dictionary
Output: {cluster_item: cluster_name} dictionary
"""
return {m: k for k, ms in s.items() for m in ms} | b9ee3aa9cfaf47a0bc956ddc0a53ae16d51d269b | 586,194 |
import keyword
def safe_names(names):
"""
Receive a list of names and return a map from names to the corresponding
safe name to use as a Python variable.
"""
safe_names = {}
for name in names:
safe_names[name] = name + "_" if keyword.iskeyword(name) else name
if len(safe_names) != ... | 3c72883fc6c5c71f7c4be3b75fc7674be17bb47b | 586,196 |
import pickle
def load_tfidf(vectorizer_path: str, wm_path: str):
"""Loads the stored TF-IDF objects
Args:
vectorizer_path (str): Path to the vectorizer .pickle file
wm_path (str): Path to the word model .pickle file
Returns:
tuple: A tuple of the tfidfvectorizer and tfidf_wm obj... | c02888faf02fc41dd7d3862f0ec6d9cdfa52e598 | 586,197 |
def count_lines(filename):
"""Counts and returns how many non empty lines in a file there are."""
with open(filename, 'r') as f:
lines = [x for x in list(f) if x.strip()]
return len(lines) | 44fd24cfc7c9497a5d1e1d9dfd48127867402aff | 586,199 |
import hashlib
def get_s3_folder_prefix(iiLocalName, igLocalName):
"""
gives the s3 prefix (~folder) in which the volume will be present.
inpire from https://github.com/buda-base/buda-iiif-presentation/blob/master/src/main/java/
io/bdrc/iiif/presentation/ImageInfoListService.java#L73
Example:
... | ae1f0b05cf3ccbcc9723096cabc05e4c5359968b | 586,201 |
def get_face_ids(oEditor, body_name):
"""
Get the face id list of a given body name.
Parameters
----------
oEditor : pywin32 COMObject
The HFSS editor in which the operation will be performed.
body_name : str
Name of the body whose face id list will be returned
... | 4547e0ad98ea031748c9d55ec1928bb3751947c4 | 586,203 |
def mock_any(cls):
"""Returns Any class to use in mock."""
class Any(cls):
"""Any class used for mocks."""
def __eq__(self, other):
return True
return Any() | e08f4ae7f0f0b72716afcd9755f465a4c0906e4e | 586,206 |
def attrsetter(attr_name):
"""
attrsetter(attr) --> attrsetter object
Return a callable object that sets the given attribute(s) on its first
operand as the second operand
After f = attrsetter('name'), the call f(o, val) executes: o.name = val
"""
def _attrsetter(obj, val):
setattr(o... | ae06878be25402bfb02bab3804c6889f6cd9ef37 | 586,207 |
def reverse_string(s):
"""Returns the reversal of the given string."""
result = ""
for char in s:
result = char + result
return result | d7cd04ce1183e04ce36f338eb342c6734e1826fc | 586,209 |
def apply_all_funcs (value_tuple, funclist):
"""Returns True is any one of the functions
in funclist returns True when applies to x and y
"""
x = value_tuple[0][-1][-1]
y = value_tuple[1]
for f in funclist:
if f(x,y):
return True
return False | 4d34ebf699287fd7b9d61d5b6ee92c65d2ce066d | 586,210 |
async def show(*args, **kwargs):
"""Dummy show function that always cancels (returns None)"""
return None | 2686113b8ca570e54288d7dcd6fe858c7acc4572 | 586,217 |
import pathlib
def get_domain(prog, fpath):
"""Return the domain from the input path.
Will extract a domain from the full path input (of a X.509 cert file)
as the Let's Encrypt directory the certificate is in, rather than, say,
the domain(s) defined in the certificate itself. Anything other than a
... | 8418d1ee10bebf1ec3a89b87d97e3ec688c2fa2b | 586,218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.