content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import copy
def rotate_angles_one_by_one (idx, angles, thetas, structures):
"""
This script takes a set of structures, and outputs a (longer) set of structures where the given bond has been rotated.
Args:
idx (int): the current position in ``angles``
angles (list of 4-element lists): the ... | a25256d90fe42e2d464b972fb127332321d4a67e | 635,031 |
def prime(number):
"""
Get the n-th prime
"""
if number == 0:
raise ValueError('there is no zeroth prime')
is_prime, count = [True for i in range(1000000 + 1)], 0
for i in range(2, 1000000 + 1):
if is_prime[i]:
count += 1
if count == number:
... | a6b24271c8b7149d2a7a7d3b04d3e933c82d73fb | 635,032 |
def flicker_amplitude_to_frequency(flicker_amplitude : float) -> float:
"""
Converts the flicker amplitude to the first filter frequency according to Kallinger et al. (2016)
:param flicker_amplitude: Flicker amplitude calculated according to Bastien et. al (2013)
:return: First filter frequency
"""
... | 772bb939b78b1ab2092a20764bd9c46c19873295 | 635,033 |
def remove_surplus_bcc_clusters(clusters, bcc_frac):
"""From a list of contour clusters, remove those with too many BCCs."""
if bcc_frac == 1.0:
return clusters
good_clusters = []
for clust in clusters:
# Retain if not outermost contour
if clust.parent is not None:
... | 0d7c2dabd83608f60cb3a11e0e52697eebbb5273 | 635,034 |
import six
def is_primitive(val):
"""
Checks if the passed value is a primitive type.
>>> is_primitive(1)
True
>>> is_primitive("abc")
True
>>> is_primitive(True)
True
>>> is_primitive({})
False
>>> is_primitive([])
False
>>> is_primitive(set([]))
:param ... | da3c0adc341a406719b786a487b0e1baad037657 | 635,035 |
import math
def get_distance(c1, c2):
""" Returns approximate distance between two pairs of coordinates in km.
Args:
c1: coordinate pair 1
c2: coordinate pair 2
Returns:
distance in km between c1 and c2
"""
# approximate radius of earth in km
R = 6373.0
lat1 = ma... | 1cc9b8933b56944df12ae842780386d35d9f984d | 635,036 |
import subprocess
def expand_file_paths(value):
"""Expand filepaths."""
command = ("find " + value + " -type f 2>/dev/null")
process = subprocess.run(command, stdout=subprocess.PIPE, shell=True).stdout
expanded_files = process.strip().decode('utf-8').split('\n')
return expanded_files | 15a2fc0e09aa3b616c87c6346f78a3ab51c7c0da | 635,037 |
def convert_kwh_gwh(kwh):
""""Conversion of MW to GWh
Input
-----
kwh : float
Kilowatthours
Return
------
gwh : float
Gigawatthours
"""
gwh = kwh * 0.000001
return gwh | aaee060f7bab8571066706a0219d4d1b0508bcbb | 635,038 |
def dbt_project_dir(tmp_path_factory):
"""A temporary directory to store dbt test files."""
d = tmp_path_factory.mktemp("project")
return d | a40c36c3236132f203f8ee263c9e3b4fc4a51cee | 635,039 |
def GetCbsdRegistrationRequest(cbsd):
"""Returns a CBSD registration request from the |Cbsd| object.
"""
return {
'cbsdCategory': cbsd.category,
'installationParam': {
'latitude': cbsd.latitude,
'longitude': cbsd.longitude,
'height': cbsd.height_agl,
'heightType... | 2720960f20e9eb792f0cc4dc5564c85a5dd69743 | 635,041 |
def states_bedline_to_vector(bedlines, states_dic):
"""
Convert a line from a bedfile containing states in categorical data to vector format.
Parameters
----------
bedline: [string,...]
A line form a bedfile broken up into its contituent parts
(e.g. ["chr1", "1000", "2000", "state"... | 1d95c73b09ac98290ffe4c84037d4ef2a5e0d85c | 635,042 |
import re
def is_valid_volume_id(volume_id):
"""
Validates drive and volume IDs, also known as the drive/volume "name".
A valid volume name should look like: volume-00000001 - It should always
start with "volume-" and end with 8 hexadecimal characters in lower case.
:type volume_id: str
:para... | 272f2ba61b1974da323fa31fe72ebb093056a424 | 635,043 |
def Not(query):
"""The negation of a query"""
return '(NOT %s)' % (query,) | 9bddebbd3c3c8e4c2e8e74b6c87049f0e4706dcb | 635,044 |
def lerp(xvar, xlim, ylim):
"""linearly interpolate a value of y given ranges for x, y.
arguments:
xvar: scalar
xlim: array with xmin, xmax
ylim: array with ymin, ymax
"""
delta_x = (xvar - xlim[0])
slope = ((ylim[1] - ylim[0]) / (xlim[1] - xlim[0]))
yvar = ylim[0] +... | a637d415555e80abf46b69d216d1acc63d4ed5ee | 635,045 |
def incidentlist(xml):
"""
Takes the full incident XML and returns a list of dictionaries with 'agency code' and 'incident number' tag and
text elements.
"""
i_list = []
for i in xml.iter('Incident'):
i_dict = dict()
i_dict['agency_code'] = i[2].text
i_dict['incident_numb... | 352f8291c509a5071bce93b01cd089626018f9c0 | 635,046 |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
"""
def helper(amt, min_coin_value):
if amt < 0:
return 0
elif amt ... | 87740318e9395b79e24b22e07c4e56bc6aa2e91c | 635,047 |
def _parse_dict(dct):
"""Auxiliary function to change the keys of a dictionary."""
return {k.split(":", 1)[-1]: v for k, v in dct.items()} | 4ab2d9de45aa6e852650a63f28b54d09805cec6c | 635,048 |
def fitAngleToBaxter(angle):
"""
Returns an angle fitted to use with Baxter.
Parameters
----------
angle (float): Angle to convert.
Returns
-------
new_angle (float): Angle transformed into Baxter's yaw.
"""
new_angle = -90.0 + angle if angle <= 90.0 else -180.0 + (angle - 90.... | 95e823ef9adb822b74b753fb8d4e55297f0631b4 | 635,049 |
def inside(x, a, b):
"""
test x \in (a, b) or not
"""
l = 0
# if not torch.isreal(x):
# return l
if a <= b:
if x >= a and x <= b:
l = 1
else:
if x >= b and x <= a:
l = 1
return l | 43447ca91f2fdb27ccbc05996fcdafd43ada388c | 635,050 |
import random
import copy
def test_get_diff(lambda_module, get_product):
"""
Test get_diff()
"""
def _get_product():
product = get_product()
product["quantity"] = random.randint(1, 10)
return product
old_products = [_get_product() for _ in range(5)]
new_products = cop... | 36382d910e50bc2a4f573cf42f8bbdd6b9b4498d | 635,051 |
def combine_adjacent(arr):
"""Sum like signed adjacent elements
arr : starting array
Returns
-------
output: new summed array
indexes: indexes indicating the first
element summed for each group in arr
"""
output, indexes = [], []
curr_i = 0
while len(arr) > 0:
... | 46638cc7f52df03c117d0ba6e300d9c3b5449431 | 635,052 |
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if len(word) == 0:
return [""]
else:
res... | 715d8bbdc0348daec08d302be244971d8f6f25de | 635,053 |
def get_str_from_params(params: dict):
""" Returns string from the parameters """
result = list()
keys = list(params.keys())
length = len(keys)
result.append("%s=%s" % (keys[0], params[keys[0]]))
for i in range(1, length):
result.append(":%s=%s" % (keys[i], params[keys[i]]))
return... | d4a169b61174ecd42a71eb9f1d540670bf780878 | 635,054 |
def sign(s):
"""
计算签名
:param s:
:return:
"""
mask = (1 << 32) - 1
hash1 = hash2 = 5381
l = len(s)
i = 0
while i < l:
c = ord(s[i])
hash1 = ((((hash1 << 5) & mask) + hash1) & mask) ^ c
i += 1
if i >= l:
break
c = ord(s[i])
... | 4c6d6a4dc005d5940b70bf55cd014f1935d4166b | 635,055 |
from typing import List
from typing import Tuple
import array
def _linestring_to_coords(geometry: List[BaselinePath]) -> List[Tuple[array]]: # type: ignore
"""
Get 2d coordinates of the endpoints of line segment string.
The line segment string is a shapely.geometry.linestring.
:param geometry: the li... | 5a374f7010d7918466949e87db91a9ebf28a2138 | 635,056 |
import json
import base64
def generate_key(json_: str) -> str:
"""generate base64 encoded key build by json using "key1+value1+key2+..." method
Args:
json_ (str)
Returns:
bytes: key
"""
encoded_string = ''.join([f'{key}{value}' for key, value in json.loads(json_).items()])
re... | 8af5ab750ec6f35ec2e257f56bd357200e6c6d72 | 635,057 |
def get_decoder_for_id(header_dict):
"""
Returns a dictionary that goes:
`dict[dataIdNum] = "decoderName"`
e.g: d[5] = 'ORSIS3302DecoderForEnergy'
"""
d = dict()
for class_key in header_dict["dataDescription"].keys():
super_keys_list = []
for super_key in header_dict["dataDes... | 64378dc3bf0afd334b18c78c398fede6cb872fe3 | 635,058 |
def get_tokens(tagger, content):
"""
文書内に出現した名詞のリストを取得する関数。
"""
tokens = [] # この記事で出現した名詞を格納するリスト。
node = tagger.parseToNode(content)
while node:
# node.featureはカンマで区切られた文字列なので、split()で分割して
# 最初の2項目をcategoryとsub_categoryに代入する。
category, sub_category = node.feature.spli... | fa43ddaf6cb554e437a80664ed713a348653db06 | 635,059 |
def sort_points_by_Y(list_of_points):
"""Given a list of 2D points (represented as Point objects), uses "sorted"
with the "key" argument to create and return a list of the SAME (not copied)
points sorted in decreasing order based on their Y coordinates, without
modifying the original list."""
return... | cc4a67b839d3e0ae1793e8cde9c17113022c7266 | 635,060 |
def tokens_to_index(token_list, vocab_dict):
"""
convert word tokens to number index
INPUT:
token_list: a list of string tokens
vocab_dict: a dictionary with tokens(key)-integer(value) pairs
OUTPUT:
index_list: a list of integer indices
"""
index_list = []
for x in t... | 1692858ea21bed7812c92db9cb09eb4e9a6a3641 | 635,061 |
import os
def isFile( path ):
"""
Returns a boolean whether or not 'path' points to a regular file.
"""
return os.path.isfile( path ) | bd8dd211dcc53247b2b219610b8979cc5125a46e | 635,062 |
import argparse
def parse_arguments():
"""Parses command line arguments.
Returns:
An object containing parsed arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--log_level', default='INFO',
help='The logging threshold.')
# Database connectivity arguments
... | f0b9f5c0f3f92d3b174b1218ed9d819c3054ebe6 | 635,063 |
import re
def is_valid_mac_address(mac):
"""
This will only validate the HHHH.HHHH.HHHH MAC format.
"""
if re.match('[0-9A-Fa-f]{4}[.][0-9A-Fa-f]{4}[.][0-9A-Fa-f]{4}$', mac):
return True
else:
return False | da21189bf7909347821346bd21ef0b40b6850d37 | 635,064 |
from typing import Union
def _(value: Union[bytes, bytearray]) -> bytes:
"""Convert ``bytes`` or ``bytearray`` to bytes"""
return value | d595fe96c27f8ef58677935c80879ff8ebc2fc24 | 635,065 |
def available_sparse_deep_model():
"""
List available sparse deep learning subjectivity analysis models.
"""
return ['fast-text-char'] | 6ec22f65cd00ea3f9885de9f8732f88e3fb2735a | 635,066 |
def _keyword_parsed_main_name(job):
"""
Return string of the parsed `main_name` of the job
"""
split_at_last_dot = str(job.main_name).rsplit(".", 1)
last_dot_replaced = " ".join(split_at_last_dot)
stripped_underscore = last_dot_replaced.replace("_", " ")
return stripped_underscore | 51d8526117f14dd37bea8c77ae08511933bd3d02 | 635,067 |
def comp_height_wire(self):
"""Return wire height
Parameters
----------
self : CondType11
A CondType11 object
Returns
-------
H: float
Height of the wire [m]
"""
return self.Hwire | 2ffa94d53d154781a835873e46a3d528859c2746 | 635,068 |
def sample_sum_func(num_a: int, num_b: int) -> int:
"""
:rtype: object
:param num_a: first number
:param num_b: second number
:return: sum of two numbers
"""
sum_two_numbers: int = num_a + num_b
return sum_two_numbers | 74c9e555721beb95f785f1c5201e26078559caba | 635,069 |
import sympy
import six
import random
def _split_factors(integer):
"""Randomly factors integer into product of two integers."""
assert integer.is_Integer
if integer == 0:
return [1, 0]
# Gives dict of form {factor: multiplicity}
factors = sympy.factorint(integer)
left = sympy.Integer(1)
right = symp... | 5a0adbc43296c325ee01b2043e5096c9702ce562 | 635,070 |
import json
def get_test_ids(check_nightly_status=False):
"""Get the test ids from conf.json
Keyword Arguments:
check_nightly_status {bool} -- if we are running nightly test (default: {False})
Returns:
tuple: (test_ids, skipped_tests)
"""
test_ids = []
with open("./Tests/conf... | 16efc15faaa16712069556191ee000cf7ada883e | 635,072 |
def compare_location_and_region(first_file, second_file):
"""
Compares versions for osfstoragefiles -
Compares location['bucket'] and location['object'].
Also compares version region_ids.
"""
first_loc = first_file['versions__location']
second_loc = second_file['versions__location']
if ... | 534e917e82a65472b4ca5f99f08ff3d523ff9321 | 635,073 |
def spritecollide(sprite, group, dokill, collided=None):
"""
**pyj2d.sprite.spritecollide**
Return list of sprites in group that intersect with sprite.
The dokill argument is a bool, True removes sprites that collide from all groups.
An optional collided is a callback function taking two sprite... | 3af14da2a26c2bdc733e16d44eb76a8009f99ac4 | 635,074 |
def make_error_logger(logger):
"""Make handlers that logs and ignores encoding errors."""
def log_errors(exc):
logger.error('incorrect character encoding', exc_info=exc)
return ('', exc.end)
return log_errors | 94d185f4a53cc4f54bb6cf7cd3f2d9abc8ec0e1a | 635,075 |
import csv
def extract_ti_places_dict(path='./data/ti_places.csv'):
"""
Extracts a dictionary that keeps track of the ti places for each administrative area.
The index column is 'istat_code', the population column is 'ti'.
:rtype: Dictionary
"""
with open(path, mode='r', encoding='utf-8-sig')... | e74e1c19e78e688acdd21e10d177ef0197bc6602 | 635,076 |
import requests
def check_http_status(host, port, **kwargs):
"""
Check that the HTTP status is normal.
:param host: The host address.
:param port: The port number.
:return bool: The return value is a Boolean.
"""
url = 'http://{}:{}'.format(host, port)
try:
res = requests.requ... | 0d64828c8c61f2c0e0521a408ce06fbc0313b9dd | 635,077 |
def is_compressed_key(pubkey_buffer):
"""
Checks whether or not a public key is compressed.
:param pubkey_buffer: public keys as bytes obj.
:return: true if public key is compressed; false otherwise
"""
if not isinstance(pubkey_buffer, bytes):
raise ValueError
length = len(pubkey_bu... | 2ec03c1982ab0cee2bb48e954dc088422f2e0696 | 635,078 |
def _detect_skipped_track(remaining_duration: float,
end_of_track_buffer: float, track: dict,
prev_track: dict) -> bool:
"""Performs the detection logic for whether a track was skipped
Args:
remaining_duration: The remaining duration of the track in m... | 93b90930f1c87131bec2958d6f81eed645133e2a | 635,080 |
def get_crashes_archive_name(cycle: int) -> str:
"""Return as crashes archive name given a cycle."""
return 'crashes-%04d.tar.gz' % cycle | f466f2c1fd0a578109e52175e6a6629bdeb2c2b2 | 635,081 |
def _output_filename(title):
"""Construct output filename."""
return title + ".html" | 46ada33d35a9a6acc77f06a32eac49692e546eaf | 635,083 |
import time
import os
def read_file_content(file_path, timeout_seconds):
"""
Read file content
:param path: Filepath
:param timeout_seconds: Time to wait until file exists
:return: File content
"""
end_time = time.time() + timeout_seconds
while end_time > time.time() and not os.path.ex... | 9211de7591f595b5e61a5f979b6a6e9b55d3561a | 635,084 |
def jn_second_zero(n):
"""Get an approximated location for the first zero of
spherical bessel's function at a given order n"""
# formula 9.5.14 in Handbook of Mathematical Functions
v = n + 0.5
return v + 3.2446076*v**(1/3) + 3.1582436*v**(-1/3) - \
0.083307*v**(-1) - 0.84367*v**(-5/3) + 0.8... | 85c8fbe12c62e15a9480e385763341aa461ed48c | 635,085 |
import os
def index_command(kiwix_bin, input_filename, output_dirname):
"""Index zim file"""
cmd = [os.path.join(kiwix_bin, 'kiwix-index'),
'-v',
input_filename,
output_dirname]
return cmd | d66c53f0d6ab6f98548214c0ef26a01a0344bda6 | 635,086 |
def binomial(row: int, column: int):
"""
Calcula o coeficiente binomial correspondente ao triangulo Pascal
:param row: numeradores do binomio
:param column: denominadores do binomio
:return: coeficiente calculado
"""
# linha (numerador) ou coluna (denominador) não podem ser negativos
if ... | 70b06b2bd52b9335daf11c4b2c76ba52d8c59ba8 | 635,087 |
from typing import Dict
from typing import Union
from typing import List
import itertools
import copy
def gen_hparam_set(
src_dict: Dict[str, Union[List[object], object]]
) -> List[Dict[str, object]]:
"""
Generate a collection of hyperparameters for hyparam searching.
NOTE: in this version, a paramete... | f851dc84f649178a36aefc08527807217eca88e3 | 635,088 |
from typing import OrderedDict
def expand_params(param_values):
"""expand combinations of parameter values"""
# param_values - list of tuples of parameter names and lists of values
n_params = len(param_values)
if n_params == 0:
return []
param_counts = [len(x[1]) for x in param_values]... | 26ebe45f786866493493155faad9e48809d02556 | 635,089 |
import requests
import json
def search(q, h, t, p=bool):
"""
OUR MAIN SEARCH ENGINE - ONLY BRINGS BACK THE FIRST THREE RESULT
:param q: query to search for
:param h: the required headers for trakt api
:param t: type we are looking for ("show", "movie", etc)
:param p: Not used
:return: a d... | 83820974fb7be5562197cb86941c336ab2b24b40 | 635,090 |
def is_palindrome(word):
"""Returns true if the word is a palindrome."""
return word == word[::-1] | aacaae1cb0efa3c5fc743231e61f58d1408807ee | 635,091 |
def verify_approval_skip(data, env, env_configs):
"""Determines if a approval stage can be added/removed from a given
environment pipeline stage based on environment setting. Defaults to false,
and verifies administrators allow skips in given environments.
Args:
data (dict): environment config d... | 521e6b4b151ee509f75a9698c0ea74fe2d4af532 | 635,092 |
def get_formatted_name(name):
"""
Return a 3-letters acronym in upper case and longer names in PascalCase.
Exemple: 'sql' -> 'SQL'; 'hunting' -> 'Hunting'
"""
if len(name) == 3:
neat_title = f"{name.upper()}"
else:
neat_title = f"{name.capitalize()}"
return neat_title | c27da647d6615e899653d9ca75ae178d194f7736 | 635,093 |
def curvature_from_stroke_vertex(svert):
"""The 3D curvature of an stroke vertex' underlying geometry
The result is None or in the range [-inf, inf]"""
c1 = svert.first_svertex.curvatures
c2 = svert.second_svertex.curvatures
if c1 is None and c2 is None:
Kr = None
elif c1 is None:
... | c8472e8021fe6359c7700c994145bf6e904368c2 | 635,094 |
def human_readable(value):
"""
Returns the number in a human readable format; for example 1048576 = "1Mi".
"""
value = float(value)
index = -1
suffixes = 'KMGTPEZY'
while value >= 1024 and index + 1 < len(suffixes):
index += 1
value = round(value / 1024)
if index == -1:
... | a8dc87493d0d8e7f8732630831991d58b8f01d38 | 635,095 |
import numpy
def edger_matrix(work_counts, conditions, regions):
"""Count matrices for input into edgeR differential expression analysis.
"""
data = []
final_regions = []
for r in regions:
cur_row = [int(work_counts[c][r]) for c in conditions]
if sum(cur_row) > 0:
final... | 8ad3a483ec52af322cb720e2fa04626c12bed570 | 635,096 |
def _calc_data_point_ticks(x_locations, num_distributions, distribution_width,
distribution_centered):
"""Returns a 1D numpy array of x-axis tick positions.
These positions will be centered on each data point.
Set distribution_centered to True for scatter and box plots because t... | c8775aab85f27465bcb2ac55c339bb6af8380e0b | 635,098 |
def rain(walls):
"""
walls is a list of non-negative integers.
Return: Integer indicating total amount of rainwater retained.
Assume that the ends of the list (before index 0 and after index
walls[-1]) are not walls, meaning they will not retain water.
If the list is empty return 0.
"""
... | e26b22f09823f4a09b8f209780152ed739bf78bd | 635,099 |
def separable_conv(graph, input, all_w, kernel_dim, layer_id):
"""Defines a separable convolution.
Args:
graph: The TASO graph.
input: The input tensor.
all_w: A list of lists of weights (one list for each layer).
kernel_dim: The size of the kernel.
layer_id: The ID o... | 54762e65d63732f353c6bb73b3b4966706d828b6 | 635,100 |
def lambda_(xTk): # pragma: no cover
""" latent heat of vaporization: J / g
:param xTk - temperature (K):
:return:
"""
return 3149 - 2.370 * xTk | fd53a5f83afbd8c9f296425adb11718ecf7c180f | 635,102 |
def get_slurm_header(slurm_dict, walltime_hrs, num_nodes=None):
""" Write a SLURM script header from a set of slurm parameters.
Parameters:
slurm_dict (dict): dictionary of SLURM environment variables.
walltime_hrs (int): allowed walltime in hours
Keyword arguments:
num_nodes (int)... | fcc5abfe03e97d6daf73dbbbab87e9cc3f98ec66 | 635,103 |
import functools
def empty_energy_result(energy_result):
"""
Return False if the energy_result list contains only negative numbers, True otherwise
"""
return functools.reduce(lambda acc, x: acc or (x >= 0), energy_result, False) | 980cd49f687ee975eac773139855eec2a4fd59d2 | 635,104 |
def normalized_to_microseconds(normalized_setpoint: float, low: int, center: int, high: int) -> int:
"""
Converts a normalized setpoint (between -1.0 and 1.0) to a pulse width (in microseconds).
Positive and negative values are computed separately, as they can span different intervals in terms of pulse wid... | 65282397c23f77a96032330cf4dbf4d176b8ae0c | 635,105 |
import requests
def post_request(url, body, headers):
"""
Method which makes a POST request to specified url
:param url: url
:param body: data in json format
:param headers: headers
:return: post response
"""
return requests.post(url, data=body, headers=headers) | da685722b716f6523352b199625f9e7570feefd8 | 635,107 |
def combine_dicts(name_to_dict):
"""Given a dictionary of (name, child_dict), return the combined version of each item in the child dictionary."""
combined = {}
for dict_name, current_dict in name_to_dict.iteritems():
for name, val in current_dict.iteritems():
combined[dict_name + '_' + name] = val
re... | 763990ba4eadfe0e65eb3cd7bebcde05c26b0b2b | 635,108 |
def get_score(scores, args):
"""
Gets the alignment scores from the aligner and calculates the maximum
alignment score between the two exon ends that could have lead to template
switching.
"""
pos = args.shs_for_ts + 1
rscores = []
score = 0
while pos <= 2 * args.shs_for_ts:
... | eaf76a929b78dbd9116a062fcc637e20729147c7 | 635,109 |
def getsystinfo():
"""Help function to create description of systematic inputs."""
return "Systematic variation: 'nom', 'up', 'down'" | bccc5b3d3c581beb3f4ee9594247837c566fe6b8 | 635,110 |
def main_path():
"""
Śceżka do folderu z plikami
Path to folder with files
"""
return "python_crash_course/files/" | 5ad9f8abb018c5e5d6d68ea30cafd5fc124aa31e | 635,111 |
from typing import Optional
from typing import Union
from typing import Iterable
from typing import List
def listify_decorator_args(
argument: Optional[Union[str, Iterable[str]]],
) -> List[str]:
"""Converts a user-supplied "list" to an actual Python list.
This helper supports a "string" list as follows:
... | 283b095eb4d560ffe22d6ac84b2f4846f5bea2ef | 635,112 |
def precision(confusion, classes, classifiers):
""" Compute the precision from a confusion matrix.
Parameters
----------
confusion : array, shape = [n_classes, n_classes]
Where entry c_{ij} is the number of observations in class i but
are classified as class j.
... | 2ba2f28d51debd375104fed63f69bf87e842d6cf | 635,113 |
import numpy
def symbolise_mfcc(mfcc):
"""Symbolise speech according to mfcc.
Args:
mfcc (2D numpy.array (float)): A list of mfcc, axis 1 is time and axis 0 is mfcc
Returns:
symbols (numpy.array (float)): A list of symbols.
"""
symbols = numpy.zeros(mfcc.shape[1])
mu = numpy.... | 5747145160940b1fee7cd01277f614f3fdb85afe | 635,114 |
def insert_file_paths(command, file_paths, start_delim='<FILE:', end_delim='>'):
"""
Insert file paths into the command line at locations indicated by
the starting and ending delimiters.
"""
tokens = command.split()
final_tokens = []
for token in tokens:
if token.startswith(start_del... | 1d433d99332db84a6e91b82acfa27939e63d7bfe | 635,115 |
def getParameterFromCall(call, index=0):
"""
Returns a parameter node by index on the call node
"""
try:
return call[1][index]
except:
return None | 78cc1521576842d74c5c4d0dce5606587beb2422 | 635,116 |
import math
def triangle_geometry(triangle):
"""
Compute the area and circumradius of a triangle.
Parameters
----------
triangle : (3x3) array-like
The coordinates of the points which form the triangle.
Returns
-------
area : float
The area of the triangle
circum_... | 9cb5124fd30cc27c24d92c7e466ac67fe5d464ff | 635,117 |
def aread8(np, input, output):
""" command: aread8 -p demp.tif -ad8 demad8.tif [-o outletfile.shp] [-wg demwg.tif] [-nc], pfile: input flow directions grid, ad8file: output contributing area grid, Outletfile: input outlets shapefile, wgfile: input weight grid file """
aread8 = "mpirun -np {} aread8 -p {} -ad8 ... | aaed2746f896f59689f396338ded0185961be26f | 635,118 |
import torch
import random
def gen_input_mask(
shape, hole_size, hole_area=None, max_holes=1):
"""
* inputs:
- shape (sequence, required):
Shape of a mask tensor to be generated.
A sequence of length 4 (N, C, H, W) is assumed.
- hole_size (sequence or in... | 799e5cd0590a58012888707b2997b69992a45f83 | 635,119 |
def pack_2byte_to_hn(low_byte, high_byte):
"""
Pack 2 bytes to network order unsigned short
"""
return ((low_byte << 8) | high_byte) & 0xffff | d8c41013feec2c61b011b6b99ea42b1104198609 | 635,120 |
from typing import Callable
import sys
def before_open(function: 'Callable') -> 'Callable':
"""
Decorator that allows for a given downlink method to be executed only before the downlink has been opened.
The downlink should have an `is_open` flag set to False.
:param function: - Decorated downl... | 573b0360fba3fa7f5d1783d2ce3c8ca1c2a588bb | 635,121 |
def loader_encode_pcr8(cmdline):
"""
Encode kernel command line the same way systemd-stub does it before measuring.
"""
return (cmdline + "\0").encode("utf-16le") | d80ebfa8b256ea366c87737f725fefca93df4b96 | 635,122 |
import uuid
import random
def generate_single_header():
"""Generate a single header"""
return {
"executionId": str(uuid.uuid1()),
"executionDate": "",
"executionSucceeded": random.choice([True, False]),
"executorName": "",
"executionType": "DECISION",
} | b59746d26d76c1d320aa680cf1817bba0fc16544 | 635,123 |
def close_enough(vector_one, vector_two):
"""Check that the values for vectors are close enough (< 0.1)"""
for i in range(len(vector_one)):
for j in range(len(vector_one[i])):
if vector_one[i][j] - vector_two[i][j] > 0.1:
return(False)
return(True) | bd70956a4a550431dd3b0a6e928113d868778e77 | 635,124 |
def duration(duration, compact=False, unit=False):
"""Returns a time duration string representing the input value
:param duration: value to format, must be convertible into an into
:param compact: whether to show also seconds, defaults to False
:param unit: whether to display he unit, defaults to False... | 15b55f3f051a34a846ec3210f5081ab55fddb10e | 635,125 |
def getDBReleaseVersion(dbh, jobPars): # extra-wrapper function, to be deprecated?
""" Get the DBRelease version from the job parameters """
return dbh.getDBReleaseVersion(jobPars=jobPars) | d3d8ded7c8fbba37574d9f7d896fd394129edde5 | 635,126 |
def read_bdseq(message):
"""Read the bdSeq number from a TAHU message."""
for metric in message.metrics:
if metric.HasField('name') and metric.name == 'bdSeq':
return metric.long_value
return None | 8200784741bbab42532728c348739f709d8e32bc | 635,127 |
def _guessFileFormat(file, filename):
"""
Guess whether a file is PDB or PDBx/mmCIF based on its filename and contents.
authored by pandegroup
"""
filename = filename.lower()
if '.pdbx' in filename or '.cif' in filename:
return 'pdbx'
if '.pdb' in filename:
return 'pdb'
f... | ab04db18b05ee416315d8d2faa2381e469dda955 | 635,128 |
def e_d(val):
"""energy divisor"""
if val == 0: return 10000
elif val == 1: return 1000
elif val == 2: return 100
elif val == 3: return 10
else: return None | d5466cf9867a85281fc624d1042f51c2c2255e06 | 635,129 |
def getPhoneNumbers(accountName):
"""Returns a list of outgoing phone numbers for a Twilio account.
Note that these numbers are supplied by Twilio, and are not defined
on a user in Ignition.
Args:
accountName (str): The Twilio account to retrieve phone numbers
for.
Returns:
... | 7dd66e5cd2af3e792c5bedc77dfb90a598f24767 | 635,130 |
import os
def get_dict_names(dict1_path, dict2_path):
"""
Get the name of the dictionaries for the end user. Use the base name of the
files. If the two base names are identical, returns "dict1" and "dict2."
@param dict1_path: The path to the first dictionary.
@param dict2_path: The path to the sec... | 421caa537ef1d3214af404a95302a5699c8d07e1 | 635,131 |
def env_config() -> dict:
"""
Configures a database connection using an environment variable (Oracle and PostgreSQL only).
:return: A dictionary containing information about the newly-created database connection.
"""
env_var = input(
"\nIdentify the name of the environment variable the conn... | bb181e3e6e12e6d6e2cf278a361a2b3ac7e6f3f3 | 635,132 |
def find_sub_list(sub_list, main_list):
"""Find starting and ending position of a sublist in a longer list.
Args:
sub_list (list): sublist
main_list (list): main longer list
Returns:
(int, int): start and end index in the list l. Returns None if sublist is not found in the main lis... | d9e0a4bad9854f3914d07c176ca5708e11bd0cd8 | 635,133 |
def some_function(foo: int, bar: str = "optional") -> str:
"""
This is some function.
:param foo: The first parameter.
:param bar: The second parameter.
:returns: The result of the function.
"""
return f"some_value {foo} {bar}" | c9f8a02dbf43b1242d15f2c85e15726ce359f057 | 635,134 |
import logging
def set_user_info(ctx, gnupghome):
"""Set user information and return gnupghome and email."""
config = "gnupghome=" + gnupghome + "\n"
# Store config file and other information.
ctx.config.touch(exist_ok=False)
with ctx.config.open("w") as f:
f.write(config)
logging.in... | 9cfc0a5703f1e11adf2d1b1cf9ee6318361337ae | 635,135 |
def roman_event(date):
"""Return the event of Roman date 'date'."""
return date[2] | f0c6ccf62b8c63a43a0158a7c744343cabb7d311 | 635,136 |
def get_ip_v4_class_mask(ip_int):
"""Return a mask indicating bits preserved when preserving class."""
if (ip_int & 0xE0000000) == 0xE0000000:
return 0xF0000000
elif (ip_int & 0xC0000000) == 0xC0000000:
return 0xE0000000
elif (ip_int & 0x80000000) == 0x80000000:
return 0xC0000000... | 5288f7c13e1305aff0efa3486148e9fdc5d29512 | 635,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.