content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def dpv(vec1, vec2)->float:
"""Dot product of two vectors"""
product = 0.
for idx, val in enumerate(vec1):
product += val * vec2[idx]
return product | 985ae996878daa24793fb6f96c170a3e637cf610 | 200,066 |
def is_proxy(obj):
""" Return True if `obj` is an array proxy
"""
try:
return obj.is_proxy
except AttributeError:
return False | 871c163b30ccc1b31b435c9baac5c0d6063d271e | 40,308 |
def is_palindrome(n, base=10):
"""
Is the given number n a palindrome in the given base?
"""
if base == 10:
n_str = str(n)
elif base == 2:
n_str = "{0:b}".format(n)
else:
raise RuntimeError("Only 2 and 10 bases supported")
for i in range(len(n_str) // 2):
... | 7e90c2122888d853850a84229ca3ca65074a8993 | 629,659 |
def extract_best_aligns(aligns_df):
"""Extracts alignments with highest score from the provided alignments
dataframe.
"""
mask = aligns_df.groupby('seq_index').agg({'score': 'idxmax'}) # get /!\ FIRST /!\ index of max align score for each sequence
aligns_df_best = aligns_df.loc[mask['score']].rese... | a7b512631a96c87380a20bea90dd2228ea020396 | 616,769 |
def bitstring_readable(data, batch_size, model_output=None, whole_batch=False):
"""Produce a human readable representation of the sequences in data.
Args:
data: data to be visualised
batch_size: size of batch
model_output: optional model output tensor to visualize alongside data.
whole_batch: wheth... | 342b6720dd30b1f8d8b984a5d49b09913050fd40 | 688,148 |
def large_dollar_volume_stocks(df, price_column, volume_column, top_percent):
"""
Get the stocks with the largest dollar volume stocks.
Parameters
----------
df : DataFrame
Stock prices with dates and ticker symbols
price_column : str
The column with the price data in `df`
v... | ef2e168dd1738a9c8e759cafd5f6180ffb65bf1c | 276,938 |
import math
def prob_no_match(n):
"""analytical result using integers - python can handle arb large numbers"""
return math.factorial(n)*math.comb(365,n)/(365**n) | fe292657654c4413fd3d9751e6a10be7c38f2c19 | 662,011 |
from typing import Mapping
def _recursive_update(d, u):
"""Recursively update a nested dict with another."""
# https://stackoverflow.com/a/3233356/1595060
for k, v in u.items():
if isinstance(v, Mapping):
d[k] = _recursive_update(d.get(k, {}), v)
else:
d[k] = v
... | 0562fa333b2667db02675382c95ce09bcbd23758 | 538,505 |
def test_data_dir(name):
"""
Decorator allowing to customize test data directory for a test.
The specified name will be used only as the last component of the path
following the directory corresponding to the test class (by default
test name itself is used for this purpose).
Example::
... | bbc437c8b247edae24a5f5c81caa674bcb827fc9 | 173,561 |
def group_by_key(dict_list, key):
"""
>>> data = [
... {'a': 1, 'b': 2},
... {'a': 1, 'b': 3}
... ]
>>> group_by_key(data, 'a')
{1: [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}]}
"""
grouped = {}
for d in dict_list:
group_key = d.get(key)
grouped.setdefault(group_k... | b1635a225fc2afb45460cca88b8a7d66934dc0c7 | 160,702 |
def buffer_to_offset(buffer):
"""
Convert a byte buffer into an integer offset according to ArcGIS packing
scheme:
(buffer[0] & 0xff) +
(buffer[1] & 0xff) * 2 ** 8 +
(buffer[2] & 0xff) * 2 ** 16 +
(buffer[3] & 0xff) * 2 ** 24 ...
Parameters
----------
buffer: list[bytes]
... | 537d1aaaaba577f59cb7641982b7f7bf93e0af29 | 427,490 |
def line(display=False):
"""To make easy separations while printing in console"""
if display == True:
return print("____________________________________________________________\n") | aa038f45baa15fc2326a0dac44df5f0ca9944abb | 400,671 |
def group_edge_pairs(edges):
"""
Group pairs of forward and reverse edges between nodes as tuples in a
list together with single directed edges if any
:param edges: list of edges
:type edges: :py:list
:return: paired edges
:rtype: :py:list
"""
pairs = []
do... | 5f1313138dbe575081a7cf9a75aea0682e835e98 | 304,641 |
def calculate_xy_coords(image_size, screen_size):
"""Calculates x and y coordinates used to display image centered on screen.
Args:
image_size as tuple (int width in pixels, int height in pixels).
screen_size as tuple (int width in pixels, int height in pixels).
Returns:
tuple (int x... | 08980f1ee015d9f8bae44d4371c9a7a7ba2fd09e | 561,515 |
def args_env(args):
"""
Create a dictionary of enumerated arguments.
"""
return {str(i): str(v) for i, v in enumerate(args)} | 730dfa5fd2af90dac7c529a2f1529f36ea435e2a | 204,952 |
def can_merge(a, b):
"""
Test if two cubes may be merged into a single cube (their bounding box)
:param a: cube a, tuple of tuple ((min coords), (max coords))
:param b: cube b, tuple of tuple ((min coords), (max coords))
:return: bool, if cubes can be merged
"""
c = 0 # Count the number of ... | 88a7e5a1d3145548f12396e66aae12cba0ee938f | 503,639 |
from typing import List
def get_function_contents_by_name(lines: List[str], name: str):
"""
Extracts a function from `lines` of segmented source code with the name `name`.
Args:
lines (`List[str]`):
Source code of a script seperated by line.
name (`str`):
The name ... | 60239b0063e83a71641d85194f72a9cc61221177 | 705,031 |
from functools import reduce
from operator import add
def determine_breadth(iterable):
"""
Determines the breadth of the addable contents of the iterable
"""
return reduce(add, iterable) | 117a5b242ebe1df069e16e598dd489c7abd9b26c | 499,595 |
def get_announcement(message, reminder_offset):
"""
Generates the announcement message
:param str message: Message about the event
:param number reminder_offset: Minutes in which event is about to happen
"""
pos = message.find(":")
if pos == -1:
activity = message.strip()
m... | 18d9921c815bcb0783ccf7d3fc010989c68aeaa2 | 471,531 |
def get_concordance(text,
keyword,
idx,
window):
"""
For a given keyword (and its position in an article), return
the concordance of words (before and after) using a window.
:param text: text
:type text: string
:param keyword: keyword... | 508a989a8d59c4877fe40291bd24be406374962a | 667,478 |
import json
def retrieve(corpus_path, labels_path="", edges_path=""):
"""
Retrieve corpus and labels of a custom dataset
given their path
Parameters
----------
corpus_path : path of the corpus
labels_path : path of the labels document
Returns
-------
result : dictionary with ... | f27acec7d3f80359bf3ea63f7fcf7d8eca0bf152 | 596,430 |
def removesuffix(s: str, suffix:str) -> str:
"""Removes the suffix from s."""
if s.endswith(suffix):
return s[:-len(suffix)]
return s | 538ca2ef7021b01f09a7c9db56069639a9389d95 | 52,390 |
def remove_prepended_comment(orig_df):
"""
remove the '#' prepend to the first column name
Note: if there is no comment, this won't do anything (idempotency).
"""
input_df = orig_df.copy()
first_col = input_df.columns[0]
return input_df.rename(columns={first_col: first_col.replace('#', "")}) | c4f11b50644070e0f26464a97feef11b4c1e6dbb | 119,685 |
def get_ordinal_string(n):
"""
Return the ordinal representation of a positive integer (e.g. 1 -> "1st")
Code by CTT @ http://stackoverflow.com/a/739301
"""
if 10 <= n % 100 < 20:
return str(n) + 'th'
else:
return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th") | c451b2fdbe6b050c63d64c0ae8cef061793df332 | 489,847 |
def _is_file_external(f):
"""Returns True if the given file is an external file."""
return f.owner.workspace_root != "" | ea3b3854d85da2c6275f1f66cdb06f5cc8d88bef | 201,523 |
def nombre_joueurs_annee(annee,liste):
"""
Fonction qui en paramètre prend une année (int)
et la liste des joueurs sous forme de liste de dictionnaires
et qui retourne le nombre de joueurs ayant joués l'année donnée
"""
compteur = 0
for enreg in liste :
if int(enreg['Année']) == anne... | 75ae36a2cac32bd6b02a4a3ade1cfab82af8f575 | 48,220 |
def AuthorToJSON(author):
"""
Converts an Author object into a JSON-compatible dictionary.
Returns None on failure.
"""
if not author:
return None
try:
json_dict = {
"type":"author",
"id":author.url,
"host":author.host,
"displayName... | 2cf4c6f764aaf6f38bfcc99d8a19f907dce3dae1 | 293,750 |
import requests
def basic_auth_request(method, url, token=None, payload=None, params=None):
"""
make a request using basic authorization
:param method: [GET, POST, PUT, DELETE ...]
:param url:
:param token: basic authentication token
:param payload: post body
:param params: Dictionary or b... | 610e951151c224a5bdf7b4fe74e759e5f713bce0 | 194,561 |
def probability_in_subspace(wavefunc: dict, subspace: list) -> float:
"""
Calculates the probability that the wavefunction 'wavefunc' lies in 'subspace'
Note: This only works for subspaces aligned with the comp. basis.
:param wavefunc: dict, contains complex amplitudes of the wavefunction
... | 1762c6ce3f3569557fcacecbdb806ebb3655afc8 | 232,612 |
def is_sublist(l1, l2, pos=False):
"""
Check if l1 is a sublist of l2 (it contains all elements from l1 in the same order).
if pos is True, return position where sublist starts, not a boolean value
"""
if l1 == []:
return 0 if pos else True
elif l1 == l2:
return 0 if pos else Tr... | 8be3d2253d6381e61ee58369bdf0c939e11d017d | 614,920 |
import typing
def asBool(key: str, value: typing.Union[str, bool, int]) -> bool:
"""
Coerce a key to boolean
Parameters
----------
key : str
Name of this setting. Used in error reporting
value : string or bool or int
Trivial for booleans. If integer, return the corresponding
... | 8df4a0479145e3128398e1b61206c81070bd5969 | 131,501 |
def _NormalizePath(path):
"""Returns the normalized path of the given one.
Normalization include:
* Convert '\\' to '/'
* Convert '\\\\' to '/'
* Resolve '../' and './'
Example:
'..\\a/../b/./c/test.cc' --> 'b/c/test.cc'
"""
path = path.replace('\\', '/')
path = path.replace('//', '/')
filtered... | ed6cd73f1c59eeef4d55121a99bb29c2e569a6da | 82,049 |
def _softmax_output_grad(ans, x, y):
"""Gradient function for softmax output."""
def grad(_0): #pylint: disable= missing-docstring
N = x.shape[0]
return (ans - y) / N
return grad | 324d12cae270d5274a5d23c560f953a3d37baaa0 | 535,994 |
def gst_value_from_inclusive(amount, gst_rate):
"""Calculate GST component from a GST inclusive total.
GST amount calculated as amount - (1 + gst_rate)).
Args:
amount (float): GST inclusive amount
gst_rate (float): GST rate to apply.
Returns:
gst_component (flo... | 5d7ba72bfe97598da3b360cf2e263aef59214af2 | 612,899 |
import pytz
def compare_dates(date_a, date_b):
"""
Compares two dates with offset-aware format.
Args:
date_a: The first date to compare
date_b: The second date to compare
Returns:
- if the date_b is greater than date_a = =1
- if the date_a is greater than date_b = 1
... | 9cede76385991eb06eb43c5ec664574be521ab65 | 189,390 |
def read_msr_line(line, tstat_switch, msr_id_switch):
"""
Function to read msr components from a single line in adj file
:param line: Msr line in adj file
:param tstat_switch: True/False switch for presence of tstats
:param msr_id_switch: True/False switch for presence of msr_ids
:return: Dictio... | 40e5f1b76fa525c6b6b47f878bd54839a4bf05b0 | 449,180 |
def PrintSourceMatrix(S,params):
"""Auxiliary function to print the source matrix (S)"""
dim = params["dim"] # Spatial dimensions
print("The source term matrix is:\n")
for i in range (0,dim+2):
for j in range (0,dim+2):
print("S[",i,",",j,"]=",S[i,j],"\n")
return 0 | be00de08d18f00ee421962290d91999cff9fb545 | 122,157 |
def get_special_tokens(vocab_size):
"""Gets the ids of the four special tokens.
The four special tokens are:
pad: padding token
oov: out of vocabulary
bos: begin of sentence
eos: end of sentence
Args:
vocab_size: The vocabulary size.
Returns:
The four-tuple (pad, oov, bos, eos).
"""... | 5e1b058f91c55e2da58d1bec1538739e0d593352 | 147,238 |
def calculate_tcp_checksum(message):
""" Calculate the TCP checksum
@param message: payload + TCP headers + pseudoheader
@return: 16-bit TCP checksum value
"""
cs = 0
for i in range(0, len(message), 2):
w = (ord(message[i])<<8 + ord(message[i+1]))
cs = cs + w
cs = (cs>>16) ... | 29012bad836e671e38cd6e7bb781ebae3fe09a54 | 453,006 |
import time
def ControlRate(t_last_call, max_rate):
"""
Limits rate at which this function is called by sleeping.
Returns the time of invocation.
"""
p = 1.0 / max_rate
t_current = time.time()
dt = t_current - t_last_call
if dt < p:
time.sleep(p - dt)
return t_curren... | 67d79eb4cdba4825ba1936ad86917a548002890f | 338,697 |
import itertools
def GetLatencyEvents(process, timeline_range):
"""Get LatencyInfo trace events from the process's trace buffer that are
within the timeline_range.
Input events dump their LatencyInfo into trace buffer as async trace event
of name starting with "InputLatency". Non-input events with name st... | 17e932bdd04c1efc069b84606fb104e340f7f9a2 | 577,021 |
def splitlines(text):
"""Split text into lines."""
return text.splitlines() | bc599e88ce14feeddb51dc6c4a48a459c01160e3 | 282,782 |
from typing import List
def format_row(columns: List[str], widths: List[int]) -> str:
"""Format one row of the table. This may go into multiple lines if
any of the columns were wrapped."""
row = ""
had_values = True
lineno = 0
while had_values:
had_values = False
line = ""
... | c01bd30b6a73f8ea83f936d139c003db952fe58b | 496,560 |
import ast
def _combine_side_inputs(side_input_shapes='',
side_input_types='',
side_input_names=''):
"""Zips the side inputs together.
Args:
side_input_shapes: forward-slash-separated list of comma-separated lists
describing input shapes.
side_input... | e67e634ad0a2d48ecaa621bb663d50e91964a426 | 393,755 |
def dict_sample_list(a_dict, n_sample = 4):
"""Sample dictionary data using even spacing - returns a list for printing"""
data_len = len(a_dict)
header = ['Printing {} entries evenly sampled from {} combinations:\n'.format(n_sample, data_len)]
return header + ['** {} ** \n{}'.format(k,repr(a_dict[k])) f... | a76bf2bc18bb9356bf38ccef566a38e87757fa28 | 128,877 |
def _bbox(pts):
"""Find the AABB bounding box for a set of points"""
x, y = pts[0]
ax, ay, bx, by = x, y, x, y
for i in range(1, len(pts)):
x, y = pts[i]
ax = x if x < ax else ax
ay = y if y < ay else ay
bx = x if x > bx else bx
by = y if y > by else by
return... | 95802ea790153020fcd6c20193536e1b19ca6102 | 657,737 |
def get_x(path, width):
"""Gets the x value from the image filename"""
return (float(int(path.split("_")[1])) - width/2) / (width/2) | c387ce4415b75677f2c7b4a1bc27b12cba469d22 | 630,738 |
def hasCycle(head):
"""
Use two pointers(one slow, one fast) to traverse the list.
Two pointers are bound to meet if there is a cycle;
otherwise, fast pointer will reach the end eventually.
"""
slow = head
fast = head
while fast and fast.next: # note the condition
slow = slow.ne... | ab518c35d44bf86d75e6a1cc1f631b8acadc9795 | 594,578 |
import string
import random
def generate_identifier(size = 16, chars = string.ascii_uppercase + string.digits):
"""
Generates a random identifier (may be used as password) with
the provided constrains of length and character ranges.
This function may be used in the generation of random based
keys... | fc749c1ac2294c365c17a54ff3d096d466fb48d6 | 619,492 |
import re
def tokenize(text):
"""Tokenize the text (i.e., insert spaces around all tokens)"""
toks = re.sub(r'([?.!;,:-]+)(?![0-9])', r' \1 ', text) # enforce space around all punct
# most common contractions
toks = re.sub(r'([\'’´])(s|m|d|ll|re|ve)\s', r' \1\2 ', toks) # I'm, I've etc.
toks = ... | 14269361eaaf55346bf08469896db408665d703a | 492,582 |
def truncate(s, amount) -> str:
"""Return a string that is no longer than the amount specified."""
if len(s) > amount:
return s[:amount - 3] + "..."
return s | 0cac2bf590a7d57197d80847ae551f8f8a9e7906 | 302,692 |
def parse_strling_info_for_locus(strling_genotype_df, locus_chrom, locus_start, locus_end, margin=700):
"""Extract info related to a specific locus from the STRling genotype table.
See https://strling.readthedocs.io/en/latest/outputs.html for more details.
Args:
strling_genotype_df (pd.DataFrame): ... | 09313a37946679ffba97cc044601a59bfdcab120 | 385,096 |
import random
def random_choice(sequence):
"""Return a random element from the non-empty sequence."""
return random.SystemRandom().choice(sequence) | 942e9e2a7967a02863c76c84b2a2b6228fad35b0 | 614,016 |
def __slice_scov__(cov, dep, given):
"""
Slices a covariance matrix keeping only the covariances between the variables
indicated by the array of indices of the independent variables.
:param cov: Covariance matrix.
:param dep: Index of dependent variable.
:param given: Array of indices of indepen... | a5742c8dc4db245521477b0bf8c6ad8f3b463a2b | 696,286 |
def drawBorder(grid: list) -> list:
"""Draw a border around the maze"""
for i, x in enumerate(grid): # Left and Right border
x[0] = x[len(grid)-1] = (20,20,20)
grid[i] = x
grid[0] = grid[len(grid)-1] = [(20,20,20) for x in range(len(grid))] # Top and Bottom border
return grid | 6aef946dc201c0c16df4daedc6a93512844cfcc5 | 547,638 |
def iterkeys(obj, **kwargs):
"""Iterate over dict keys in Python 2 & 3."""
return (obj.iterkeys(**kwargs)
if hasattr(obj, 'iterkeys')
else iter(obj.keys(**kwargs))) | 03787c0e8bb493c721871990c4068144782370e2 | 697,552 |
def join_string_lists(**kwargs) -> dict:
"""Convert named lists of strings to one dict with comma-separated strings.
:param kwargs: Lists of strings
:return: Converted dict.
Example:
>>> join_string_lists(foo=["a", "b", "c"], bar=["a", "b"], foobar=None)
{"foo": "a,b,c", "bar": "a,b"}
"""... | c5c93c0335ccedf37edf0d202a1fed4f5b7d0243 | 588,936 |
def num2char(numpair, key):
"""Takes in a numpair like '34', and returns the character in row 3 (actually 4th row)
and column 4 (actually 5th column) of the key"""
row_num = int(numpair[0])
column_num = int(numpair[1])
return(key[row_num][column_num]) | a86cf1ef327d2f1fbedf8b661e812c4d486fb3ac | 33,521 |
def closest_number(val, num_list):
"""
Return closest element to val in num_list.
Parameters
----------
val: integer, float,
value to find closest element from num_list.
num_list: list,
list from which to find the closest element.
Returns
-------
A element of num_list... | cf58cafbed0c2a0b773c287157581620bb915b68 | 389,003 |
def nid(x):
"""Return the address of an array data, used to check whether two arrays
refer to the same data in memory."""
return x.__array_interface__['data'][0] | 5a3e3760b492e418f96ceacdd31eb9a35c124ef4 | 287,902 |
def build_file_list(path):
"""
Build a list a list of files (and directories) by iterating recursively
over the given path
:param path: The path to iterate over
:type path: pathlib.Path
:return: A tuple of directories and files
:rtype: tuple(list, list)
"""
dirs = []
files = []
... | 1558bf9fda13ded5a478d477116ad031e8aea434 | 308,447 |
def get_timeout(run_type):
"""Get timeout for a each run type - daily, hourly etc
:param run_type: Run type
:type run_type: str
:return: Number of seconds the tool allowed to wait until other instances
finish
:rtype: int
"""
timeouts = {
'hourly': 3600 / 2,
'daily': 24... | 40c07cb61bb3fa4c43538c0bf265990fe763a929 | 634,294 |
def default_key(rarity: float) -> float:
"""The default function that converts rarity to drop rate (1/x)
Parameters
----------
rarity : float
the rarity of the item
Returns
-------
float
the drop rate of the item
"""
return 1 / rarity | 806e624efe27bd80aef4ef1077842bcbb984634f | 340,903 |
import pkg_resources
import yaml
def get_metadata(package_name):
"""
Return runner related metadata for the provided runner package name.
:rtype: ``list`` of ``dict``
"""
file_path = pkg_resources.resource_filename(package_name, 'runner.yaml')
with open(file_path, 'r') as fp:
conten... | 0ae30c8cfe35eec3dd96f551a99963cc403c211f | 299,034 |
import json
def jsonifyer(someDict):
"""Provides standardization of pretty json
Args:
someDict (dict): Any JSON compatible dictionary
Returns:
JSON string
"""
return json.dumps(someDict, sort_keys=True, indent=4, separators=(',', ': ')) | c274e742875dc333f1da3e8b0b3cd5f0aff7a6e9 | 146,495 |
def not_equal(x, y):
"""Element-wise `(x != y)`."""
return x != y | 4905b947a768f773088de670e810ad626c147726 | 363,733 |
def _build_technical_detail(
target: str, header: str, method: str, uri: str, param: str, attack: str, evidence: str) -> str:
"""Build the technical detail markdown content."""
return f"""{header}
* Target: {target}
```http
{method} {uri}
{param}
{attack}
{evidence}
```
""" | 2d20ad7f67f0c1e93d6933b905ca9096deb4b168 | 512,462 |
def getallis(l,match):
"""
get all indices of match pattern in list
"""
return [i for i, x in enumerate(l) if x == match] | 6d4496a9356d2ef839066fc5a5c40896af86b809 | 351,672 |
def move_bounding_rect(rect, delta_x, delta_y):
""" Move bounding rect x,y by some delta_x, delta_y . """
x, y, w, h = rect
return (x+delta_x, y+delta_y, w, h) | 1610d738c35d9d5ffd580a901fcef8a143c85106 | 370,016 |
def hits_to_dict(hits_df):
"""
Given a hits_df, return a dict of sample id -> list of hits
"""
sample_to_clones = {}
for sample, sub_hits_df in hits_df.groupby("sample_id"):
sample_to_clones[sample] = sub_hits_df[
["clone1", "clone2"]
].stack().unique()
return sample_... | 427cee30e7f477dab7d84363177046c6b9800329 | 279,910 |
def count(lbls, wntarget):
"""
Count the number of line transitions with wavenumber smaller than wntarget.
Parameters
----------
lbls: List of lbl objects
wntarget: Float
The target wavenumber.
Returns
-------
nwave: Integer
The number of transitions with wavenumber... | 3d44e19bb8f79593a4f0525cb0ab11c0984b8f88 | 545,570 |
import random
def init_centroids(data:list, k):
"""
Can be intialiazed in several ways. One of them is picking K random samples from the data
:param data:
:return:
"""
return random.sample(data, k) | 31ca7a01b4a79c6d0d73a2899fa55f45610d3d7d | 442,082 |
def doc_to_text(doc, sent_delim='\n'):
"""
Convert document object to original text represention.
Assumes parser offsets map to original document offsets
:param doc:
:param sent_delim:
:return:
"""
text = []
for sent in doc.sentences:
offsets = map(int, sent.stable_id.split("... | afdee8854392fa1133db38673118fdbac87314eb | 578,937 |
def middle_truncate(value, size):
"""
Truncates a string to the given size placing the ellipsis in the middle.
"""
size = int(size)
if len(value) > size:
if size > 3:
start = (size - 3) / 2
end = (size - 3) - start
return value[:start] + u'\u2026' + value[... | afe7183f4673750b3cce70472b7a3713119ecc7d | 482,322 |
def get_doc_str(fun):
"""Get the doc string for a function and return a default if none is found."""
if fun.__doc__:
return '\n'.join([line.strip() for line in fun.__doc__.split('\n')])
else:
return 'No documentation provided for %s()' % fun.__name__ | ab7653a8975fc632c6682e74b9bf67e21b7ffdd1 | 80,182 |
def is_feature_extractor_model(model_config):
"""
If the model is a feature extractor model:
- evaluation model is on
- trunk is frozen
- number of features specified for features extraction > 0
"""
return (
model_config.FEATURE_EVAL_SETTINGS.EVAL_MODE_ON
and (
... | 53c9b398efb09099bbe8257f875720a2ec41a495 | 43,515 |
import ntpath
import posixpath
def to_posix(path):
"""
Return a path using the posix path separator given a path that may contain
posix or windows separators, converting "\\" to "/". NB: this path will
still be valid in the windows explorer (except for a UNC or share name). It
will be a valid path... | 6e11d24beda6316168462220a771ce90369e8eb0 | 680,090 |
def append_form_control(value):
"""A filter for adding bootstrap classes to form fields."""
return value.replace(
'<input', '<input class="form-control"'
).replace(
'<textarea', '<textarea class="form-control"'
).replace(
'<select', '<select class="form-contro... | 57de329073f6389b8ee6c28ae3f2af7e8d298ffd | 206,608 |
def prefixed(strlist, prefix):
"""
Filter a list to values starting with the prefix string
:param strlist: a list of strings
:param prefix: str
:return: a subset of the original list to values only beginning with the prefix string
"""
return [g for g in strlist if str(g).startswith(prefix)] | b5603ed8cd6efb5bc7fc99dbc90471c17bccc4b4 | 177,944 |
def zone_origin(zone_object):
""" Return coordinates of a zone
Args:
zone_object (EpBunch): zone element in zone list
Returns: Coordinates [X, Y, Z] of the zone in a list
"""
return [zone_object.X_Origin, zone_object.Y_Origin, zone_object.Z_Origin] | a539761f757feb65dd653456bec2f357b2a57945 | 457,466 |
def to_string(obj, last_comma=False):
"""Convert to string in one line.
Args:
obj(list, tuple or dict): a list, tuple or dict to convert.
last_comma(bool): add a comma at last.
Returns:
(str) string.
Example:
>>> to_string([1, 2, 3, 4], last_comma=True)
>>> # 1... | 1f22e31a84ec33749e43fd4fadabe268c4c322b6 | 433,021 |
def find_inner(obj, find_key):
"""
Recursively search through the data structure to find objects
keyed by find_key.
"""
results = []
if not hasattr(obj, "__iter__"):
# not a sequence type - return nothing
# this excludes strings
return results
if isinstance(obj, dic... | e0448d873f6f5e1c33a22db882dc352bb97e4fa0 | 470,249 |
def split_lindblad_paramtype(typ):
"""
Splits a Lindblad-gate parameteriation type into
a base-type (e.g. "H+S") and an evolution-type
string.
Parameters
----------
typ : str
The parameterization type, e.g. "H+S terms".
Returns
-------
base_type : str
The "base-... | 91a5cad144de0c4f3fb4e6572c03472899f0d3e8 | 138,013 |
def clean_side_panel(sidepanel):
"""
Cleans the SidePanel data and stores it in a dict.
Parameter:
sidepanel: html-sidepanel extracted using bs4
Returns:
data: dict of extracted data
"""
data = dict()
for x in sidepanel:
x = x.text.strip().replace('\n', '')
... | c9fab309b64b788283e0848a0777fd3ef80014ad | 25,228 |
import itertools
def normalize_padding(padding, rank):
"""
normalized format of padding should have length equal to rank+2
And the order should follow the order of dimension
ex. Conv2d (rank=2) it's normalized format length:2+2 ==>(left, right,top bottom)
Args:
padding (None, int, tuple)... | 6e67d1a7ff408c013fe7fc122a0b0320025e2373 | 37,154 |
def null_input_op_fn(x):
"""This function does no transformation on the inputs, used as default."""
return x | 913f921a571703bef6b9768b69fc53474045d021 | 339,351 |
import math
def float_iszero(distance: float, threshold: float = 1e-05) -> bool:
"""
Computes if a distance is close to zero modulo an epsilon.
:param distance: distance to evaluate
:param threshold: the epsilon value
:return: true or false if the condition is met
"""
return math.isclose(... | 0b58c9a80242d1d2c88df454525f68d38abcd0b5 | 293,893 |
def get_main_domain_name(url_str) -> str:
"""get url domain texts
Args:
url_str (str): url string
Returns:
str: domain name of url
"""
domain_name = url_str.split("/")[2]
main_domain_name = domain_name.split(".")[-2]
return main_domain_name | ddc3fc8aa2b0b61eafd84ac9754c271f011ac8d2 | 627,602 |
def get_flights_sorted_price(flights, reverse=False):
"""Return a list of flights sorted by price.
Args:
flights (list): list of flights, each flight is represented
by a dictionary.
reverse (bool, optional): defines the sorting order,
by default to False - ascending, if ... | 2d21ff6ccee3e07b5ce4aaf7627c94be2570aeb7 | 667,375 |
def remove_non_ascii(text: str) -> str:
""" Removes non ascii characters
:param text: Text to be cleaned
:return: Clean text
"""
return ''.join(char for char in text if ord(char) < 128) | 94a003856809eb740b5c85af094095acb2e07dad | 29,211 |
def get_allowed_tokens_from_config(config, module='main'):
"""Return a list of allowed auth tokens from the application config"""
env_variable_name = ""
if module == "main":
env_variable_name = 'DM_ANTIVIRUS_API_AUTH_TOKENS'
elif module == 'callbacks':
# though SNS uses the "Basic" auth... | ade52605bf0c390091fc201a01c010ec8d1a0a46 | 608,274 |
import torch
def load_checkpoint(checkpoint_file, model, model_opt):
"""
Loads a checkpoint including model state and running loss for continued training
"""
if checkpoint_file is not None:
checkpoint = torch.load(checkpoint_file)
state_dict = checkpoint["state_dict"]
start_ite... | ea9239646bb74cf5b9ff9a2ffa39e2ab96d9a2ed | 66,087 |
def new_session(graph, expire_on_commit=False):
"""
Create a new session.
"""
return graph.sessionmaker(expire_on_commit=expire_on_commit) | 14376529c4d7737450a4ed420c93b7d6bb9a3275 | 485,849 |
def unique_column_name(df, name):
"""
Generate a column name that is not already present in the dataframe.
"""
i = 1
newname = name
while newname in list(df):
i += 1
newname = '%s_%d' % (name, i)
return newname | 61adf22cf7da2b502a49a6a8ff00506277104a31 | 308,064 |
import typing
def is_unpackable(obj: typing.Any):
"""
Checks if the given object is unpackable or not (if you can use **obj or not)
"""
return all(hasattr(obj, attr) for attr in ('keys', '__getitem__')) | 27a3cd1c6bdff581411796c4f4b1d3caa9f04ad0 | 269,543 |
def replace_user_in_file_path(file_name, user):
"""Replace user name in give file path
Args:
file_name (str): Path to file
user (str): New user to replace with
Returns:
str: New file path
"""
file_items = [x.strip()
for x in file_name.strip().split('/') if... | db4426f99cd6930d7edc8277e5c5ecf1870853e4 | 124,816 |
def dictget(d, l):
"""
Lookup item in nested dict using a list of keys, or None if non-existent
d: nested dict
l: list of keys, or None
"""
try:
dl0 = d[l[0]]
except (KeyError, TypeError):
return None
if len(l) == 1:
return dl0
return dictget(dl0, l[1:]) | 8adc8d795700e622f4c8c384ed65b38abd44f0d1 | 257,789 |
def y_intersection(line_slope, intercept, x_value):
"""
Finds the y value of the line (y = mx + b) at point x and returns the point
This basically solves y = mx + b
:param line_slope: slope of the line (m)
:param intercept: the intercept of the line (b)
:param x_value: the value to be used (sub... | 0b96f1fcce597a48ae88f286b543fed5c0e7917e | 327,386 |
def jaccard_distance(label1, label2):
"""Jaccard distance metric"""
union_len = len(label1 | label2)
intersection_len = len(label1 & label2)
return (union_len - intersection_len) / float(union_len) | c1d025eff5eae5ab3d1558e35f43e137c5e5d65d | 374,667 |
def create_id(fname: str, lname: str) -> str:
"""Create a player ID from a first name and last name.
String format: <first 5 characters of last name><first 2 characters of first name><01>
The last two integer digits allow for the prevention of ID conflicts.
To increment by an integer n, use add_n(player... | b67279adca01076723d81a34c69af3186c044fc6 | 511,864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.