content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sort_by_username(user):
"""Sort students by their username"""
return user['username'] | d4e5dd7a5d682dfd67140632f9de419dc9c813f1 | 648,336 |
def rerouter_middleware(app):
"""
Reroute the root page to /vulnpy/. This is slightly irresponsible because we
don't call the wrapped application in this case.
"""
def wrapped_application(environ, start_response):
if environ["PATH_INFO"] in ("", "/"):
start_response("302 FOUND",... | 14762a0cf8c2e2ba1d85eb61b79b67f7d3c03461 | 648,337 |
def update_dictionary(dictionary, year, hurricane_name, data):
"""
checks if year from file isnt in dictionary
adds it if it is not
checks if there is data for each hurricane
adds the data if there is not
append data to data list inside hurricane dictionary inside year dictionary
:pa... | 1fd8caf90c2a4b43e4aa4ea9b5a82b99d9aaa2f5 | 648,338 |
def pattern_in_string(pattern: str, string: str) -> int:
"""
>>> pattern_in_string('aba', 'abababa')
3
"""
n = len(string) - len(pattern) + 1
return sum(string[i:].startswith(pattern) for i in range(n)) | 1c2090bee02b37d473b772e53391aa2131746887 | 648,339 |
def _sanitize_str_to_list(dim):
"""Make dim to list if string, pass if None else raise ValueError."""
if isinstance(dim, str):
dim = [dim]
elif isinstance(dim, list) or dim is None:
dim = dim
else:
raise ValueError(
f"Expected `dim` as `str`, `list` or None, found {di... | 94ed147b8d5b1762e987813362e7d5b7a112d22a | 648,340 |
import os
def get(request):
"""Fucntion to replicate GET method"""
if os.path.exists(request[1]):
f = open(request[1], "r")
data = f.read()
f.close()
return "200 OK", data
data = None
return "404 Not Found", data | 71e89895e117a51a01d19e9c1a937a382f1ca281 | 648,342 |
import math
def compute_stability_fm_h(H, t0, u_attr, r_air, hc, d0, z0m, cp=1004.16):
"""
To Match IDL, fh defaults to 0 for L values outside the range -100 to 100
It is unclear why the range -100 to 100 is used since L is forced to be < 0
Parameters
----------
H : ee.Image
t0 : ee.Imag... | c70c78ed44fab61a4d6fe48ae7d815a237a322fa | 648,343 |
def prepare(link:str):
"""A function to check if the link is complete (it includes the protocol)
and that it can be used by the library (it should not end with a slash)
Args:
**link (str)**: The link to check/prepare
Raises:
**Exception**: Thrown if the protocol is not present in the URL
Returns:
**str... | c26c0f1a50a95188721b33044dd434b466318bad | 648,344 |
def apply_slope_intercept(dicom_file):
"""
Applies rescale slope and rescale intercept transformation.
"""
array = dicom_file.pixel_array.copy()
scale_slope = 1
scale_intercept = 0
if "RescaleIntercept" in dicom_file:
scale_intercept = int(dicom_file.RescaleIntercept)
if "Rescal... | ea8e0bca934abac7b98a5bafe821905a43ccee94 | 648,345 |
def modularity(G, communities):
"""Compute Louvain modularity of graph G, given the partition `communities`.
:param dict G: the graph
:param dict communities: the communities each node is assigned to
"""
m = sum(
[w for _, neighbors in G.items() for _, w in neighbors.items()]
) / 2.0
... | 432e28135b0e8b291010f64b849d6943167e8efb | 648,346 |
def to_pandas_adjacency(G):
"""
Returns the graph adjacency matrix as a Pandas DataFrame.
The row indices denote source and column names denote destination.
Parameters
----------
G : cugraph.Graph
Graph containing the adjacency matrix.
"""
pdf = G.to_pandas_adjacency()
retur... | 96ae061c25d536c0b98d1923f9e4a9a3cb00c726 | 648,347 |
def read_structure(rdkit_conf):
"""Get structure from rdkit conformer"""
return rdkit_conf.GetPositions().tolist() | f3918934c198665ab0bb3b70a320a8e31a3972a6 | 648,348 |
def parse_response_item(item_response_list):
"""
The function parses GetItemsResponse and creates a dict of ASIN to AmazonProduct object
params:
*item_response_list*
List of Items in GetItemsResponse
return
Dict of ASIN to AmazonProduct object
"""
mapped_response = ... | 5a676e4c7c336f3334d860402ce2600d9a90f86d | 648,349 |
from typing import Iterable
def to_lower(text_docs_bow: Iterable[Iterable[str]]) -> Iterable[Iterable[str]]:
"""Converts all letters in documents ("bag of words" format) to lowercase.
Args:
text_docs_bow: A list of lists of words from a document
Returns:
A generator expression for all of... | 939e2ff1d4ff8b14c1bd785e7cb7e086444ad4f8 | 648,351 |
import random
def headers():
"""Generate a header
"""
# A fake device to avoid the Anti reptile
USER_AGENTS = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.5... | 1f4cd30db4348d0d7c2e9af90e58fc5d32e494d3 | 648,352 |
from unittest.mock import call
def main():
"""
Platform agnostic wrapper script for towncrier.
Fixes the issue (#7251) where windows users are unable to natively run tox -e docs to build pytest docs.
"""
with open("doc/en/_changelog_towncrier_draft.rst", "w") as draft_file:
return call(("t... | de155b7c80813e6b697a62bc595c1e6530f74452 | 648,353 |
def is_parameter(value):
"""Returns True if the given value is a reference to a template parameter.
Parameters
----------
value: string
String value in the workflow specification for a template parameter
Returns
-------
bool
"""
# Check if the value matches the template par... | 03e402ca07affe4cecc550d8aa27365660e74ee5 | 648,354 |
import math
def get_average_color(x, y, x_len, y_len, image, skip=1):
""" Returns a 3-tuple containing the RGB value of the average color of the
given square bounded area of length = n whose origin (top left corner)
is (x, y) in the given image"""
i = image.load()
r, g, b = 0, 0, 0
count = 0
... | 506f8dd794fe58d543e50fdaeb326bc285a0f1c6 | 648,356 |
def build_timeline_page_url_from_username(username):
"""
>>> build_timeline_page_url_from_username("username")
'https://mbasic.facebook.com/username?v=timeline'
"""
return "https://mbasic.facebook.com/{0}?v=timeline". \
format(username) | 232a056b62cc0f2836aee62251bb9f2c444b7b0f | 648,357 |
import re
def is_cnrm(sheet_cell):
"""Is this variable produced by CNRM?"""
if not sheet_cell:
return False
int_string = re.findall(r'-?\d+', sheet_cell)
if int_string:
if (int_string[0] == '1' or
int_string[0] == '2' or
int_string[0] == '3'):
retur... | db5e57b6cd39172545c6e920791e35cd55a57103 | 648,358 |
import codecs
def readfile(filename, mode="r", encoding="utf-8"):
"""Opens *filename*, reads it's contents and returns them as a string."""
if "b" in mode:
with open(filename, mode=mode) as fp:
return fp.read() # returns bytes, not str
else:
with codecs.open(filename, mode=mod... | 2b957fca63143b5578d2f8e52908f9f6e23793b6 | 648,359 |
import datetime
def convertfrom_epoch_time(epoch_time: "int | float"):
"""Takes a given epoch timestamp int or float and converts it to a datetime object.
Examples:
>>> now = get_epoch_time()\n
>>> now\n
1636559940.508071
>>> now_as_dt_obj = convertfrom_epoch_time( no... | 6aabd4ef1ceabcc522b7585dcd91938c9d4cfd4d | 648,360 |
def is_prime(number):
"""checks if a given number is prime"""
prime = True
for n in range(2, number):
if prime and number % n == 0:
prime = False
print("The number is not prime")
if prime:
print("The number is prime")
return prime | a6119b54e3ff16d7e94ad4ac06e224c623ee5dd1 | 648,361 |
import subprocess, datetime, os, time, signal
def set_usb_status_by_devcon(status, devid, timeout=120):
"""
using devcon to enable/disable the device.
using it must download the devcon.exe, and put it under c:\
"""
set_cmd = r"devcon.exe %s *VID_%s*" % (status, devid)
start = datetime.dateti... | 8f4edf0286596e04cf2e2c82ce890d3006d0ca66 | 648,362 |
def normalize(df):
"""Normalization: a data pre-processing step. Usually, making adjusting
loser and upper casing, abbrevations, word order, and so on.
Normalization must be a set of operations independent of data splitting.
** Vanilla definition. **
Include your own code below to import your proj... | 06968db47637040f5300e54c89ba6f6101ecfba8 | 648,363 |
def offset(elements):
"""get the offsets of the given element"""
startoffset = []
endoffset = []
length = 0
for elem in elements:
AllPrevious = elem.findAllPrevious()
for previous in AllPrevious:
if any(previous in p.findAllPrevious() for p in AllPrevious):
... | bc8bc475791a03a29d8db05b3dbcf36852427d08 | 648,364 |
def parse_args(argv):
"""Confirm params are correct"""
return len(argv) == 1 or len(argv) == 2 | 87f40ad6c92e71ba8aaf9024564d675117d35983 | 648,365 |
def distance_from_origin(position):
"""
Get the 'taxicab geometry' distance of a position from the origin (0, 0).
"""
return sum([abs(x) for x in position]) | 71975e73ed0192fce6cace6c4bcf3c5c23f47e8d | 648,366 |
def hex_mat_to_string(data):
""" Return string from hex matrix. Inverse of string_to_hex_mat"""
return ''.join([''.join([chr(h) for h in block]) for block in data]).strip('\x00') | c8852004eb5fc051a80ace51373e928197c74afd | 648,367 |
import re
def _camel_2_snake_case(name: str):
""" 驼峰转下划线式命名.
Args:
name:
name 中只包含: 大小写字母, 数字和点号
name 中数字不可以出现在开头
References:
https://www.yuque.com/tianyunperfect/ygzsw4/av4s8q
"""
name = (
name
.replace('QtQuick', 'qtquick')
... | cf20428db6e191918a78b7483ee6ce476ff42d81 | 648,368 |
def rel_error(a,b):
"""
Calculates the error between the 2 numbers
Input-
a -> 1st number
b -> 2nd number
Output-
error -> Difference between the 2 numbers
"""
error = a - b
return error | 386a21f79e8349e20e40d4e5841252339690793d | 648,369 |
import torch
def fftn(x):
"""
Applies n-dimensional Fast Fourier Transform (FFT) to input array.
Args:
x: Input n-dimensional array.
Returns:
n-dimensional Fourier transform of input n-dimensional array.
"""
out = x
for axis in reversed(range(x.ndim)[1:]): # We don't nee... | a97aaf2db8b2d6170a2cdae8d8b602ed43bf987d | 648,371 |
import re
def get_namespace(tag):
"""Returns the namespace of tag."""
m = re.match("^{(.*?)}", tag)
namespace = m.group(1) if m else ""
if not namespace.startswith("http://www.mediawiki.org/xml/export-"):
raise ValueError("%s not recognized as MediaWiki dump namespace"
... | b21b21f3d72c8ff0660e5ad69fbbd663c884a815 | 648,372 |
import argparse
import sys
def _parse_command_line():
"""Configure and parse our command line flags.
Returns:
Namespace. The parsed arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--portserver_static_pool',
type=str,
default='15000-24999',
... | e6a89b5ac95d9499c2364234bef35140b6f119c0 | 648,373 |
def getLonLatCrs(searchList):
"""get the correct names of the columns holding the coordinates
@param header Header of the CSV
@returns (lon, lat, crs) where lon, lat, crs are the column names
"""
lng = None
lat = None
crs = None
for t in searchList:
if t.lower() in ("longitude", ... | 5364e19c7b9312c66fa900ff042ba5f7c6c30777 | 648,374 |
def divisãoInteira (x, y):
"""
x, y são números
retorna quociente, resto, flag maior que 1, flag denominador 0
"""
if y != 0:
return x//y, x%y, x > y, False
else:
return None, None, x>y, True | 71d8baa264926123860bef90241d47b4489776d8 | 648,375 |
import json
def extract_aws_policies(action: str, client, managed: bool):
"""
Call the AWS IAM API to retrieve policies and perform an action with them.
:param action: what action to take with the IAM policies (list, dump)
:param client: the boto client to use
:param managed: (boolean) if true, i... | 5bf99bd20fbdde1accf2cbd00c99e83882c08104 | 648,376 |
def end_other(a, b):
"""
Function to compare two strings ending.
Given two strings, return True if either of the strings appears at the very
end of the other string, ignoring upper/lower case differences (in other
words, the computation should not be "case sensitive").
Args:
a (String)... | 690a19861f336c3b1d377e386253bd3960bec5e0 | 648,377 |
def compute_symmetric_dir_variance(K, alpha):
"""
compute the marginal distribution of \pi_1 for symmetric Dirichlet distribution
:param K: dimension
:param alpha: concentration paramegter for Dirichlet(alpha, ..., alpha)
:return: variance of marginal distribution of \pi_1
"""
common = 1. * ... | d5d9e6b4fa373c6560d5484c73437cb490518ef3 | 648,378 |
def parse_node_info_file(input_file):
"""
Parses the node info file and returns the translation of the nodes to
GeneID, UniprotAccession and GeneSymbol
"""
node_to_geneID = {}
node_to_uniprotacc = {}
node_to_genesymbol = {}
with open(input_file, 'r') as input_fd:
first_line = in... | 06d9ffdaa623359fb2b20ba7f2ad0d70b922f64c | 648,379 |
def preprocess(matrix, index):
"""
Takes as list of lists (in other words a matrix), and returns a list of
preprocessed sentences for all elements at the index specified for the
inner list.
For BERT models, dropping punctuation affects accuracy. See
https://www.aclweb.org/anthology/2020.pam-1.1... | 4b2ccc1075da4e54b04735a6a7ba578008dbc6a7 | 648,380 |
import os
def display():
"""
Get the availabel display.
:return: display, empty if none
:rtype: str
"""
if 'DISPLAY' in os.environ:
return os.environ['DISPLAY']
return None | 4d03a2c78d91911fdb38a4827e7b6268c4ecb4f3 | 648,381 |
from typing import List
def clean_literals(data: List[list]) -> List[list]:
"""
:param data: triples [s, p, o] with possible literals
:return: triples [s,p,o] without literals
"""
result = []
for triple in data:
if "http://" not in triple[2]:
result.append(triple)
re... | a66d78b38ae249a40ec705336b0833ce6efe47b3 | 648,382 |
def getCachedValue(cache, bits, generator):
""" Return and cache large (prime) numbers of specified number of bits """
if bits not in cache:
# populate with 2 numbers
cache[bits] = [generator(bits) for _ in range(2)]
# rotate, so each call will return a different number
a = cache[bits]
... | 8bbaa4ca48202407cda7de42c1512b6ef74ae755 | 648,383 |
def reduce_feats(df, featlist):
"""
Takes in a df and outputs only the given columns in featlist
:param df:
:param featlist:
:return:
"""
return df[featlist].copy(), [f'*arg* finalfeats = {featlist}'] | 1105296de96a62345a20873fb9411c4c2b39ec5a | 648,384 |
import os
def make_dir_if_not_exist(directory: str) -> str:
"""
Creates a directory if it doesn't exist yet.
:param directory: path
:return: path
"""
if not os.path.isdir(directory):
os.mkdir(directory)
return directory | dc63750f444a90384fae2472a9169bb349911b19 | 648,385 |
import os
def validate_path(path, allow_empty, isDirectory):
""" Check if a path exists and return the path with all variables expanded or raise AssertionError
>>> validate_path('/usr/bin')
/usr/bin
>>> import os
>>> os.environ['HOME'] == validate_path('~')
True
>>> validate_path('/dev/nu... | 50eb1cda79b415d61fdb8b42dbf49d179fccaaf4 | 648,386 |
def one_hot(i, n):
""" Makes a one-hot vector of length n with 1 in position i. """
one_hot = [0 for x in range(n)]
one_hot[i] = 1
return one_hot | 2c482899b68c547ca235e7f561ea4b676553f27c | 648,387 |
def convert36ToAscii(start, chs):
"""Convert decimal address to ascci address
:param start: NBP adress in decimal reverse:Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address
:param chs:tsring of all digits and ascii upper
:return:NB... | e8b00d5d0a49d4f128b84a4c874e268b5d92ca9e | 648,390 |
def read_all_commits(filename):
"""Read all commits from the given GIT log file."""
commits = []
with open(filename) as fin:
for line in fin:
splitted = line.strip().split(" ", 1)
commits.append(splitted)
commits.reverse()
return commits | fa56a84b0d5f6684fbcf362299b773d1d3939fa0 | 648,392 |
def list_of_2_pairs_key_value(self):
"""list of 2 pairs key value."""
self.pairs = [('u', 'uu'), ('v', 'vv')]
return self.pairs | 6cbe4715ddf11eb719cc5dfac15294247b99b991 | 648,393 |
def DetermineType(value):
"""Determines the type of val, returning a "full path" string.
For example:
DetermineType(5) -> __builtin__.int
DetermineType(Foo()) -> com.google.bar.Foo
Args:
value: Any value, the value is irrelevant as only the type metadata
is checked
Returns:
Type path stri... | 40154c8e9c678d8d2effa68584aeb058ef13a98f | 648,394 |
def optional(args, key):
"""If the given key is in args, return the corresponding value, otherwise
return None
"""
return key in args and args[key] or None | 23f3f158aa1ee473fb09e1a90650223f571d299e | 648,395 |
import math
def inverse_equirectangular_projection(x, y, center_coord=(0.0, 0.0)):
"""
Computes the projection from the map to the sphere
"""
center_lon, center_lat = center_coord
lon = x / math.cos(center_lat) + center_lon
lat = y + center_lat
return lon, lat | 6f37206f6dac65587e06400e55fa667c4e3a2ebf | 648,396 |
def get_correlation_metrics_from_args(args):
"""
Extract a list of correlation metrics to use from the program arguments.
"""
correlation_metrics = []
if args.pearson:
correlation_metrics.append('pearson')
if args.spearman:
correlation_metrics.append('spearman')
if args.kenda... | 39c8eb0aaad5f9a8c63c02a41157aab3149fb955 | 648,397 |
import random
def ranstr(num=32, char='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'):
"""随机字符串
num: 产生的长度,默认:32
"""
salt = ''
for i in range(num):
salt += random.choice(char)
return salt | d89a12a25a4691383def9212a97bec7a1e96389a | 648,398 |
import math
def distance_calculation(homeLattitude, homeLongitude, destinationLattitude, destinationLongitude):
"""
This function returns the distance between two geographiclocations using
the haversine formula.
Inputs:
1. homeLattitude - Home or Current Location's Latitude
... | 8cbe8df1e771f180cc61293c44f3ed46f98a42d2 | 648,399 |
import itertools
def extract_values(blob, offset, names):
"""Extract values that are delimited by type/length bytes.
The values will be extracted into a dictionary. They'll be saved to keys
in the same order that keys are provided in *names*. If there are more
values than key names then additional ke... | 9ab43169276b4da78d4b867b44003be57e8ca230 | 648,400 |
def get_authors_by_publisher(data, ascending=True):
"""Returns the authors by each publisher as a pandas series
Args:
data: The pandas dataframe to get the data from
ascending: The sorting direction for the returned data.
Defaults to True.
Returns:
The sorted data as a pand... | 757efc92aa8b1446971c917387d7cc6b6c34bd2c | 648,401 |
import re
def remove(html, *args):
"""remove(html[, str][...]) -> html
Return the html with each string str removed (replaced with a
blank space).
"""
reobj = re.compile("|".join(args), re.IGNORECASE)
return reobj.sub(" ", html) | e875ee23a688ef965b16226d127340b48ffe2180 | 648,402 |
def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left-right) > 1 or -1 in [left, right]:
return -1
return 1 + max(left, right) | 5a39cc76dc47c4a527f4606cb76f0014390329da | 648,403 |
def not_none(row):
"""
Is this None? Hint: .filter() with it.
"""
return row is not None | 9fe0dd2f297f7546b033eb7328779d6ff4f39d2a | 648,404 |
import torch
def temporal_iou(spans1, spans2):
"""
Args:
spans1: (N, 2) torch.Tensor, each row defines a span [st, ed]
spans2: (M, 2) torch.Tensor, ...
Returns:
iou: (N, M) torch.Tensor
union: (N, M) torch.Tensor
>>> test_spans1 = torch.Tensor([[0, 0.2], [0.5, 1.0]])
... | 45d033a3bdb6fe615feb1c1fe09ab063dd45a266 | 648,406 |
def course_difficulty(date, df):
"""
Returns SG:OTT average for the field at a given tournament.
(Date format yyyy-mm-dd)
"""
is_sgott = df['Variable'] == 'SG: Off-the-Tee - (TOTAL SG:OTT)'
filtered = df.loc[is_sgott]
grouped = filtered.groupby("Date")["Value"].mean()
date1 = grouped.ind... | dbce0f0e5ef5934d4da7e1e4e9b7472e8565a851 | 648,407 |
def mask(my_int, min_len=3):
"""
my_int:
1 -> 001
15 -> 1111
...
min_len: minimum_len -> List Count
1 -> [ True ]
2 -> [ True, True ]
3 -> [ True, True, True ]
...
"""
return [b == '1' for b in bin(my_int)[2:].rjust(min_l... | 35bf96bf25bf4a03ebae279494a54fbd4482f56a | 648,408 |
def parse_port(host):
"""
@params host: host filed in inventory.csv. e.g 10.202.12.56, 127.0.0.1:1162
@return host, port
"""
if ":" in host:
tmp = host.split(":")
host = tmp[0]
port = tmp[1]
else:
port = 161
return host, port | c8e34862d93165bcb202f77c544c0043bc30bfb4 | 648,409 |
def regular_plural(noun: str) -> str:
"""English rule to get the plural form of a word"""
if noun[-1] == "s":
return noun + "es"
return noun + "s" | 5b2ef7924fe93fb26b20639816032f6c85071bf0 | 648,410 |
def fill(data):
"""Replace spaces with NNN's."""
filled = {}
for name, seq in data.items():
filled_seq = seq.replace(" ", "N")
filled[name] = filled_seq
return filled | 449e2660cf4518aeb7de6d04c52a59e0d3525fac | 648,411 |
def get_requested_roles(settings):
"""Retrieve any valid requested_roles from dict settings"""
if ('requested_roles' in settings and
settings['requested_roles'] not in ['None', None]):
return settings['requested_roles'].split(',')
else:
return [] | 8e31dc039172650be85a8ce9a33f722e31d0e90a | 648,412 |
import pickle
def decode_pickle(data):
"""
Restore original object using Pickle.
"""
return pickle.loads(data, fix_imports=False) | 3030c89191e293210acea52b651edddc2b724f2f | 648,413 |
import importlib
def loadPlugins(config):
"""Loads jeff plugins specified in the config file.
Args:
config: jeff configuration dictionary loaded with utils.loadConfig.
Returns:
A dictionary containing the loaded module indexed by the plugin nameself
else False.
"""
plugin... | cebec2c6e0d6a59b5ba5e17931d2d8e824879bd4 | 648,415 |
import csv
import io
def splitStr(delimiter, escapeChar, s):
"""
Splits s based on delimiter that can be escaped via escapeChar
"""
# Let's use csv reader to implement this
reader = csv.reader(io.StringIO(s), delimiter=delimiter, escapechar=escapeChar)
# Unpack first line
for x in reader:
... | 1fb07495aa712df39bff00f5b7f2fbeaef5046b6 | 648,416 |
def broke_stroke(trajectory):
"""
break one stroke into one or multiple sub-stroke for preventing error caused by UR5 cannot maintain a speed
:param trajectory: the trajectory of a stroke
:return: a array of broken sub-stroke
"""
stroke_group = []
pointer1 = 0
if len(trajectory) < 11:
... | 4a5cd4cae9531ed0bd890b4f8cf15e64c0c976c1 | 648,417 |
def generate_ngram_tables(ngrams):
"""Generates relative frequency table for the n-gram"""
ngram_tables = []
for ngram in ngrams:
ngram_table = dict()
for sentence in ngram:
for token in sentence:
if token in ngram_table: # If token is already present, add one to ... | 844cf1176cd5ee87316b83fa14270d7d8fa4bd8b | 648,418 |
from typing import OrderedDict
def parse_vcf_file(path):
"""
:param path:
:return:
"""
data = []
headers = []
with open(path, 'rt') as fp:
for line in fp:
if line.startswith('##'):
continue
if line.startswith('#'):
cols = li... | 14ec29ec3f7f53636f84ec4dc5acc048f9b93296 | 648,419 |
def updated_querystring(request, params):
"""Updates current querystring with a given dict of params, removing
existing occurrences of such params. Returns a urlencoded querystring."""
original_params = request.GET.copy()
for key in params:
if key in original_params:
original_params.... | 85112c6ca8cc18e70f89cf75699201d47a8cfd14 | 648,420 |
def get_first_training_set_from_nested_cross_validation(cvs, data):
"""Use recursion to get the indices of the first training set in nested
cross-validation.
Parameters
----------
cvs : None or cross validator or a list of cross validators
If None, then the data is returned.
If `cvs... | 8d73e7217af20fe3d6b74a9e846ae65decfd4c8a | 648,421 |
def get_name(pbs_file):
"""
Extract the model name from a `CMIP5-compatible file name
<https://cmip.llnl.gov/cmip5/output_req.html>`_.
Parameters
----------
pbs_file : str
A filename that obeys the CMIP5 standard.
Returns
-------
str
The name of the model.
"""
... | 0011bd0dcdb0cd2249300ceb5e1ec7e56ad15e3d | 648,422 |
def find_subset_of(control, subset, length):
"""This will look for inverted matches, e.g.
--- ---
| | |
--- resembles ---
| |
--- ---."""
filt = filter(lambda x: len(x) == length, contro... | 7b83fe36e306a002d4b8e141a26ad4dd4c92cea9 | 648,424 |
def get_rn_freqs(core):
"""
Get red noise frequency array from a core, with error message if noise
array has not been included.
"""
if core.rn_freqs is None:
raise ValueError('Please set red noise frequency array in '
' the core named {0}.'.format(core.label))
el... | 93059b12ed995ffc9356624232a9c5d8a7526e45 | 648,425 |
def vecDotProduct(inVecA, inVecB):
""" returns dotproct inVecZ dot inVecB """
return inVecA[0] * inVecB[0] + inVecA[1] * inVecB[1] + inVecA[2] * inVecB[2] | 27636423dcf447c355f043ed4aa97daed414665a | 648,426 |
def calc_angle_speed_gain_vector(joint, dav, i, periodic_time):
"""Calculate angle speed gain for multiple Degrees of Freedom
"""
if periodic_time == 0:
return 1.0
dav_gain = 1.0
for joint_dof_index in range(joint.joint_dof):
if dav[i + joint_dof_index] == 0:
dav_gain = ... | 3a7e274e4e8bf97a87ef73dbb484eba9fc343af0 | 648,427 |
def repeat_along_dimension(array, number, dim=0):
"""Return a view into the array with a new, repeated dimension.
Parameters
----------
array : torch.Tensor
number : int
The number of repeats.
dim : int
The dimension along which to repeat.
Returns
-------
array : to... | bc45cf653a6f61de381fcd0b586711235a3554b0 | 648,428 |
def get_tableblocks(page):
"""Get all the TableBlocks for a given page.
TableBlocks can be stored either directly in page's content,
or in a FullWidthText item. So we must check both.
"""
try:
data = page.specific.content.raw_data
except Exception:
return []
tableblocks = lis... | 7831201f6b2ecc63f35fbaec1927597c3d0baafb | 648,429 |
import six
def hostport(scheme, host, port):
"""
Returns the host component, with a port specifcation if needed.
"""
if (port, scheme) in [(80, "http"), (443, "https"), (80, b"http"), (443, b"https")]:
return host
else:
if isinstance(host, six.binary_type):
return b... | b07388cf3fa9cc53e0bfc3dc3619dd69f8969ae5 | 648,430 |
import re
def clean_premiere_prefix(string):
"""Clean premiere prefix"""
# looks for strings like "PREMIERE:", "premiere "
result = re.search(r'(premiere\:?\s)', string, re.IGNORECASE)
if result is not None:
prefix = result.groups()[0]
string = string.replace(prefix, '')
return str... | 4b1da2546cf0a3ad1f330093d7606b40ea64a211 | 648,431 |
def format_embed_length(data: list) -> list:
"""
If the length of the data is greater than 1024 characters, it will be shortened to that amount.
Parameters
----------
data : list
The list containing the description for an embed.
Returns
-------
list
The shortened descri... | dcc843f64788cc7be122f36556aa57576173fe95 | 648,432 |
def renamed_prefix(cfg, old, new):
"""
Returns a new dictionary that has all keys of `cfg` that begin with `old`
renamed to begin with `new` instead.
"""
renamed = dict(cfg)
for k in cfg.keys():
if k.startswith(old):
renamed[new + k[len(old):]] = renamed.pop(k)
return ren... | efca0995d82c287e53b3b70b89f2317864ba64bd | 648,433 |
def vec_inner(x, y):
"""Calculates the inner product of the last dimensions of x and y."""
xT = x.T
yT = y.T
return (xT[0]*yT[0]+xT[1]*yT[1]+xT[2]*yT[2]).T | f47e3161cc3043284b093f52d999ab65da6e0bf0 | 648,434 |
def get_rec_names(study_folder):
"""
Get list of keys of recordings.
Read from the 'names.txt' file in study folder.
Parameters
----------
study_folder: str
The study folder.
Returns
----------
rec_names: list
LIst of names.
"""
with open(study_folder / 'na... | ab9c7eddc0ce593ddcea129c2122e753a94432bf | 648,436 |
def sizeof_fmt(num, dec = 3, kibibyte = False):
"""Byte size formatting utility function."""
prefixes = None
factor = None
if kibibyte:
factor = 1024.0
prefix = ['bytes','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']
else:
factor = 1000.0
prefix = ['bytes','KB','MB','GB','TB','PB','EB','ZB','YB']
for x ... | 16856289c3fc1d5903a11e69d86b1c645ee0e27e | 648,437 |
async def clear_fields(message, embed):
"""
Removes all embed fields of the embed of a message from a dictionary with a much more tight function
"""
embed.clear_fields()
return await message.edit(embed=embed) | 8c6e37643a8258ff45b0f4f0a3f45125387d64ea | 648,438 |
def flatten_manifests(root_manifest, only_with_entries=False, recursion=0):
"""
Convert a tree-structure Manifest into a flat list structured list of
Manifests.
:param root_manifest:
:type root_manifest: Manifest
:param only_with_entries: Switch to filter result to only those
manifests with ... | 759783d2fb8046c198831fda33edf4d7f6034d44 | 648,439 |
from datetime import datetime
def acqtime(feature):
"""A handler that returns the correctly formatted date, based on asset."""
msec = feature['properties']['system:time_start']
return datetime.fromtimestamp(msec / 1000).isoformat() | 031622b2b716010105ac1c880f908ff6e70c3c1f | 648,440 |
def _parse_date(text):
"""Parse a text date like ``"2004-08-30`` into a triple of numbers.
May fling ValueErrors or TypeErrors around if the input or date is invalid.
It should at least be a string--I mean, come on.
"""
return tuple(int(i) for i in text.split('-')) | 19de0150621e878646fa44069d5ea09c69933536 | 648,441 |
def get_linknames(dic):
"""Gets the names of links from links block so references can be made in properties list"""
out = []
links = dic['links']
for link in links:
if type(link) == dict:
try:
out.append(link['name'])
except KeyError:
for l... | 512efbdb9bb4b030663f1901bd218b5137b042cb | 648,442 |
def name():
"""Set name for petgem package.
:param: None
:return: petgem name
:rtype: string
"""
return 'petgem' | 1159ea441c1090f561a71252a32a3248628fa6a2 | 648,444 |
def split_list(doc_list, n_groups):
"""
Args:
doc_list (list): is a list of documents to be split up
n_groups (int): is the number of groups to split the doc_list into
Returns:
split_lists (list): a list of n_groups which are approximately equal
in length, as a necessary step... | b6191f91773c1ae22157a2dcc2c57c02acd858be | 648,445 |
def mock_server_with_authenticated_connection():
"""Instantiate a LogInsightMockAdapter with a """
raise DeprecationWarning()
connection = Connection("mockserverlocal", auth=Credentials("admin", "password", "mock"))
adapter = LogInsightMockAdapter()
adapter.prep()
connection._requestsession.moun... | eeb969cd77fcefce99b4c1fa2af41f1840d9eaea | 648,446 |
def insert_breaks(s, min_length, max_length):
"""Inserts line breaks to try to get line lengths within the given range.
This tries to minimize raggedness and to break lines at punctuation
(periods and commas). It never splits words or numbers. Multiple spaces
may be converted into single spaces.
Args:
... | ca202f3e3c86ac7b13f62ae057583cfe54e06e0b | 648,447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.