content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_p_at_n_in_m(data, n, m, ind):
"""
Get n in m
"""
pos_score = data[ind][0]
curr = data[ind:ind + m]
curr = sorted(curr, key=lambda x: x[0], reverse=True)
if curr[n - 1][0] <= pos_score:
return 1
return 0 | 447f1776acd4b79c8c552f2c5618151f1a72b8e8 | 658,260 |
def logOutUser(command):
""" Check if command is to log out (o | logout). """
return (command.strip().lower() == "o" or command.strip().lower() == "logout") | cb0ba11282a0e867f681e8bc006e98dafaa588fe | 658,261 |
import os
def sedf_paths_func(file_name, server_url, out_dataset_folder):
"""
See psg_utils/download/utils.py [download_dataset]
A callable of signature func(file_name, server_url, out_dataset_folder) which returns:
1) download_url (path to fetch file from on remote system)
2) out_file_path (path ... | 9df995846e77b388ca413ccb8a46706f1a848e68 | 658,262 |
from typing import Iterable
import functools
from operator import getitem
def get_in(keys: Iterable):
"""Creates a function that returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys.
>>> get_in(["a", "b", 1])({"a": {"b": [0, 1, 2]}})
1
"""
def get_in(coll):
return functools.reduce(... | b04c67beb2a9bf6f969b0f4193e5dc49f4d9bbf4 | 658,263 |
def enable_windows_defender():
"""
Enable Windows Defender Powershell command.
:return: Returns the powershell command to enable win defender again.
"""
return "Set-MpPreference -DisableRealtimeMonitoring $false" | c495b55638e2f33f71dea9625519b4117b707371 | 658,264 |
def get_all():
"""List all available hospitals."""
return {} | 44c89483248a94d94534577174ff4642a7932ba8 | 658,266 |
import re
def escapeRegexChars(txt,
escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')):
"""Return a txt with all special regular expressions chars escaped."""
return escapeRE.sub(r'\\\1', txt) | cc2afea8e9bb0c9a56b9a3a31cb2370205d88558 | 658,267 |
from typing import Dict
def is_coco_polygon(coco_label: Dict) -> bool:
"""Check if a given label is a valid polygon only label."""
has_bbox = "bbox" in coco_label and len(coco_label["bbox"]) == 4
has_segment = len(coco_label.get("segmentation", [])) > 0
no_keypoints = not coco_label.get("keypoints")
... | 2880a2c6a734098427121385c382c2ea39bcb422 | 658,268 |
def _equivalence_partition(iterable, relation):
"""Partitions a set of objects into equivalence classes
canned function taken from https://stackoverflow.com/a/38924631
Args:
iterable: collection of objects to be partitioned
relation: equivalence relation. I.e. relation(o1,o2) evaluates to ... | c57818f1adc8bcaf6651b9bd9c6fb3fb8af56133 | 658,269 |
def _select_month_reindex(indices, month):
"""Subsets indices for given month then reindexes to original size."""
select_month = indices[indices.index.month == month]
return select_month.reindex(index=indices.index) | 590e006418178bccdf2bd2ebbfb09a383f0716f2 | 658,270 |
def sgn(x):
"""
To handle the complex case, we need to
use this definition of the sign(A) instead of numpy.sign,
which just takes the sign of the real part.
"""
return 1 if x == 0 else x/abs(x) | ba83f92ada2127134b89a075b32de3661d03fae4 | 658,271 |
import re
def old_to_new_tracks(old_tracks: str) -> str:
"""
>>> old_to_new_tracks(EXAMPLE_INPUT)
'make_tracks li1 -x_offset 0.23 -x_pitch 0.46 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met1 -x_offset 0.17 -x_pitch 0.34 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met2 -x_offset 0.23 -x_pitch 0.46 -y_offse... | 9bc45cc3ea1e51a6fa52dd53d6e4af6dc6adef6e | 658,272 |
import ast
def parse(data:str) -> object:
"""
Given a string with python source code,
returns a python ast tree.
"""
return ast.parse(data) | b28ce6220d54e330b84d5856dfbc68566b61c3c6 | 658,273 |
def get_frame_durations(sentences, timestamps):
"""Given a list of sentences and timestamps of all words, return timestamps of each sentence
Args:
sentences (list): List of sentences
timestamps (list): [
[<word_string>, <start_time_float>, <end_time_float>],
...
... | 7063e2d5df87c430384cd506b27671bf64ffcf2e | 658,274 |
def _token_addresses(
token_amount,
number_of_tokens,
deploy_service,
participants,
register):
""" Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and
distributed among `blockchain_services`. Optionally the instances will be registered with
... | 7f9a79e03de4d5d876fcd8a05663d80c5c83740f | 658,275 |
def WR2(func):
"""Function to wrap another containing 2 argument.
Used to parametrize tests in which some cases depend
on the registry while avoiding to create it at the module level
"""
return lambda ureg, x, y: func(x, y) | 385a42d81165c6648a30e0273a2c324d30f9a589 | 658,276 |
def test_jpeg1(h, f):
"""JPEG data in JFIF format"""
if b"JFIF" in h[:23]:
return "jpeg" | 4c1ef49ecc08c802dedeb2057c8d8bd87d550907 | 658,277 |
def cint(n):
""" A função cint, recebe um valor (n) que pode ser uma número inteiro, real, string ou uma lista e converte o valor para número inteiro
No caso de (n) ser uma lista irá converter cada um dos valores contidos na lista para inteiros e continuará sendo uma lista
No caso de ser uma string vazia ou letra, r... | 81c3f89e9a3fa2ddb4e9d8cf0f24325a5c439ffe | 658,278 |
import os
def get_clip_paths(path: str) -> list:
"""
Gets all the mp4 files listed in the given
path and returns the paths as a list.
"""
return [
os.path.join(path, file) for file in os.listdir(path) if file.endswith(".mp4")
] | ff319c8aa96182f686a98c309d83d2ba02d8a3de | 658,279 |
def getMaxDimOfAllGlyphs(fontDict):
""" This function checks all glyphs and return the maximum width and the maximum height in the set of glyphs"""
sizesList = []
for i in fontDict.keys():
# print fontDict[i][2].values()
sizesList += map(lambda x: x[1].size, fontDict[i][2].values())
maxv ... | 2a8d08e9e0faa717575a9694a0e6ba4b0167d456 | 658,280 |
def get_attack_rate(df, location):
"""
Get the attack rate for the location.
Args:
df (pd.DataFrame) : pandas DataFrame with attack rates for this scenario
location (str) : name of the location
Returns:
float: Attack rate as a fraction from SIR model, values between 0 and 1.... | 05e27abfd3046a6b455d1a1606ad1591d637e50f | 658,281 |
import tarfile
def extract_tarfile(file_path):
"""Extract a .tar archive into an appropriately named folder, return the path of the folder, avoid extracting if folder exists."""
new_path = None
with tarfile.open(str(file_path)) as archive:
new_dir = file_path.name.split('.tar')[0]
new_path... | a0daf1796599293220272bf842e7d3482f51f533 | 658,282 |
import math
def get_epsilon_of_fedmd_nfdp(n, k, replacement=True):
"""Return epsilon of FedMD-NFDP
Args:
n (int): training set size
k (int): sampling size
replacement (bool, optional): sampling w/o replacement. Defaults to True.
Returns:
float: epsilon of FedMD-NFDP
"... | e5cff34f217fec38ca896f955c450db093ae0eaf | 658,283 |
def max_subarray1(sequence):
""" Find sub-sequence in sequence having maximum sum """
# this is the version before the final version for testing purposes
max_sum, max_sub = 0, []
for i in range(len(sequence)):
for j in range(i+1, len(sequence)):
sub_seq = sequence[i:j+1]
... | 3277c203db8766286ba28fb30d9c47a75f21dbf5 | 658,284 |
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4):
"""
Compute the intersection point of two lines.
Taken from https://stackoverflow.com/a/20679579 .
Parameters
----------
x1 : number
x coordinate of the first point on line 1. (The lines extends beyond this point.)
... | 4e9de8ec15635aadccfa93a18750065005f087e4 | 658,285 |
def padded_concat(*values: str, strip: bool = True, sep: str = " ") -> str:
"""
>>> padded_concat(" hello", " yolo", "", " ", "yo", strip=True)
'hello yolo yo'
>>> padded_concat(" hello", " yolo", "", " ", "yo", strip=False)
' hello yolo yo'
>>> padded_concat(" hello", " yolo", "yo"... | e7dc78d42303a98a9fdf2964c461e75a5b9ef672 | 658,287 |
def income1(households):
"""
Dummy for for income group 1
"""
return (households['income_category'] == 'income group 1').astype(int) | 26f4c5f9f1cb6c56bfc4d5bb8410d4b31516d628 | 658,288 |
def get_android_data_path(language: str, word_type: str):
"""
Returns the path to the data json of the Android app given a language and word type.
Parameters
----------
language : str
The language the path should be returned for.
word_type : str
The type of word... | 81b02e0cddc5ec4d7c9377513c43d6fadbc2d918 | 658,289 |
def bLen(*args):
"""bLen(*args) -> len(args)
a better version of len, which takes args because in python3 everything is a generator"""
return len(args) | 2a48865c1892e48eeb41828b4afbb27e61d1b1e6 | 658,290 |
def build_company_name(name_dict, _emptyString=u''):
"""Given a dictionary that represents a "long" IMDb company name,
return a string.
"""
name = name_dict.get('name')
if not name:
return _emptyString
country = name_dict.get('country')
if country is not None:
name += ' %s' %... | 70d2fb6e42bc6ad52a2e88ec9027bd9d76870d89 | 658,291 |
def remove_namespaces_whitespaces(type_str):
"""
Clear type name from namespaces and whitespaces
"""
return type_str.replace('sycl::', '').replace(
' ', '_').replace('std::', '') | 49301d01b7d809fdbf74c429273ca58283854edc | 658,294 |
def listSum(SumList):
"""
递归求和函数
:param SumList: 求和列表
:return:求和之后的值
"""
if len(SumList) == 1:
return SumList[0]
else:
return SumList[0] + listSum(SumList[1:]) | 6e4a5f9fe0a66251ca4b044e9b45bfab8c167112 | 658,296 |
def get_to_folder_name(folder_name, date_stamp):
"""
From the date_stamp
return the S3 folder name to save published files into
"""
return folder_name + date_stamp + "/" | 65de65718a1c3d09f99c7fdadad644edc944efc8 | 658,297 |
from typing import List
def parse_combined_columns(eval_data: List[List[str]], index_a: int, index_b: int, delimiter: str = ' - ') -> str:
"""
Combines two columns worth of data into a single list of comments, separated by a delimiter
"""
if len(eval_data) <= 1:
return ''
return_val = "\\b... | 0911ae650287acb9ebe4a0dbb7b86f4cae46a499 | 658,298 |
import math
def get_prime_factors(n):
"""Return prime decomposition of an int n
"""
prime_factors = []
while n % 2 == 0:
prime_factors.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1,2):
while n % i== 0:
prime_factors.append(i)
n = n / i... | 0e669ba330b72bd446002d8daf0d5ec715b698aa | 658,299 |
def CheckIfItIsBlacklisted(chr1, start1, chr2, start2, blacklist, extention):
"""
Check if coordinate are present in the ``blacklist region file``
:param str chr1: str of the breakpoint in first chromosome
:param int start1: int of the start location of the breakpoint in first chromosome
:param str... | bf33cd23ab929960d4a9f7779f104d6d04845dd3 | 658,300 |
def load_figer_set_present_in_conll(file_path):
"""
Load the freebase types that were present in conll dataset.
"""
types_covered_local = set()
with open(file_path) as file_i:
for row in file_i:
fb_type, _ = row.split('\t')
types_covered_local.add(fb_type)
return ... | aacbcb8ad40335f0b196fea56b6d83e8423bc599 | 658,301 |
def get_percentile_dict(yhat_name, valid, id_):
""" Returns the percentiles of a column, yhat_name, as the indices based on
another column id_.
:param yhat_name: Name of column in valid in which to find percentiles.
:param valid: Pandas validation frame.
:param id_: Validation Pandas frame con... | cde37a38be2238fa27032fbac27846dad596ee18 | 658,302 |
def get_container_indicators(item_json):
"""Returns container indicator(s) for an archival object.
Args:
item_json (dict): ArchivesSpace archival object information that has
resolved top containers and digital objects.
Returns:
string or None: A concatenated string containing t... | cb8313bcf6d473e793bca59862b7704ab4f422b5 | 658,303 |
def filter_traceback(tb_list):
"""Given a traceback as a list of strings, looks for common boilerplate and removes it."""
# List of boiler plate pattern to look for, with example before each
# The match pattern is just some string that the line needs to contain
"""
File "asynq/async_task.py", l... | ce883c3d2c9118125b41701b1c981bfa8583011b | 658,304 |
def romanToInt( s):
"""
:type s: str
:rtype: int
"""
rome_dict = {"I":1, "V":5,"X":10,"L":50, "C":100, "D":500, "M":1000 }
sum = 0
#arr_i = []
for i in range(0, len(s)-1):
print(s[i])
if (rome_dict[s[i]]>=rome... | b0347a854b79e41493bef28a8d4562d4958bdd1b | 658,305 |
def find_different_named_columns_list(data1, data2):
"""
Parameters
----------
*datas: tuple of two pandas.DataFrame with nominal columns
Returns
-------
var name: different_categories, list of lists of strs with two inner lists
different_categories[0] includes the column names of d... | baf5ce611456f7b593074e07df8151a719772689 | 658,307 |
import json
def read_json(file_path: str) -> dict:
"""
Function that reads JSON configuration file and returns data.
>>> from snakypy import helpers
>>> file = '/tmp/file.json'
>>> helpers.files.read_json(file)
Args:
file_path (str): You must receive the full/absolute file path
... | f2f1f2e5c0b05c12b391fe095fd4c53ebdc4c9a3 | 658,309 |
def is_pure(obj, prop):
"""
Checking and setting type to PURE
Args:
obj: None
prop: None
Return:
Boolean
"""
return True if (not prop and not obj) else False | 1fba856635bb6c75019fa31b6ccd4a5d211b8bad | 658,311 |
import math
def floor(x):
"""Round x to the nearest whole number smaller than or equal to x."""
return math.floor(x) | 8e769a4f74d5256d048421b4010165f40977d597 | 658,312 |
def get_calmag(inimag, distance, ebv_val, magext_val):
""" Apply the absorption and distance modulus
color = colsub * 3.07 * EBV
inimag -- magnitude from star star[chip[FILTER] (it should be = star[chip[BAND]]
distance -- Distance Modulus used to calculate the calibrated magnitude
ebv_va... | 20e513ea60a310f9d404e170684f182e03c3ec06 | 658,314 |
import re
def words(text):
"""Get all words from the text."""
return re.findall("[a-z]+", text.lower()) | e28f2dd54aabc9d0abe88300e0575cbb8a29e445 | 658,315 |
import re
def parse_signature(signature):
"""
Parses one signature
:param signature: stanc3 function signature
:return: return type, fucntion name and list of function argument types
"""
rest, return_type = signature.rsplit("=>", 1)
function_name, rest = rest.split("(", 1)
args = re.fi... | 91e451902601e4196ca4e79458f3fb44193210b4 | 658,316 |
def rgb(rgb_colors):
"""
Return a tuple of integers, as used in AWT/Java plots.
Parameters
----------
rgb_colors : list
Represents a list with three positions that correspond to the
percentage red, green and blue colors.
Returns
-------
tuple
Represents a tuple ... | c2e3861c631bf5c64e426e02455758732d70fb8e | 658,317 |
import argparse
def read_cmd_line():
"""Read the input file and the workflow name from the command line."""
msg = "distribute_jobs.py -i input.yml"
parser = argparse.ArgumentParser(description=msg)
parser.add_argument('-i', required=True,
help="Input file in YAML format")
... | bad0b8c7ca96b487c031e0d8316a5b962559ae0e | 658,319 |
import re
def shorten(string, maxLen, last):
"""Returns <string> with custom truncation.
Keyword arguments:
string -- <str>; the text to shorten
maxLen -- <int>; the maximum number of characters <string> can
be
last -- <str>; truncates <string> to <last> found closes... | 3e381848d333b21019bece0e907997f4ebb5eef5 | 658,321 |
def _triangulate(g, comb_emb):
"""
Helper function to schnyder method for computing coordinates in the plane to
plot a planar graph with no edge crossings.
Given a connected graph g with at least 3 vertices and a planar combinatorial
embedding comb_emb of g, modify g in place to form a graph whose ... | c8ecd268c4de7d15f7d7a9071d6607c1b3f1943e | 658,322 |
def enabled_disabled(b):
"""Convert boolean value to 'enabled' or 'disabled'."""
return "enabled" if b else "disabled" | d599aa1711a767c921d3ccd7af9ad18e8430ca4e | 658,324 |
def match_update_from_regex(re_parsing_rules, stmt):
"""Parse an update statement using regexes.
Args:
re_parsing_rules (dict): Dictionary containing the rules for
parsing statements as values and their effects as keys.
stmt (str): String representing a statement
Returns:
... | 1a5de48c816d2517df962ee5cf7a62a1d52ff0a7 | 658,325 |
import itertools
def tee(iterable, n=2):
"""Return `n` independent iterators from a single iterable.
This function uses single dispatch.
.. seealso:: :func:`itertools.tee`
"""
return itertools.tee(iterable, n) | d3ba7e011da69d66087961b6592c6b84b5f93842 | 658,326 |
import requests
import json
def custom_ws_perm_maker(user_id: str, ws_perms: dict):
"""
Returns an Adapter for requests_mock that deals with mocking workspace permissions.
:param user_id: str - the user id
:param ws_perms: dict of permissions, keys are ws ids, values are permission. Example:
{... | 86837c953dafd6b96f70de79c64ce72b6997e0cc | 658,328 |
def heuristic(point_1, point_2):
"""Calculates the manhattan distance between points and returns an integer"""
x1, y1 = point_1
x2, y2 = point_2
man_dist = abs(x1 - x2) + abs(y1 - y2)
return man_dist | 275855aa70a15a6ccd600ff5b046fd24a463a389 | 658,329 |
def read_whitelist(whitelist_file):
"""This function reads the white list file and returns the list"""
# create an empty dictionary to store the white lists
whitelistdict = {}
with open(whitelist_file, 'r') as fp:
for line in fp:
whitelistdict[line.strip()] = True
# return the ... | aa416fd866673e1ddf9c5c91d19b11a8fafa6fe5 | 658,330 |
def create_count_neighbors_ca1d(width):
"""
Returns a list with the weights for 'neighbors' and 'center_idx' parameters
of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...).
The weights are responsible to count the number of alive neighbors.
Parameters
----------
width : int
Neig... | 5e1416a39f398bb4858855009c022af0101c1a5f | 658,331 |
import random
def _generate_processing_blocks(start_id, min_blocks=0, max_blocks=4):
"""Generate a number of Processing Blocks"""
processing_blocks = []
num_blocks = random.randint(min_blocks, max_blocks)
for i in range(start_id, start_id + num_blocks):
_id = 'sip-pb{:03d}'.format(i)
b... | 0eaa40c92c480d4d08986828ed9a046f5b00cda2 | 658,332 |
import re
def isHour(time):
"""renvoit 1 si l'heure est au bon format pour etre transformé en heure, 0 sinon"""
try:
assert isinstance(time, str)
regex = re.compile(r"[0-9]*:[0-9]*")
assert regex.match(time)
args = time.split(":")
assert len(args) == 2 and isinstance(... | f04b7242e09a4cdc35356298126499b09d22651c | 658,333 |
def remove_zero(number: str) -> str:
"""
:param number:
:return:
"""
if number.startswith("0") and number.endswith("0"):
return "0"
elif number.startswith("0"):
return number.replace("0", "")
else:
return number | ee674409355378486d0a9c2cd5f50112bfc19ee4 | 658,334 |
import base64
def base642str(s: str):
"""
Convert a base64 to string.
:param s: the base64 string
:return: a string
"""
return base64.b64decode(s).decode() | 7f5a09206d5f81e348cd5c9b6489b808a5d00894 | 658,335 |
def GDT_match_cutoff_dim(GDT_percent, GDT_cutoff):
"""
Matches GDT_cutoff array to the dimensions of GDT_percent. Used in combination
with analysis.PLOT() function to plot multiple curves on one canvas.
Args:
GDT_percent (list, array): output of gdt.GDT()
GDT_cutoff (list, array): outpu... | 82e8d4021d305db3553239304899a606b583abfa | 658,336 |
import struct
def u32(x):
"""Unpacks a 4-byte string into an integer (little endian)"""
return struct.unpack('<I', x)[0] | 07c4e353375cac3ef8e4de44d6823aa888affb97 | 658,337 |
import hashlib
def gravatar_avatar_url(email, size):
"""Возвращает граватар с указанным *email* и размером *size*.
Возвращает сгенерированный граватар с использованием параметра
d=monsterid в случае, если аватар не загружен на сервисе.
:param str email: email пользователя
:param int size: шири... | 85bd664b4c8ebe0f8839ef0dc8127b32c8ae5b4c | 658,338 |
def null_distance(node1, node2):
"""Retourner distance nulle entre noeuds pour émule Dijkstra."""
return 0 | ed9e1f2b1f2136ffd3a476252adab21ee575a20c | 658,339 |
import http
def auth_reject(realm=None):
"""
Returns a HTTP 401 UNAUTHORIZED response to a user that is being rejected from requesting a resource.
Use the realm param to control which realm is provided in the rejection
"""
auth_header_value = 'Basic'
if realm is not None:
auth_header_... | 1759cb35603196cf7c7030939da8dd236fe563b7 | 658,340 |
def get_subject_object_phrase(doc, dep):
"""Extract Subject And Object"""
start, end = 0, 1
for token in doc:
if dep in token.dep_ and token.head.dep_ == 'ROOT':
subtree = list(token.subtree)
start = subtree[0].i
end = subtree[-1].i + 1
return str(doc[start:en... | 719a5c42431caa227a9227c43a5ac86ca99a20ea | 658,341 |
import hashlib
def get_hash(page):
"""
Получает хеш страницы.
"""
return hashlib.sha1(page).hexdigest() | 258bba5b9876fc66debbf3eec0d27de283e762af | 658,342 |
def cria_posicao(col, lin):
"""
cria_posicao: str x str -> posicao
Esta funcao recebe duas cadeias de carateres correspondentes a
coluna e a linha de uma posicao e devolve a posicao correspondente.
"""
col_para_num = {
'a': 1,
'b': 2,
'c': 3
}
if type(col) == type... | 7bdfcb7d7583eaf1f8530e7893b4581573f47807 | 658,343 |
import fileinput
def read_resources(path):
"""Reads resources ids from a file.
For example:
model/50974922035d0706da00003d
model/509748b7035d0706da000039
model/5097488b155268377a000059
"""
resources = []
for line in fileinput.input([path]):
resources.append(line.rstrip())
... | 0b249ec83954a5a70e83152b373711ce5b59cff0 | 658,344 |
import hashlib
def sha1(text_: str) -> str:
"""Get SHA1 hash from string in hex form."""
return hashlib.sha1(str(text_).encode("UTF-8")).hexdigest() | 5561c35c86821ed4098917c21eb4a5ed7abcac0b | 658,345 |
def get_current_account_id(context):
"""
Get current account id.
@param context: the context of the event
@return: current account id
"""
return context.invoked_function_arn.split(":")[4] | d3f8fce71edf575af7aebd7c75a9cc71f2900f86 | 658,346 |
def getShortVersion(version: str) -> str:
"""
:param version: A Python version.
:return: The major and minor part of 'version'.
"""
return '.'.join(version.split('.')[:2]) | ca77869adc2610d48e48eba0c525c1f1589b5c9e | 658,347 |
from typing import Dict
from typing import List
def df_ordered_dict(include_io=True) -> Dict[str, List]:
"""
Return an ordered defaultdict designed to create tabular exports from datasets
"""
keys = [
"dataset_index",
"doses_dropped",
"model_name",
"model_index",
... | 359356b9ebe1c9f76a96e652dcac83e272fdf3be | 658,348 |
def _add_cell_methods_2(cmd):
"""Second set of cell_method additions. Split this way to appease
pylint."""
cmd += " -a cell_methods,RiverDepth_tavg,c,c,"
cmd += "'time: mean area: point where land'"
cmd += " -a cell_methods,RiverFlowVelocity_tavg,c,c,"
cmd += "'time: mean area: po... | e72ac051559852da75f0b0a52cc19c8e292e2356 | 658,349 |
import math
def dip(x0, z0, x1, z1):
""" Compute dip between two points: (x0, z0) (x1, z1)
Parameters
----------
x0 : float
X-coordinate of point 0
x1 : float
X-coordinate of point 1
z0 : float
Z-coordinate of point 0
z1 : float
Z-coordinate of point 1
... | 63d0420b79a708082ceb1117eedc88899886659f | 658,350 |
def solver_problem1(inputs):
""" Count the number of increasement from given list """
num_increased = 0
for i in range(1, len(inputs)):
if inputs[i] > inputs[i - 1]:
num_increased += 1
return num_increased | ab0a82da86ba730934f2a1e572ae4f145fb5e463 | 658,351 |
def get_n_grams(text, n):
"""
Computes the n-grams of a given text
:rtype : list
:param text: The text provided
:param n: The n of n-grams
:return: List of all the word's n-grams
"""
# returning the list of n-grams
return [text[i:i+n] for i in range(len(text) - n + 1)] | 107c1c36c3b3cd0fa66e012f6af36911a0ed3c66 | 658,352 |
from typing import Counter
def build_t_dataset(corpus_file, mincount):
"""
Process raw text into a dataset.
The universal embedding: [entities, words].
So the start index of words is ent_eize.
"""
with open(corpus_file, mode='r', encoding='utf_32') as f:
words = f.read().split()
# ... | 7928e6f50fda432c1319eec1a8e71f5faa7fd7b2 | 658,353 |
def normalize(z):
"""
Normalize an array.
:param z: The array to normalize
:type z: array
"""
return (z - min(z)) / (max(z) - min(z)) | 2483412c7ce8e11a5d912d1fab678c3e4f6a91aa | 658,354 |
def _default_scale(bound, objective):
"""`max{1.0,|objective|}`"""
# avoid using abs() as it uses the same logic, but adds
# additional function call overhead
if objective > 1.0:
return objective
elif objective < -1.0:
return -objective
else:
return 1.0 | f3eab35faf9693788885b849615157c719bccdb8 | 658,355 |
def generateHeader():
""" ## Google Chrome headers
Host: search.mtvnservices.com
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWe... | 2990994505572bb0a70af1e7a8de5e13220537dc | 658,356 |
import string
def str_to_python_id(val):
"""Convert a string to a valid python id in a reversible way
Arguments:
val (str): The value to convert
Returns:
str: The valid python id
"""
result = ''
for c in val:
if c in string.ascii_letters or c == '_':
resul... | 7fe7f7808b6e106ea9fddabf37393cdc521de920 | 658,357 |
def set_generator(filename, index):
"""
Given a file, returns a set with all the values from the column[index]
"""
results = set()
with open(filename, 'r') as fi:
for line in fi:
line = line.strip().split()
results.add(line[index])
return results | 50cd2afab1e57381030c48dfaf53ce64fd7910a3 | 658,358 |
def vdot(a, b):
"""
vdot(a, b)
Return the dot product of two vectors.
The vdot(`a`, `b`) function handles complex numbers differently than
dot(`a`, `b`). If the first argument is complex the complex conjugate
of the first argument is used for the calculation of the dot product.
Note that... | 3c7fe3ef076f48063327c4c590b4194eff7c4a51 | 658,359 |
def fetch_pipe_elements(pipesystem, ignore_inlets=False, ignore_outlets=False):
"""Iterates through the PipeSystem and returns a list of all PipeElements
Arguments
------------------
pipesystem : PipeSystem
The PipeSystem for which the elements should be gathered for
ignore_inlets : bool
... | 0b6f808108809ced30c101b1c70184107f0e0c9b | 658,361 |
def overall_completion_rate(female_completion, male_completion):
"""
Fill in this function to return a NumPy array containing the overall
school completion rate for each country. The arguments are NumPy
arrays giving the female and male completion of each country in
the same order.
"""
retur... | 5ca7928cb3adefdc695ee6b823f7e84638cf1cb1 | 658,362 |
from typing import List
def get_requirements(reqs_filename: str) -> List[str]:
"""Get a package's requirements based on its requirements file."""
try:
with open(reqs_filename, "r", encoding="utf-8") as reqs_file:
reqs = reqs_file.read().strip().split()
return reqs
except FileN... | 67c1034401dc9394d8ee15b46451d50e4cae7f69 | 658,363 |
def adjust_to_1(row):
"""If total sum larger than 1, remove the differnce from largest value."""
total = sum(row)
if total > 1:
largest = max(row)
replace = row.index(largest)
row[replace] = largest - (total-1)
return row | 90cc4b5c276cc0cc8cc6ed89db684ced81cee4c8 | 658,364 |
def _set_default_duty_cycle(duty_cycle: float, type_id: int) -> float:
"""Set the default max rated temperature for mechanical relays.
:param duty_cycle: the current duty cycle.
:param type_id: the type ID of the relay with missing defaults.
:return: _duty_cycle
:rtype: float
"""
if duty_cy... | a9ae302568b0c857420d2877fdf7c32f4e53f41a | 658,365 |
import os
def closing(email):
"""
Finds email (letter) closing.
Returns 0 (none) or 1 (exists)
Email closing list from About.com (http://jobsearch.about.com/od/letterwritingtips/a/letter-closings-list.htm)
"""
result = 0 # 0: none, 1: closing exists
# open closing list file
f = open(... | 7ce0ded52296f71ee62d03d32729e31ca3dec44d | 658,366 |
import logging
import sys
def leastsquare(x,y,weight=None):
"""
least squares fitting
coefficients from y= a+bx
return (b,a)
reference: http://mathworld.wolfram.com/LeastSquaresFitting.html
For weighted least square: http://goo.gl/pGpTZ6
"""
n=len(x)
if n != len(y):
logging.error('Unequal length... | 49a89ade0876c4cacaebd3535449a592b1ad9981 | 658,367 |
def _R(T, Cr, n):
"""
Basic function for calculating relaxation time due to
the Raman mechanism. For canonical definition, see fx.
DOI: 10.1039/c9cc02421b
Input
T: temperature for the calculation
Cr: Raman pre-factor
n: Raman exponent
Output
tau: relaxation time due to ... | 5b7f5547dae4caf0ee1761032a2867a559373cb8 | 658,368 |
def partially_tracked(df, track_ratios):
"""Number of objects tracked between 20 and 80 percent of lifespan."""
del df # unused
return track_ratios[(track_ratios >= 0.2) & (track_ratios < 0.8)].count() | aa0e0543f71161183480f251733cf764c10f3d79 | 658,369 |
from datetime import datetime
def trim_microseconds(dt: datetime) -> datetime:
"""Trim microseconds from a datetime as per ECMA-262."""
return dt.replace(microsecond=((dt.microsecond // 1000) * 1000)) | b560e7edf42401e76667066bfa6f7992bd9b3973 | 658,370 |
import torch
def temporal_separation_loss(cfg: dict, coords: torch.Tensor) -> torch.Tensor:
""" Encourages key-point to have different temporal trajectories.
:param cfg: Configuration dictionary
:param coords: Key-point coordinates tensor in (N, T, C, 3)
:return: The separation loss
"""
# Tr... | 7de1f78311454266ba529e326e0d313a69ffb376 | 658,371 |
def colored(name: str, color: str = "", style: str = "") -> str:
"""Colors a string with given color name."""
try:
import colorama # pylint: disable=import-outside-toplevel
colors = {
"green": colorama.Fore.GREEN,
"red": colorama.Fore.RED,
"blue": colorama.F... | 7073b8d58f21f3af4d8c2a537b6a21017aaed232 | 658,374 |
def kappa_idx():
"""
Provide scalar products indexes for kappa values.
Return:
list_kappa_idx -- list of lists
"""
list_kappa_idx00 = [[0, 0, 0, 0, 0, '00000'],
[0, 0, 1, 1, 0, '00001'],
[0, 1, 2, 0, 0, '00010'],
[0, 1, 3, 1, 0, '00011'],
[1, 2, 0, 0, 0, '00100'],
[1, 2, 1, 1, 0, '0... | 2634d73319565ef7693125f8954b6177cafdefa6 | 658,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.