content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def fill_median(df):
"""Fill NaN with median."""
df = df.fillna(df.median().fillna(0).to_dict())
return df | b5ba61c19fae87c61f484c0431798abf7db5bd69 | 457,406 |
def find_tag(text, tag, start):
""" Tuple `(start, end)` of `tag` in `text` starting at `start`.
If `tag` is not found, `(-1, end)` is returned.
"""
i = text.find(tag, start)
j = i + len(tag)
result = (i, j)
return result | 8f25fb59130fab091060b0d33a06ad613686baf4 | 389,064 |
def dataframe_tptnfpfn(df, pos_label=True, labels=None):
"""Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2)
>>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]]
>>> columns=['Cat', 'Dog', 'Rabbit']
>>> x = np.array([[tc, pc] for (tc, row) in e... | 00a1f59c7699f375c088f86825b3a29076bc1fda | 576,936 |
def _get_metric_prefix(power: int, default: str = "") -> str:
"""Return the metric prefix for the power.
Args:
power (int): The power whose metric prefix will be returned.
default (str): The default value to return if an exact match is
not found.
Returns:
str: The metri... | b35f5ff3691eafe87274a685d41f9c57161df1fb | 44,060 |
def append_to_title(title: str, append_title: str) -> str:
"""
Append a title to a title avoiding duplication in title text, i.e. 'Steps Steps'.
:param title: Title to append to.
:param append_title: Other title to append to the title.
:return: The appended title without title duplication.
"""
... | f661fbe8d04be9b9d6a83bbfc019fec66ec630c2 | 365,292 |
def nsecs_to_timespec(ns):
"""Return (s, ns) where ns is always non-negative
and t = s + ns / 10e8""" # metadata record rep (and libc rep)
ns = int(ns)
return (ns / 10**9, ns % 10**9) | b1e8d9bf5804b9d1f59a3046ae33ebda577a197f | 151,491 |
def fill_with_none(df, *cols):
"""
This function fills the NaN values with
'None' string value.
"""
for col in cols:
df[col] = df[col].fillna('None')
return df | 547103126a2ebba05c9492b4edbf688dea31824e | 512,039 |
def polynomiale(a : int, b : int, c : int, d : int, x : int) -> int:
"""Retourne la valeur de a*x^3 + b*x^2 + c*x + d
"""
return (a*x*x*x + b*x*x + c*x + d) | e54035ccb18c2257b754dcfbd77f756b464a0c76 | 250,237 |
def enforce_string(func):
"""
Decorator to enforce a string argument.
"""
def wrapper(self, *args):
if type(args[0]) is not str:
raise ValueError("Invalid type provided. Must be a string.")
func(self, *args)
return wrapper | 2029596c1d4f72de040b66ec38556906206bdc01 | 555,605 |
def get_text(xml, tag):
"""Return the text from a given tag and XML element.
"""
elem = xml.find(tag)
if elem is not None:
return elem.text.strip() | ece7c28a98f8bf61a3d182a2109875b6a031dbaa | 699,964 |
from typing import Optional
def unflatten_dict(dict_: dict, separator: Optional[str] = ".") -> dict:
"""Unflattens a dictionary, reveres `flatten_dict`
Args:
dict_: The dictionary to unflatten
separator: The sepearator that was used to flatten the dict
"""
result_dict = {}
for ke... | 61e6288c2b22535cfad438bbb3cfa241676a51a4 | 265,185 |
from typing import Any
import json
def loads(data: str, **kwargs: Any) -> Any:
"""
Alias for `json.loads`.
Arguments:
data -- A string with valid JSON.
kwargs -- List of additional parameters to pass to `json.loads`.
Returns:
An object created from JSON data.
"""
retu... | ab1c081c630cf339d3a2674258d77b12bc2578f7 | 66,301 |
def almost_zero(x, atol: float = 1e-6):
""" Returns true if `x` is within a given tolerance parameter """
return abs(x) < atol | 44d869c4c47415371784eca4073bb0a2c4033eb3 | 152,722 |
def is_space_free(board, move):
"""Return true if the passed move is free on the passed board."""
return board[move] == ' ' | 5d2ebdc6747237448989bf6abf215b2c53c570d2 | 683,160 |
def masked_average(tensor, mask):
""" Performs masked average of a given tensor at time dim. """
tensor_sum = (tensor * mask.float().unsqueeze(-1)).sum(1)
tensor_mean = tensor_sum / mask.sum(-1).float().unsqueeze(-1)
return tensor_mean | 820d2ac679afba3a13841943afae050a22f7e354 | 253,988 |
def check_version_2(dataset):
"""Checks if json-stat version attribute exists and is equal or greater \
than 2.0 for a given dataset.
Args:
dataset (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
... | bfc86b4d16750379a6ad9325f13ac267c0f414a3 | 641,350 |
import time
def timer(function):
"""Print the duration of a function making use of decorators."""
def function_(*args,**kwargs):
"""Tested function."""
ti=time.time()
result=function(*args,**kwargs)
tf=time.time()
dt=tf-ti
print("[TIMER]: "+str(function.__name__... | 93ab39c5760c73c535c44ac6d0c33d80f731af87 | 312,574 |
def aumentar(n, p):
"""
Somar porcentagem
:param n: número a ser somado
:param p: porcentagem a ser somada
:return: resultado
"""
n = float(n)
resultado = n + (n * p / 100)
return resultado | 80267aa21e9498696b490227c7f6a735a4b8c6b1 | 291,138 |
def Factorial(number:int):
"""
Calculate the factorial of a positive integer
https://en.wikipedia.org/wiki/Factorial
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: factor... | bd2580a86b465ad7205ecb1a4dfacde94bb301a5 | 471,897 |
def get_geometry(dataset):
"""
Extract and return geometry coordinates as a list in a dictionary:
returns
{
'geometry': {
'type' : 'Polygon',
'coordinates': [...]
}
}
or
empty dictionary
"""
valid_data = dataset._gs.get... | 5c149eaf29c99bf699e9014f60d00c039d6c6792 | 565,894 |
def get_backend_bucket_outputs(res_name, backend_name):
""" Creates outputs for the backend bucket. """
outputs = [
{
'name': 'name',
'value': backend_name
},
{
'name': 'selfLink',
'value': '$(ref.{0}.selfLink)'.format(res_name)
}
... | 45fd59e7e9c5bb4a13e05ea45283338bee125843 | 91,343 |
def generate_absolute_parameter(parameter_values):
"""Generate parameters list for absolute parameter type."""
return parameter_values | 0d9d587f17e5ef7d2f3c89a3ae03bf7eafb9ae78 | 606,626 |
def makecard (name, front, back):
""" Convert captured data for a flashcard into a dictionary
Helper for md2json() function, which converts flashcard entries from
Markdown to JSON. We allow several different ways to enter
the flashcard entries in Markdown, and this function
handles identifying those cases a... | f97c166bcea00ee46eed134284e65538fb160b3a | 190,661 |
def hsv_to_rgb(h, s, v):
"""Convert HSV values RGB.
See https://stackoverflow.com/a/26856771.
:param h: Hue component of the color to convert.
:param s: Saturation component of the color to convert.
:param v: Value component of the color to convert.
:rtype: tuple
""... | 0b74f5ccbff722a139bea316c41f644aa2d7a36d | 651,468 |
def _parse_logline_timestamp(t):
"""Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond.
"""
date, time = t.split(' ')
month, day = da... | 9b0ea2f6cfe4edef89eec6dbbddbdd258640c210 | 692,957 |
def response(status, data=''):
"""
Returns dictionary which is the response for the request.
The dictionary contains 2 keys: status and data.
"""
d = {}
d['status'] = status
d['data'] = data
return d | 207724cc64e2092fa1b65aafaf369ce9a8133d1d | 196,527 |
def distance_score(pos1: list,
pos2: list,
scene_x_scale: float,
scene_y_scale: float):
"""
Calculate distance score between two points using scene relative scale.
:param pos1: First point.
:param pos2: Second point.
:param scene_x_scale: X s... | aa5b13f4aba6d8b9831d794d8d377610c5508896 | 493,172 |
def delete_zero_amount_exchanges(data, drop_types=None):
"""Drop all zero value exchanges from a list of datasets.
``drop_types`` is an optional list of strings, giving the type of exchanges to drop; default is to drop all types.
Returns the modified data."""
if drop_types:
dont_delete = lambd... | 8e9c214826398959b74e7bffc1e41ea635172d0a | 692,439 |
import traceback
def get_plot_frame(map_obj, key_map, cached=False):
"""
Returns an item in a HoloMap or DynamicMap given a mapping key
dimensions and their values.
"""
if map_obj.kdims and len(map_obj.kdims) == 1 and map_obj.kdims[0] == 'Frame':
# Special handling for static plots
... | 8746d78ac462d19d92b2d89bffdea0fe85c30a1d | 436,090 |
def _get_slice_len(idx):
"""
Get the number of elements in a slice.
Parameters
----------
idx : np.ndarray
A (3,) shaped array containing start, stop, step
Returns
-------
n : int
The length of the slice.
Examples
--------
>>> idx = np.array([5, 15, 5])
... | 39ab973ba9c6d41a6bab9478df1f3e0dd0f8888d | 496,666 |
def _ConditionHelpText(intro):
"""Get the help text for --condition."""
help_text = """
{intro}
*expression*::: (Required) Expression of the condition which
evaluates to True or False. This uses a subset of Common Expression
Language syntax.
*title*::: (Required) Title for the expression, i.e. a short string
desc... | 3899206fc5bb60c6dec9bc0fc58dcce80cb0799b | 653,663 |
def word_list_to_string(word_list, delimeter=" "):
"""Convert a list of words to a sentence.
"""
string = ""
for word in word_list:
string+=word+delimeter
nchar = len(string)
return str(string[0:nchar-1]) | 46a532a96429c61098fae12ac8995306cda9c586 | 418,215 |
def xml_get_attrs(xml_element, attrs):
"""Returns the list of necessary attributes
Parameters:
element: xml element
attrs: tuple of attributes
Returns:
a dictionary of elements
"""
result = {}
for attr in attrs:
result[attr] = xml_element.getAttribute(attr) ... | 77911646f3624dc089475927a8b1e14abd9caef7 | 628,315 |
def extract_unique_words(list_of_tup):
"""
:param list_of_tup: list of tuples
:return: The unique words from all the reviews
"""
unique_wrs = set()
for review in list_of_tup:
for pair in review:
unique_wrs.add(pair[0])
return sorted(list(unique_wrs)) | 5c5266fa964e5c961d30cbbf939fe5787feca393 | 362,138 |
from copy import deepcopy
def get_nn(seqdict, positions, nn, base):
"""
Returns nn nearest neigbour bases on either side of the imput positions (i.e. a 2nn+1 mer)
Parameters
----------
seqdict : dictionary in the format returned by seq_dict()
positions : list containing positions in the form... | f70167791eedfd565d79b969404bc462c0d6a52d | 604,760 |
import json
def get_threshold(filename, current_threshold, service, version):
"""
Get the threshold score
:param filename: String, File that containes the best score. Ie, './path/file.py'
:param current_threshold: Float, the latest score. Ie, 6.78
:param service: String, Service to evaluate. Ie, '... | b090368303dd6705f8bad41416a7f31d422d5153 | 474,077 |
import torch
def invsoftplus(x):
"""Inverse of torch.nn.functional.softplus"""
bound = 20.0
xa = torch.clamp(x, None, bound)
res = torch.log(torch.exp(xa)-1.0)*(xa < bound) + xa*(xa >= bound)
return res | d29379fcb4b371c5689117a4ba6ac8dc58ea690f | 205,899 |
from bs4 import BeautifulSoup
def strip_html(string: str):
"""
Use BeautifulSoup to strip out any HTML tags from strings.
"""
return BeautifulSoup(string, "html.parser").get_text() | 796fc52ddd303906c7fd217275cb2a897e76767c | 695,836 |
import re
def extract_positivie_integer_value(text, key):
"""
Extract an integer value for a given key in a text
Args:
text (str): text to extract value from
key (str): key to extract value for
Raises:
ValueError: value is not a positive integer
Returns:
int: extrac... | 43257254883a343afbe27a5ee0dd814eaf9ddc3d | 362,692 |
def pytest_report_header(config):
""" return a string in test report header """
return "Hey this are the tests" | e64bf912f78e8524d99126569d0423c821158498 | 695,314 |
from typing import Any
def clean(data: Any) -> Any:
"""Recursively cleans a `dict` or a `list` from 'None' values."""
if isinstance(data, list):
return [x for x in map(clean, data) if x is not None]
if isinstance(data, dict):
result = {key: clean(value) for key, value in data.items()}
... | 5e98b2d83f3686a0e8beeb53165743d8e80713ce | 143,119 |
def remove_sublists(lst):
"""
Returns a list where all sublists are removed
:param lst: list
:return: list
>>> remove_sublists([[1, 2, 3], [1, 2]])
[[1, 2, 3]]
>>> remove_sublists([[1, 2, 3], [1]])
[[1, 2, 3]]
>>> remove_sublists([[1, 2, 3], [1, 2], [1]])
[[1, 2, 3]]
>>> rem... | f41bb66a70dc15825ce4a57b41b0f326bde4fb84 | 68,419 |
import gzip
import shutil
def compress_gzip(file_path: str, out_path: str) -> str:
"""Compress a file into gzip.
Args:
file_path: Path to file
out_dir: Path to compressed file
Returns:
Path to compressed file
"""
with open(file_path, 'rb') as f, gzip.open(out_path, 'wb') ... | 10158a91dcd39411944f4f8a135e9114243b7cd7 | 307,495 |
from typing import List
def drop_lowest(grades: List[float]) -> List[float]:
"""Drops the lowest number and returns the pruned collection
Args:
grades (List[float]): An array of number grades
Returns:
List[float]: The pruned list of grades
"""
new_grades = grades.copy()
new_g... | 950907b0cad3fa65d9b9c062dac1eb60f3a371c0 | 313,516 |
from typing import Dict
def _parse_schemata_file_row(line: str) -> Dict[str, str]:
"""Parse RDTAllocation.l3 and RDTAllocation.mb strings based on
https://github.com/torvalds/linux/blob/9cf6b756cdf2cd38b8b0dac2567f7c6daf5e79d5/arch/x86/kernel/cpu/resctrl/ctrlmondata.c#L254
and return dict mapping and doma... | 359672902330e30c8b188f6565b4242f8730ecea | 60,053 |
def capitalized(piece_name: str) -> str:
"""Returns a capitalized version of a piece name
Args:
piece_name: Piece name
Returns:
Capitalized version
"""
return '%s%s' % (piece_name[0].upper(), piece_name[1:].lower()) | 98838f820e90f6b1540f537ed878324d02aefb87 | 73,579 |
def write_to_text_file(file_path, file_contents):
"""
Writes the given file_contents to the file_path in text format
if current user's permissions grants to do so.
:param file_path: Absolute path for the file
:param file_contents: List<str> List of lines
:return: void
:rtype: void
:raise... | 5390092f05c1a449567ae701c2ca08b0ef4405c6 | 77,457 |
def list_(client, name=None, file_=None, dim_type=None, encoded=None, select=False):
"""Get a list of dimensions from a model.
If select is true, then the current selection in Creo will be cleared even
if no items are found.
Args:
client (obj):
creopyson Client.
name (str|l... | 7f15f89fe91ca1dbeddd03fdd011db8bedb1ad6f | 287,154 |
def _get_QSlider(self):
"""
Get current value for QSlider
"""
return self.value() | 9badb4a2ecbc93016f07f720f1d99431732fc6e7 | 143,193 |
def lcs(X, Y):
""" Function for finding the longest common subsequence between two lists.
In this script, this function is particular used for aligning between the
ground-truth output string and the predicted string (for visualization purpose).
Args:
X: a list
Y: a list
Returns: a l... | 336040927b84f0e64d5682896fa4bd9cc18eaddf | 540,038 |
import csv
def load_data(path_to_csv, num_samples=None):
"""
Read the csv file given and return the path to images and steering angles
"""
image_path = []
steering_angle = []
with open(path_to_csv, "r", newline='') as f:
recorded_data = csv.reader(f, delimiter=',', quotechar='|')
... | be02b6f02a01293b59de8a8acf63f676a64ac558 | 627,815 |
def restriction(d, keys):
"""Return the dictionary that is the subdictionary of d over the specified
keys"""
return {key: d.get(key) for key in keys} | 9fdb2d2e5bea0d96380e592ffc6d7720b32ade30 | 693,979 |
def dms_to_degrees(v):
"""Convert degree/minute/second to decimal degrees."""
d = float(v[0][0]) / float(v[0][1])
m = float(v[1][0]) / float(v[1][1])
s = float(v[2][0]) / float(v[2][1])
return d + (m / 60.0) + (s / 3600.0) | 163dc1a23c8f0e913d5a505c7cba58f3b2b72bb7 | 187,429 |
def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
days, seconds = duration.days, duration.seconds
... | 4a0a0b89608e895963df2ec5e890db7a1ae313c9 | 571,056 |
def remove_useless_features(training_data):
"""Create features and targets
Args:
training_data (list): List of Dataframe containing data from each file.
Returns:
dict : Dictionary containing features and target for each file.
"""
data_dict = {}
for key, data in training_data.i... | 92ee3957bd8ccadd14bfd87a5f51818b63ba6462 | 273,258 |
import string
import random
def randstr(n=8):
"""
randstr creates a random string of numbers and upper/lowercase characters.
>>> randstr()
"0YH58H9E"
>>> randstr(5)
"0ds34"
This code is slighty modified version of
http://stackoverflow.com/questions/2257441/random-string-generation-w... | 493dade04e2fe4c39323dbf404abb0ee1e062e0f | 470,186 |
import yaml
def yaml_load(path):
"""Returns content of YAML file at `path` as a Python object."""
with open(path, 'r', encoding='utf-8') as f:
data_yaml = yaml.load(f, Loader=yaml.FullLoader)
return data_yaml | abf0e4501c3963cf86ee2e83ba8b91c9410b7fbb | 573,297 |
def contains_filepath(filepath1, filepath2):
"""
contains_filepath checks if file1 is contained in filepath of file2
"""
return filepath2.startswith(filepath1) | 4b6d7da1da171dadd41d6b4e24d8311d8b8d5f0b | 484,414 |
def combine_dicts(seq):
"""Combine a list of dictionaries into single one."""
ret = {}
for item in seq:
ret.update(item)
return ret | 4d49e6fb1eec8cb3042a39a018da6f3bb9e3463b | 117,541 |
import re
def get_pagetext_mkiconf(pagetext):
"""Return the mkiconf vars found on most dashboard pages.
These variables are largely the same as administered orgs, but could
be useful elsewhere. Keeping this here is in case I could use this of
scraping method later. Check the regex below for the expec... | 985e7305c9d84f60c1fb6e3e36ad827d542b8ec0 | 416,774 |
def bigquery_serialize_date(py_date):
"""
Convert a python date object into a serialized format that Bigquery accepts.
Accurate to days.
Bigguery format: 'YYYY-[M]M-[D]D'
https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types
Args:
py_date (datetime.date): The date to... | b730fdfe6696011601d466ad65010b5b566749e7 | 695,286 |
import logging
import pkgutil
import importlib
def get_modules_by_name_prefix(prefix):
"""Get modules whose name starts with the prefix.
:param prefix: a prefix used to select modules to be returned.
:returns: a map of the modules to their names, with the prefix
stripped.
"""
logger = log... | 5f82f5dbae72381ce26311443137939df77bbe6b | 537,474 |
def _paths_for_iter(diff, iter_type):
"""
Get the set for all the files in the given diff for the specified type.
:param diff: git diff to query.
:param iter_type: Iter type ['M', 'A', 'R', 'D'].
:return: set of changed files.
"""
a_path_changes = {change.a_path for change in diff.iter_chan... | fe828c21277c1051aebc4c125b53228ab9c7cc12 | 645,380 |
from typing import Tuple
def convert_hex_to_rgb(hx: str) -> Tuple[int, ...]:
"""
Takes a string with format "#FFFFFF" and converts the value
into a proper hexadecimal value, usable for images.
Parameters
----------
hx: str
The hexadecimal value.
Returns
-------
Tuple[int,... | 023312b4115a98fffbb5ead2c8da7dc5b57d622d | 356,068 |
def isreadable(f):
"""
Returns True if the file-like object can be read from. This is a common-
sense approximation of io.IOBase.readable.
"""
if hasattr(f, 'readable'):
return f.readable()
if hasattr(f, 'closed') and f.closed:
# This mimics the behavior of io.IOBase.readable
... | 04530ed6bc40c19b22c0f3d694cb0418202e2949 | 670,306 |
def _get_equality(analysis_1: dict, analysis_2: dict) -> dict:
"""Compares the two input dictionaries and generates a new dictionary,
representing the equality between the two.
Args:
analysis_1(dict): Eg: {'rs10144418': ['T', 'C'], 'rs1037256': ['G', 'A'],... }
analysis_2(dict): Eg: {'rs101... | 94859d1eb03bdfc656ab8fb70ce6eb4cabe89e35 | 608,461 |
def has_urn_and_labels(mi, urn, labels):
"""Returns true if it the monitoring_info contains the labels and urn."""
def contains_labels(mi, labels):
# Check all the labels and their values exist in the monitoring_info
return all(item in mi.labels.items() for item in labels.items())
return c... | 7dcfccfb148590c091c45a6af846bcc2d4072472 | 247,660 |
def getClientIP(request):
"""
Pull the requested client IP address from the X-Forwarded-For request
header. If there is more than one IP address in the value, it will return
the first one.
For more info, see: 'def access_route' in
https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/wrapp... | 4ed0d2693e805aab782a304dd0ab9a62bc1f91d4 | 60,242 |
def getSeqRegions(seqs, header, coordinates):
"""From sequence dictionary return spliced coordinates.
Takes a sequence dictionary (ie from fasta2dict), the contig name (header)
and the coordinates to fetch (list of tuples)
Parameters
----------
seqs : dict
dictionary of sequences keyed... | 2881c9cef621be24e77943b8d527c380499befff | 97,038 |
def xor(a: bool, b: bool) -> bool:
"""Exclusive or (XOR)"""
return a ^ b | bcb1db14eee93f10fe75c7eb918be0a3f4ee48c3 | 144,668 |
def _replace_in_single_or_double_quotes(val, from_, to):
"""Replace a value in a string enclosed in single or double quotes."""
return val.replace(f"'{from_}'", f"{to}").replace(f'"{from_}"', f"{to}") | 5f1dfa6fae4ac6c669c8d27c749b26c822dbe0f3 | 430,761 |
from pathlib import Path
from typing import List
def get_files(
d: Path,
pattern: str,
sort_lexicographical: bool = False,
sort_numerical: bool = False,
) -> List[Path]:
"""Return a list of files in a given directory.
Args:
d: The path to the directory.
pattern: The wildcard t... | b9639e43c36ae132905a7154b1cfdb3b556c6e24 | 519,624 |
import torch
import math
def angle_normalize(angle: torch.Tensor) -> torch.Tensor:
"""
Normalize the `angle` to have a value in [-pi, pi]
Args:
angle: Tensor of angles of shape N
"""
TWO_PI = 2 * math.pi
angle = torch.fmod(torch.fmod(angle, TWO_PI) + TWO_PI, TWO_PI)
return torch.w... | 1ad2f5e99fde42d92fe6ba3a06d08650e5a84132 | 301,742 |
def mod_Goodman_Fos(sa, sm, Se, Sut):
"""
Computes the mod Goodman relation factor of safety
:param sa: alternating stress
:param sm: midrange stress
:param Se: Endurance strength
:param Sut: Ultimate tensile strength
:return: factor of safety
"""
n_inv = sa/Se + sm / Sut
retur... | b98e8335929a8ef40569f25fd46dc7035090a20a | 627,871 |
from typing import List
from pathlib import Path
import re
def extracted_urls() -> List[str]:
"""
README.mdからURLを抽出する。
Returns
-------
List[str]
README.mdに含まれるURLのリスト。重複は除かれている。
"""
file_path = Path(__file__).parents[1] / 'README.md'
with open(file_path, mode='rt', encoding='u... | 0faf486395a3c0d6474977766f84561686b6fb7b | 187,636 |
def get_sub_row_by(rows, **conditions):
"""Returns a table row that matches conditions."""
for table_row in rows():
if table_row.matches_conditions(**conditions):
return table_row
return None | b5c24f37bdd319b3f2c94a17bc0ee1b0ecddfc15 | 539,920 |
def is_templated_secret(secret: str) -> bool:
"""
Filters secrets that are shaped like: {secret}, <secret>, or ${secret}.
"""
try:
if (
(secret[0] == '{' and secret[-1] == '}')
or (secret[0] == '<' and secret[-1] == '>')
or (secret[0] == '$' and secret[1] == '... | 4fa6c95bdfbb884b4452d57fea381c16665412ad | 450,936 |
def pos_pow(z,k):
"""z^k if k is positive, else 0.0"""
if k>=0:
return z**k
else:
return 0.0 | ba0a46e8711005b9ac0dbd603f600dfaa67fbdd4 | 18,713 |
def transpose(matrix):
"""Transpose a list of lists."""
return [list(t) for t in zip(*matrix)] | d584d6a8341488f5af7a2e217310ead17a5bbf37 | 545,573 |
from typing import Dict
from typing import Any
from warnings import warn
def has_license_and_update(data: Dict[str, Any]) -> bool:
"""Check if license header exists anywhere in notebook and format.
Args:
data: object representing a parsed JSON notebook.
Returns:
Boolean: True if notebook contains the ... | 67f3f6d7b9f31961f138824482926dcf529f5409 | 633,670 |
def format_zone_df(df, name):
"""copies df, checks if it contains invalid geometry and adds col for zone area
:param geopandas.geodataframe.GeoDataFrame df: GeoDataFrame where
index = zone names, columns = ['geometry']
:param str name: the name of the data set
:return: (*geopandas.geodataframe.... | d71fc4a678b18c6524f58cfafb7396eec9bde61d | 313,350 |
import json
def loader(filename):
"""
Load translation from file and return a dictionary with info.
:param filename: filename info
:type filename: str
:return: dict object.
:rtype: dict
:raises: TypeError, ValueError
"""
if not isinstance(filename, str):
raise T... | 1e978466509c9cc54265a448b8c4f9f997a14336 | 564,684 |
from typing import OrderedDict
def as_ordered_dict(v, ctx, value_transform=None, additional_params=None):
"""Expects v to be a list containing single key/value pair entries, and
transforms it into an ordered dictionary."""
if not isinstance(v, list):
raise Exception("Expected list of key/value pai... | e89cc7189429d5aa819141242a0b3260ccd6a225 | 464,319 |
def get_full_path_file_name(folder_name, file_name):
""" Build full path to file given folder and file name """
full_path_file_name = ''
if folder_name > '':
full_path_file_name = folder_name + '/'
full_path_file_name += file_name
return full_path_file_name | caac6524224c0bf49b65bc8281f3fac4847f5a46 | 546,694 |
from pathlib import Path
import shutil
def get_config(repo_path: Path, filename: str) -> Path:
"""Get a config file, copied from the test directory into repo_path.
:param repo_path: path to the repo into which to copy the config file.
:param filename: name of the file from the test directory.
:return... | 4ac87766cd61e4202a3b73bd373009f8b6f52d34 | 676,993 |
def getCenter(box):
"""
This function calculates the center of a bounding box.
"""
# get the corners of the box
x1 = box[0]
x2 = box[2]
y1 = box[1]
y2 = box[3]
# find the middle along the x axis
center_x = int((x1+x2)/2)
# find the middle along the y axis
center_y = int(... | d09a8954e1489f58a9bfa774fca3263eaa97c864 | 693,443 |
def top_files(query, files, idfs, n):
"""
Given a `query` (a set of words), `files` (a dictionary mapping names of
files to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the filenames of the the `n` top
files that match the query, ranked accord... | 67abbcf5d0938b7046d8192ea6e48d73cb47fed0 | 440,723 |
def chr2num(chr_name):
"""
Returns a numerical mapping for a primary chromosome name
Assumes names are prefixed with "chr"
"""
chr_id = chr_name[3:]
if chr_id == 'X':
return 23
elif chr_id == 'Y':
return 24
elif chr_id == 'M':
return 25
return int(chr_id) | 92504f7fa7edf0a0cf1b766c357df52a5325f7c2 | 447,698 |
import re
def remove_reminders(text):
"""Remove reminder text from a string.
Reminder text, as defined by magic cards, consists of complete
sentences enclosed in parentheses.
"""
return re.sub(r'(\A|\ )\(.*?\.\"?\)+', '', text) | 5282f1c6f6dd6f198782fc057d71306c4340bb74 | 342,309 |
def find_nearest_multiple(num, n):
"""Find the nearest multiple of n to num
1. num: a number, num must be larger than n to have a meaningful result.
2. n : a number to be multipled
"""
return int(round(num / n)) * n | 753e68908ebd1ff3ae4e40b992ce048ffd83262e | 522,514 |
from typing import Union
def celsius_to_kelvin(temperature_in_celsius: Union[int, float]) -> float:
"""
>>> celsius_to_kelvin(0)
273.15
>>> celsius_to_kelvin(1)
274.15
>>> celsius_to_kelvin(-1)
272.15
>>> celsius_to_kelvin(-273.15)
0.0
>>> celsius_to_kelvin(-274.15)
Tra... | 1aa5b214e20c0d47a3ab50388132f174cd33dbde | 30,152 |
def obfuscate_email(email):
"""Takes an email address and returns an obfuscated version of it.
For example: test@example.com would turn into t**t@e*********m
"""
if email is None:
return None
splitmail = email.split("@")
# If the prefix is 1 character, then we can't obfuscate it
if l... | 36c230ed75fc75fc7ecd6dd2ea71a6b3310c4108 | 708,417 |
def unwrap(string):
"""
Converts a string to an array of characters.
"""
return [c for c in string] | 2d23d612b4c8e49165cbaa2adc2ae59285ceda80 | 429,452 |
def get_attr(instance, name):
"""Get the value of an attribute from a given instance.
:param instance: The instance.
:type instance: object
:param name: The attribute name.
:type name: str
"""
return getattr(instance, name) | a2c92637c2b31356dee4dee32999c895385d4e07 | 252,076 |
def generate_state_table(p):
"""
generates table of state-integers that are allowed by the symmetries
of the model
Args:
p - dictionary that contains the relevant system parameters
Returns:
state_table - list of all state_numbers that belong to the relevant
Hilbertspace
... | 5d0fe34e495bbecac0a571844609008cd4d9ab00 | 174,800 |
from typing import Tuple
def calculate_broadcasted_elementwise_result_shape(
first: Tuple[int, ...],
second: Tuple[int, ...],
) -> Tuple[int, ...]:
"""Determine the return shape of a broadcasted elementwise operation."""
return tuple(max(a, b) for a, b in zip(first, second)) | 5d565b2b5f38c84ab1f1573f4200fc65d6ae8e6a | 25,055 |
def parse_str_to_int(workflow_parameters):
"""Parse integers stored as strings to integers."""
for (key, val) in workflow_parameters.items():
try:
if isinstance(val, str) and val[0] == "'":
# The actual value of the int as str could be stored as:
# '\'val\'', ... | 420251a48ca371e300a9705f645393aacc99df27 | 394,692 |
def naive_ascii_decode(encoded_number: str, length: int) -> str:
"""
This function will decode an integer into a str if it's been encoded with
naive ASCII encoding.
:param encoded_number: The encoded integer as a string.
:param length: The length(in bytes that the output string should be).
:return: The decoded s... | 1a774beabc0cb17c4ed58d433d315fbfb158d555 | 417,761 |
from typing import List
def remove_nested_packages(packages: List[str]) -> List[str]:
"""Remove nested packages from a list of packages.
>>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
['a']
>>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"])
['a', 'b', 'c.d', 'g.... | 04cacb569dbe68b61861462e754d62fd27b22ffe | 584,748 |
def read_lines(f):
"""Convert a file into a list of strings, without line breaks."""
return [line.strip() for line in open(f)] | 8392911f2163578ef9d075a11395f9859c4d90ad | 213,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.