content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pathlib
def about_package(init_posixpath: pathlib.Path) -> dict:
"""
Return package information defined with dunders in __init__.py as a dictionary, when
provided with a PosixPath to the __init__.py file.
"""
about_text: str = init_posixpath.read_text()
return {
entry.split(" = ... | 4e43c305ecf784e8355d2ab9ac735c18b7346881 | 627,624 |
def divide_to_keys(dict_all_embeddings):
"""
Distinguish between types of embedding methods - ours and state-of-the-art
:param dict_all_embeddings: dict of all embeddings
:return: Names of our methods, names of state-of-the-art methods
"""
keys_ours = []
keys_state_of_the_art = []
keys =... | fe88a8a7a515a8d09b8aa541e56c3fa22b91554d | 627,625 |
import itertools
def combine_strings(target_strings, r_strings, n_collisions):
"""Combines the r_strings with the target strings until the desired number of collisions is reached"""
i = 0
ret = target_strings.copy()
while True:
i = i + 1
for s in itertools.product(r_strings, repeat=i):... | fe2dac9bfabb9d79a116937e92158f7b4333b4f9 | 627,627 |
import requests
from bs4 import BeautifulSoup
def get_valid_urls(url, break_url):
"""
Get valid urls from sitemap.xml. Note: only links after group-49 are valid for download.
- url: the link to stemap.xml
- break_url: the url link to the group-49
>>> url = "https://apkpure.com/sitemap.xml... | f12afcce54d873239bfe621eaa2ee640a8879329 | 627,628 |
def get_correlation_values(cors, r, c):
"""
Gets correlation between properties r and c for all files
Parameters
----------
cors : list
propertiess correlations per file
r : int
first property index
c : int
second property index
Returns
... | da02af082d947a371c66fce87ef9a961cf00283e | 627,629 |
import platform
def is_amd64():
"""
Check if script is running on an AMD64 system (Python can be 32/64, this is for subprocess)
"""
return platform.machine().endswith("64") | a0e77c75cf1b2dbe6b8857ec8218438a6a787e01 | 627,630 |
import requests
import json
def get_vendor_from_mac(mac):
"""Get the vendor from the MAC using an API"""
url = "https://mac2vendor.com/api/v4/mac/"
mac_str = "".join(mac.split(":")[:3])
try:
r = requests.get(url + mac_str)
response = json.loads(r.text)
if not response["success"... | 271c855d7d8f9ec8ae124e20899273b305b4b807 | 627,631 |
from numpy import array, roll
def uniq(x, index=None):
"""Replicates the IDL ``UNIQ()`` function.
Returns the *subscripts* of the unique elements of an array. The elements
must actually be *sorted* before being passed to this function. This can
be done by sorting `x` explicitly or by passing the ar... | 4ac47d47d5866c6ce3fbd0beeb0b5140071a7e6d | 627,632 |
def next_name(container, key):
"""
Given a container object and some key prefix, yield the next key with the
given prefix that is not contained into container.
"""
if key not in container:
return key
for i in range(1, 1000):
test = f"{key}_{i}"
if test not in container:
... | d7b7e660a97b7586e162c7517ade46151b65e534 | 627,633 |
def measurement_exists(cur, project_key, id):
"""
Check whether the measurement exists in the database in the given project.
"""
measurement = cur.execute(
"SELECT * FROM measurements WHERE id=? AND projects_key=?", (id, project_key)
).fetchone()
if not measurement:
return False... | d5b8392813960a50364640692aeb12d7b694a44b | 627,634 |
def _escape_markdown_literals(string):
"""Escape any markdown literals in ``string`` by prepending with \\
:type string: str
:rtype: str
"""
literals = list("\\`*_{}[]()<>#+-.!:|")
escape = lambda c: '\\' + c if c in literals else c
return "".join(map(escape, string)) | 235571211707919e1f08329dc45d6461e5a0d63d | 627,635 |
import warnings
def divide2(a, b):
"""Return a/b.
If b = 0, raise a warning and return the NaN ("Not a Number") value."""
if b == 0:
warnings.warn("Division by zero !")
return float("nan")
else:
return a/b | 7c940b49a142f77417381702ea853e69115f18f5 | 627,637 |
def filterEvents(eventDict, currentTime):
"""
:param eventDict: event dictionary at time Current time
:param currentTime: the time wanted to be taken care of
:return: dictionary of filtered events that are opened at time Current time
"""
return {e['id']: e for e in eventDict.values() if not e['a... | 56c9e62b70eb5a2414da7e08ebe90c58ace1c593 | 627,638 |
def _req_content_type_property():
"""
Set and retrieve Request.content_type
Strips off any charset when retrieved
"""
def getter(self):
if 'content-type' in self.headers:
return self.headers.get('content-type').split(';')[0]
def setter(self, value):
self.headers['con... | 5eaa1ef0ddf58502eeb48adaee7fc88a9166d145 | 627,639 |
import torch
def clip_linear(values, a, b):
"""Clip values to [-1, 1]
Input:
- values(torch tensor): values to be clipped
- a (float): coefficient
- b (float): intersection
Output: (torch tensor) clipped values
"""
return torch.clamp(values * a + b, -1, 1) | 3e2e909814b2c3e46635e2b68c06ab66f063f56f | 627,640 |
def coverage2_rule(M, i, j, w):
"""
Shift spans beginning of some day other than the first day.
:param M: Model
:param i: period
:param j: day
:param w: week
:return: Constraint rule
"""
return sum(M.Shift[M.n_prds_per_day.value + (i - p), j - 1, w, l, t]
for l in M.... | e4c33dc30894973ce4ede339af7857507dc7862f | 627,641 |
def trim(s):
"""Deletes whitspaces in a string before and after a word."""
res = ""
for i in range(len(s)):
if i == 0 and s[i] == " ":
continue
elif i == len(s) - 1 and s[i] == " ":
continue
else:
res += s[i]
return res | 2764d8fa3d1e69b40668824615390038c3427d0b | 627,642 |
import math
def calculate_shot_distance(play):
"""Parses a play and returns the distance from the net.
Args:
play (dict): A dictionary of a penalty play attributes.
Note:
dist_string (String): distance with unit (foot / feet)
"""
event_x = abs(play['coordinates']['x'])
event... | 6cec00d4b7e2ccb613137fb8afc2f641266ce618 | 627,643 |
def to_camel_case(snake_str):
"""
Converts snake_string to camelCase
:param str snake_str:
:returns: str
"""
components = snake_str.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | 4245decbef1fd052c57f7ebe74e6b55d7238db1d | 627,644 |
import typing
import textwrap
def WrapText(text: str, length: int) -> typing.List[str]:
"""
A function that wraps text.
Parameters
----------
text : str
The text to wrap.
length : int
The length to wrap the text at.
Returns
-------
typing.List[str]
A list ... | 9fa22bbcc075bfd068f124822c761d4509b16147 | 627,645 |
import re
def pixivShorten(url):
"""
pixiv 短链接
:param str url:
:return:
"""
pid_search = re.search('pixiv.+illust_id=([0-9]+)', url)
if pid_search:
return 'https://pixiv.net/i/' + pid_search[1]
uid_search = re.search('pixiv.+member\\.php\\?id=([0-9]+)', url)
if uid_search:
... | f3e8e1e9bc8f4a05a287bd1d18bd955c45bd6283 | 627,646 |
import os
def platform_delay():
"""
It is typical for a platform to have some internal delay
that is inherent to the hardware.
"""
if os.path.exists('/run/vyatta/platform/ufi.s9500-30xs'):
return 50
return 0 | 28e764930409e5efe83ae89e57aeca63fa579251 | 627,647 |
def data_split(dataset, n_test_set=30):
"""
split data into train and test sets
Arguments:
----------
dataset: pd.DataFrame
- time series dataset
n_test_set: int
- the last n data points
Returns:
--------
X_train : pd.DataFrame
- training set
X_test : pd... | 9ddf63e3355ee8c6e77356c4ab75e40600a99de6 | 627,648 |
def check_equal(lst):
""" Return True if all items in `lst` are equal, False otherwise.
Note that check_equal([1, True]) is True.
"""
return not lst or lst.count(lst[0]) == len(lst) | b35a560d4e7cf1d52142ed79bfa3ea0b549cc3a2 | 627,649 |
import re
def match_first(string, prefix_infos, key):
"""Match string against each regex. Return first match, or None"""
for prefix_info in prefix_infos:
regex = prefix_info.get(key)
if regex:
match = re.match(regex, string)
if match:
prefix_info["match... | b8722d0393aff5f378893025957cfd31e27caead | 627,650 |
def str2bool(string):
"""
converts a string into a bool
"""
if string == True:
return True
if string == False or string[:1].lower() == 'f' or string[:1].lower() == 'n':
return False
else:
return True | f5c70f9948e12c7fd159be1532ed71ce25385c5f | 627,651 |
def sign(x):
"""
Returns the sign of x.
:param x:
:return:
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 | bcbbcda206c0c2c45983554449850eabbd19d842 | 627,652 |
import re
def grep(regex, output):
"""Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the exp... | 7b09acac1a268caf89a3268f8272696f4a1dee2f | 627,653 |
import uuid
def generate_enrollment_record_data() -> dict:
"""Helper method for generating data for an EnrollmentRecord"""
return {
"csp_user_uuid": uuid.uuid4(),
"first_name": "Bob",
"last_name": "Testington",
} | d4cbe12723a04734029c66f51643a59c1f329b26 | 627,654 |
import six
def _to_byte_string(value, num_bits):
"""Convert an integer to a big-endian string of bytes with padding.
Padding is added at the end (i.e. after the least-significant bit) if
required.
"""
shifts = six.moves.xrange(num_bits - 8, -8, -8)
byte_at = lambda off: ((value >> off # noqa... | a694617ea8669e158115e750b5ae782f16c63512 | 627,655 |
def arr_contain(arr, val):
"""
数组是否包含 val
:param arr:
:param val:
:return:
"""
# 判断是否存在
for key in arr:
if key == val:
return True
return False | 22642b0be13ca79ca890aa55f19d459329dc1d83 | 627,656 |
import torch
def to_onehot(indices: torch.Tensor, num_classes: int) -> torch.Tensor:
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...) and of type uint8. Output's device is equal to the
input's device`.
"""
onehot = torch.zeros... | d677812dc217d5408e784e94c5e9e88526e7a674 | 627,657 |
def split_frg(idx_parts, list_parts_quality):
""" splitting a fragment dictionary
input: a fragment dictionary and a dic_idx_parts={brcd:{0:{1,2,3}, 1:{4,5,6},... },..}
output: a dictionary, key: barcode values:
split those rows with the same barcode but came from different molecules
"""
di... | 94751b12912248ebadb7ac803f55f8f3611affed | 627,658 |
def usage():
"""Provide usage instructions"""
return '''
NAME
run_tests.py - pycsw unit test testrunner
SYNOPSIS
run_tests.py -u <url> [-l logfile] [-s suite1[,suite2]]
Available options:
-u URL to test
-l log results to file
-s testsuites to run (comma-seperated list)
... | e0c5f983477c7fb13fec6e33b4592986d60ff407 | 627,659 |
def generate_chunk_data_list(size, data_size):
"""
generate a lit of data chunk enpoints
"""
L = []
idx = 0
while idx < size:
L.append((idx, min(idx + data_size - 1, size - 1)))
idx += data_size
return L | 390b74b26771dd0c63028e85f6e3f1fcbfbd559e | 627,660 |
def get_subcommand_kwargs(mgr, name, namespace):
"""Get subcommand options from global parsed
arguments.
"""
subcmd = mgr.get(name)
subcmd_kwargs = {}
for opt in list(subcmd.args.values()) + list(subcmd.options.values()):
if hasattr(namespace, opt.dest):
subcmd_kwargs[opt.des... | 4cc91e7d71df39f4adce8849942a3ec0b696658a | 627,661 |
import random
def block_permutation(preserve_symmetry = True):
"""Choose order to rearrange rows or columns of blocks."""
if preserve_symmetry:
return random.choice([[0,1,2],[2,1,0]])
result = [0,1,2]
random.shuffle(result)
return result | 087199eca4b462eb9745054bb898227c86e2f99b | 627,662 |
def first_char_is_number(text):
"""Check if string starts with a number."""
return text[0].isdigit() | 1caa7978b6dd9e7cca1200a905026d6f9de92a65 | 627,663 |
def extract_authors(pubs):
"""Get list of author IDs from a list of namedtuples representing
publications.
"""
l = [x.author_ids.split(";") for x in pubs if isinstance(x.author_ids, str)]
return [au for sl in l for au in sl] | dd128f8e5ccba16ed7c83f5d15fe3ca269bf6616 | 627,664 |
def partition(array, start, end):
"""
Perform Partition Operation on array a.
Time Complexity: O(nLogn)
Auxiliary Space: O(n)
:param a: Iterable of elements
:param start: pivot value for array
:param end: right limit of array
:return: return i value for function, used in partitioning of ... | 4f1cc2e2ffee5014a1ddfe4ecdeb2ff71d4bd4f8 | 627,665 |
def no_perf_degrad(optimzed_time: float, non_optimized_time: float, rtol: float = 5e-2) -> bool:
"""Assert no performance degradation.
Args:
optimzed_time (float): [description]
non_optimized_time (float): [description]
rtol (float, optional): Max tolerant runtime degradation. Defaults ... | 8b02fdfa87e33d3cc27a13c7338d2be22f85588a | 627,666 |
def flatten_model_colnames(model_colnames):
"""
From a dict that maps model name to a list of field names, generate a list with string elements `<module>.<field>`.
"""
flat_colnames = []
for modelname, colnames in model_colnames.items():
flat_colnames.extend([modelname + '.' + c for c in col... | c75ce44c76e984696f90dcbf35dc223df380045f | 627,667 |
import os
def files_match(path1, path2):
"""Checks if the filename1 (from path1) and filename2 (from path2) without extension are the same."""
return os.path.splitext(os.path.basename(path1))[0] == os.path.splitext(os.path.basename(path2))[0] | 7b92a0daeee2febda504eaf36fd4e2901a03ab0b | 627,668 |
def line_plot(ax, x, ys, labels=None, styles=None, param_dict=None):
"""
A helper function to make a line graph
Parameters
----------
ax : Axes
The axes to draw to
x : array
The x data
ys : array
The y data
labels : list
The ys labels
param_dict : di... | 837867df9029f9a1c78cf448079e19e3ba9a17b3 | 627,669 |
def match_cur_window(cur_window, num_template):
"""
判断给定window的切块是否与数字模板匹配
:param cur_window:
:param num_template:
:return: True 匹配, False 不匹配
"""
is_match = True
for x, y in num_template: # (x, y) point need to be 255
if cur_window[x, y] == 255:
is_match = False
... | 5602615ef08704592b3e17de844e0b0382b49551 | 627,670 |
def _intersect(a, b):
"""Returns the Intersection of two sets.
Returns common elements of two iterables
._intersect("apples", "oranges") returns "aes"
Args:
a, b: iterables that can be compared
Returns:
list of common elements between the two input iterables
"""
retu... | ab8cd7c1f4f27c0db4d0bf4c45cc047bbcf31bde | 627,671 |
def ismount(path):
"""Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
system where a different file system has been mounted. The function checks
whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
or whether :file:`path/..` and *path* p... | 802bab8a1ff5a2fc28669d6208050b04586ecdc8 | 627,672 |
def create_simple_dict_from_word_list(word_list):
"""
DEPRECATED: Use create_dict_from_word_list
word_list (list): a list of words
Returns a dict of {'a':[words starting with 'a'], 'b':[words starting with 'b'], etc...}
"""
word_dict = {}
for word in word_list:
if len(word)... | f510a0b9b60219cdd81e76f0d8e10d77698749cb | 627,673 |
def jenkins_api_query_build_statuses(jenkins_url):
"""Construct API query to Jenkins (CI)."""
return "{url}/api/json?tree=builds[result]".format(url=jenkins_url) | eb8625ba17dfb6f630701f4356cbcce6a6d39265 | 627,674 |
def PreOpN(op, items):
""" Naive PreOp algorithm """
k = len(items)
output = [None]*k
output[0] = items[0]
for i in range(1, k):
output[i] = op(output[i-1], items[i])
return output | 1c5912f2689596012bacbe6c45559f5c52a1922f | 627,675 |
import torch
import copy
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList(copy.deepcopy(module) for _ in range(num_copies)) | 044e2f6742760c0e46b2ad9c961e646f1d04c6df | 627,676 |
from typing import Any
def _get_dot_attrib(obj, elem_path: str) -> Any:
"""Return attribute at dotted path."""
path_elems = elem_path.split(".")
cur_node = obj
for elem in path_elems:
cur_node = getattr(cur_node, elem, None)
if cur_node is None:
raise KeyError(f"{elem} valu... | 0789bd0b35a7de81924495e13ae89a763bd6b7f9 | 627,677 |
def mock_subparsers_fixture():
"""Fixture for mocking a subparsers object from argparse."""
class MockSubparsers: # pylint: disable=too-few-public-methods
"""Mock subparsers from argparse."""
def __init__(self):
self.parsers = []
def add_parser(self, *args, **kwargs):
... | b4072e8b6f43f5d47c51b80c72c97b2de0b59062 | 627,678 |
def class_result(classname):
"""Errcheck function. Returns a function that creates the specified class.
"""
def wrap_errcheck(result, func, arguments):
if result is None:
return None
return classname(result)
return wrap_errcheck | c0fe0b36863637fd2b73ae562301968af944f522 | 627,679 |
def integer_if_integral(x):
"""Convert a float to int if it can be represented as an int"""
return int(x) if x == int(x) else x | 88f61d2792612f8108728a76d1eb8eb9b4c0abe6 | 627,680 |
import requests
def neuralcoref(text):
"""
State-of-the-art neural coreference resolution system based on neural nets and spaCy,
Coreference is the fact that two or more expressions in a text – like pronouns or nouns – link to the same person or thing. It is a classical Natural language processing task, ... | 8dd6d293ed165d500f5f5b906cd8bcc380d2214c | 627,681 |
def proportion_of_energy_delivered(sim):
""" Calculate the percentage of total energy delivered over total energy requested.
Args:
sim (Simulator): A Simulator object which has been run.
Returns:
float: Proportion of total energy requested which was delivered during the simulation.
"""... | 48a6dc2f4f81317c838b0e040937adb488760d48 | 627,683 |
import random
def make_sms_code():
"""
短信验证码
:return:
"""
return str(random.randint(1000, 9999)) | 653e6b7c0b9c44d910ed77b0c10aad58fbee35a8 | 627,684 |
def d(d):
"""Decode the given bytes instance using UTF-8."""
return d.decode('UTF-8') | 07efd6024ddf39b2e2e592457d9d52d2256cfc22 | 627,685 |
from bisect import insort_left
def test_count_num_of_rectangles():
"""
Given a set of points on 2d coordinates,
find how many right rectangles we can connect those dots
"""
def count_rect(ps):
# create hashmap of all points : Y -> X
# Complexity : O(p)
ymap = {}
for x,y in ps:
if y not... | 85a5072d2f55b50d259427ead0e29461f4e80959 | 627,686 |
def profile_key(prof):
"""Get the sort key for profiles."""
if prof == 'core':
return (0, prof)
return (1, prof) | 88d7a0c6955852ef1ccb4fbce340e48ed7b295df | 627,687 |
def identify(rod, x, y):
"""Adds chip ids (chip_x, chip_y) to the key for a rod
Args:
rod: dict of (x, y): [values]
x: x coordinate that identifies the source chip
y: y coordinate that identifies the source chip
Returns:
dict: {(chip_x, chip_y, x, y): [values]}
... | 1fd1b94c87d2bcd4f685d3d8738deab026ad002c | 627,689 |
def datagenerator_affine(gen,test = False):
"""
Datagenerator for the affine network (both stages)
Args:
gen: an image generator, loading the image, indicator, loss placeholders and landmarks
test: True in case we test the function
Returns:
generator to train the affine networ... | 9018412abb087d48f61a9756d304f0b658b30fe6 | 627,690 |
from typing import Dict
from typing import Any
def get_value_len(dct: Dict[Any, Any]) -> Dict[Any, int]:
"""Get length of each dictionary value.
Args:
dct: Python `dict()` object.
Returns:
`dict()` object.
Example:
>>> status_codes = {
200: ['google.com', 'so... | 9f8cd9e6d08bd624c1666eba691dea7fc40e6767 | 627,691 |
def desktop_agent_headers():
"""
Use this in headers to act as a Desktop
"""
return {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"
} | d4016c3f8967ba869d98625a82bd214a7a118064 | 627,692 |
def plant_pm_heat_rates(annual_gen_fuel_923):
"""
Calculate the heat rate by plant, prime mover, and fuel type. Values are saved
as a dictionary.
Parameters
----------
annual_gen_fuel_923 : dataframe
Data from the 923 generation and fuel use table. Heat rate for each row should
... | 028fbe063d301a27bbc8dc6ee8fbc0b1d03f5463 | 627,693 |
import os
def parse_info_from_name(preprocessed_dirname):
"""! Given a name of a preprocessed dataset root dirname infer all the
encoded information
Args:
preprocessed_dirname: A dirname as the one follows:
wsj0_2mix_8k_4s_min_preprocessed or even a dirpath
Returns:
min_or_ma... | 1d0dd70c020ccd85554a9735aefc73bf177bec18 | 627,694 |
def djb2(self, key):
"""
DJB2 hash, 32-bit
"""
# Cast the key to a string and get bytes
str_key = str(key).encode()
# Start from an arbitrary large prime
hash_value = 5381
# Bit-shift and sum value for each character
for b in str_key:
hash_value = ((hash_value << 5) + hash_... | bca616b6ec1d84063d66cab6d4f379414d474f23 | 627,696 |
import hashlib
def hash_nested_tuple(tup):
""" Hash a nested tuple to hexadecimal """
return hashlib.md5(repr(sorted(tup)).encode('utf8')).hexdigest() | 2662cea34043e3b13c1570d740ca109a209a306e | 627,697 |
import argparse
def parse_command_line_args():
"""
Parse command-line arguments.
Returns:
args (class 'argparse.Namespace'):
An object containing the parsed command-line arguments.
For every command-line option, the values are stored as follows:
args.{option}
"""
# Initiate the argument parser
par... | 6fb67132478edb7a8bf210347a9ce7c37d936c1e | 627,698 |
def get_icon_detail(icon_details):
"""
Iterate over icon details from response.
This method is used in "risksense-get-apps" command.
:param icon_details: Icon details from response.
:return: List of required icon detail dictionary.
"""
return [{
'Type': icon_detail.get('type', ''),
... | c21181a6135ff9982a1ce549c21fc497f03f3788 | 627,699 |
def _maybe_parse_as_library_copts(srcs):
"""Returns a list of compiler flags depending on `main.swift`'s presence.
Builds on Apple platforms typically don't use `swift_binary`; they use
different linking logic (https://github.com/bazelbuild/rules_apple) to
produce fat binaries and bundles. This means t... | 0661f70e4ffca4f04d76c4ab0f442683355e0c61 | 627,700 |
def wait_for_line(input_string):
"""
Should the intepreter wait for another line of input or try to evaluate the
current line as is.
"""
trailing_ops = ['+', '-', '/', '*', '^', '=',
'>', '<', '/;', '/:', '/.', '&&', '||']
if any(input_string.rstrip().endswith(op) for op in t... | 903e987a807795e0b6eb719462563326329131b9 | 627,701 |
from typing import OrderedDict
def get_parameters_from_path(store, paths, **kwargs):
"""
Gets parameters from the specified paths and combines them
into one dictionary. Values that are the same WILL be overwritten.
Arguments:
store {EC2ParameterStore} -- The AWS Parameter Store you wish t... | 8d06c1c9f79c19e029b2c64931a199ae88d24728 | 627,702 |
import torch
def construct_diag(x):
"""
Constructs a diagonal matrix based on batched data. Solution found here:
https://stackoverflow.com/questions/47372508/how-to-construct-a-3d-tensor-where-every-2d-sub-tensor-is-a-diagonal-matrix-in-p
Do note that it only considers the last axis.
:param x: The... | d622fc0681498ba878990090d80855760d545ab9 | 627,703 |
def dim(self):
"""Return the dimensionality of the ambient space."""
return self.shape[-1] | 6e41cc940ec8626c646564bf6887664caac52df2 | 627,704 |
import random
def calculate_total_expected_execution_time(load_size: int) -> float:
""" Total time consumer-master should buffer out slave invocations for"""
if load_size < 500:
total_expected_execution_time = 70
else:
total_expected_execution_time = random.randint(50, 70)
return total... | 55439a0edf69c7b42462db39390224b42ce1b338 | 627,705 |
import random
import string
def random_id(length: int = 8) -> str:
"""Sample a random string to use for job id."""
return "".join(random.sample(string.ascii_letters + string.digits, length)) | bf1cde20f62b5429b02a1f85e42d8e4de8630231 | 627,706 |
import logging
import os
import yaml
import glob
def load_data_from_filesystem(collection=None, device=None, state=None):
"""Loads all known data for a given device or an entire collection
from the file system (/netbox) in a given state.
"""
if not state or state in ["0", "None"]:
state = "a"... | 42bcb5a2b163060fba75699c7fac59921e961824 | 627,707 |
def param_uses_64bits(param):
"""Returns True iff a syscall parameter description corresponds
to a 64-bit type."""
param = param.strip()
# First, check that the param type begins with one of the known
# 64-bit types.
if not ( \
param.startswith("int64_t") or param.startswith("uint64_t"... | 24098bf43fd7e999a86574120f5de1415f7eb47e | 627,708 |
def contingency(set1,set2,all_genes):
"""Creates contingency table for gene enrichment
set1: Set of genes (e.g. regulon)
set2: Set of genes (e.g. i-modulon)
all_genes: Set of all genes
"""
tp = len(set1 & set2)
fp = len(set2 - set1)
tn = len(all_genes - set1 - set2)
... | d52a7f6f291d66095b6a62073eef8025f4a097da | 627,709 |
def lastFrameFromSegmentLength(dist, first_frame, length):
"""Retrieves the index of the last frame for our current analysis.
last_frame should be 'dist' meters away from first_frame in terms of distance traveled along the trajectory.
Args:
dist (List[float]): distance along the trajectory, incr... | 3e85a8814da1f17dd8e3f9136e5e1682cc09bcd5 | 627,710 |
def lyrics_to_frequencies(wordlist):
"""
wordlist (list): list of words (strings) of song lyrics
Returns a dictionary mapping different lyrics words to their frequencies or number of occurences
"""
myDict = {}
for word in wordlist:
if word in myDict:
myDict[word] += 1
... | c4b2ee8216281eb0675b2146fe87f077f3f130be | 627,711 |
import time
def get_timestamp(date_time):
"""
Create a `timestamp` from a `datetime` object. A `timestamp` is defined
as the number of milliseconds since January 1, 1970 00:00. This is like
Javascript or the Unix timestamp times 1000.
"""
return time.mktime(date_time.timetuple()) * 1000 | 482cfce4f6314a40ac0e51c8763aa4d4fb533541 | 627,712 |
def presjek_strugotine(dubina_rezanja, posmak):
"""
presjek_strugotine [mm2]
\tdubina_rezanja [mm]\n
\tposmak [mm/okr]
"""
return dubina_rezanja*posmak | d5d903f0502226adfcecd7d04ada3377bb9dd2db | 627,713 |
import re
def clean_text(text):
"""
텍스트를 정규화하기 위하여 입력된 text로 부터 스페셜 문자 제거
Args:
text: (string) text string which may contain special character
Returns:
normalized sentence
"""
text = re.sub('[-=+,#/\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`…》]', '', text)
return text | 201c4c51230ccc3e0bb2c44ecccc0cad92ecf7ec | 627,714 |
import random
def double_biased_coin_urn(control_success, control_trials,
treatment_success, treatment_trials,
control_name=None, treatment_name=None,
seed=None):
""" Returns a group assignment for adaptive trials using the Double Bi... | b6a9fc0fe6282bbae19ff6d040a96b9c37b2bb1b | 627,715 |
import time
def time_it(method):
"""
Timing decorator that outputs how long an algorithm takes to find or not find a path
:return: wrapper function
"""
def wrapper_time_it(self):
start_time = time.time()
method(self)
print("", end="\r")
print(f"The search algorithm... | 14b882b5b2395a782951fae3c002cde22bd0a56a | 627,717 |
def getattr_deep(obj, attrs):
"""
Like getattr(), but checks in children objects
Example:
X = object()
X.Y = childobject()
X.Y.variable = 5
getattr(X, 'Y.variable') -> AttributeError
getattr_deep(X, 'Y.variable') -> 5
:param obj: object
:param attrs: attribu... | 1d9165ee550ce0fb442533982dcc1c5cbfad8fc3 | 627,718 |
def chunk_file(fname, *, limit=5000, start_num=0):
"""
This function is inexorably tied to extras.fetch_eddb.jq_post_process.
Importantly jq doesn't wrap in list brackets or end in ','
Take any file with fname. Chunk that file out with limit lines per file.
Each chunk will be written to a file with... | dd39a73660c3eadcb7d928bfd675e22def0ada5c | 627,719 |
def _to_module_name(fn):
# type: (str) -> str
"""
Try to guess imported name from file descriptor path
"""
fn = fn.replace('/', '_dot_')
fn = fn[:-len('.proto')] # strip suffix
fn += '__pb2' # XXX: might only be one underscore?
return fn | 2569b8ecc7736bab9045e62e4650e823e3a56190 | 627,720 |
def convert_pad_shape(pad_shape):
""" Used to get arguments for F.pad. """
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape | e267511ff8bce7c1782be21fdc9e5d4325be016a | 627,721 |
def get_base_url(parsed):
"""Convert a parsed URL back to string but only include scheme, netloc, and path, omitting query."""
return parsed.scheme + "://" + parsed.netloc + parsed.path | 21df200efbd72eab7ea844e3d8b5466170eac5c9 | 627,723 |
import ctypes
def chromatic_to_voltage_table(degrees):
"""
Convert a list of chromatic scale degrees to a binary voltage table.
"""
# roll out the degrees to 100 entries
unrolled = [degrees[i%len(degrees)]+12*(i/12) for i in range(100)]
# create a list of codes for each semitone
codes = [i... | c9db1b951dfa661a7b283c7c98177b142ce56291 | 627,725 |
import os
def datePathFn(path):
""" Given pathname for a file , return a pair of the pathname and
the modification date
"""
return (path, os.path.getmtime(path)) | 5787529fede1fce520720be48b068231871a7af0 | 627,727 |
def add(first_number, second_number):
"""
>>> add(1, 2)
3
>>> add(1.1, 2.2)
3.3000000000000003
>>> add(-1.1, 1.1)
0.0
"""
return first_number + second_number | 16c8a7a8ea02285732710c940bd11f9930a7eec4 | 627,728 |
import re
def css_colour(s):
"""Is string a valid CSS colour."""
m = re.match(r'^(?:[0-9a-fA-Z]{3}){1,2}$', s)
return m is not None | 82066d04b2504179e40a70f84c8939af335285ac | 627,729 |
import os
def sysname():
"""Returns the os.uname().sysname field."""
try:
return repr(os.uname().sysname)
except:
return repr('unknown') | e61c9ed8181fd9f0b59ac846b35e8cfea310fc0f | 627,730 |
def to_str(text, session=None):
"""
Try to decode a bytestream to a python str, using encoding schemas from settings
or from Session. Will always return a str(), also if not given a str/bytes.
Args:
text (any): The text to encode to bytes. If a str, return it. If also not bytes, convert
... | 74bcec023a7a8afea69c24a3dc2d7ae41247f461 | 627,731 |
def get_regression_predictions(input_feature, intercept, slope):
"""
Purpose: Compute predictions
Input : input_feature (x), intercept (w0), slope (w1)
Output : Predicted output based on estimated intercept, slope and input feature
"""
predicted_output = intercept + slope * input_feature
re... | be03ccb21abab4bac099ded636be07e67d4db2ae | 627,732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.