content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def datetime_to_ds_nodash(dt):
"""Convert a Python datetime object to a string with the format YYYYMMDD"""
return dt.strftime('%Y%m%d') | 0fc8ef07fb3153bc9a3b561fdbf3b6fdfe33de7a | 626,668 |
def init_model_with_data(model_obj, data_dict):
"""instantiate the generated tfp model object with data
Parameters
----------
model_obj : tfd.Distribution
an un-instantiated model object
data_dict : dict
data for the model
Returns
-------
tfd.Distribution
... | f71bab16321d3e2d0413e5483b320c8097930ae1 | 626,669 |
def quintic_easein(pos):
"""
Easing function for animations: Quintic Ease In
"""
return pos * pos * pos * pos * pos | 2a5c722315940d00e5be50e3c597d42a0b627268 | 626,676 |
def _format_exception(exception):
"""Formats the exception into a string."""
exception_type = type(exception).__name__
exception_message = str(exception)
if exception_message:
return "{}: {}".format(exception_type, exception_message)
else:
return exception_type | ca1fd85ade965172531a0b5db0e84eefb4520c2a | 626,678 |
def query_attr_where(params, table_ref=True):
"""
Construct where conditions when building neighbors query
Create portion of WHERE clauses for weeding out NULL-valued geometries
Input: dict of params:
{'subquery': ...,
'numerator': 'data1',
'denominator': ... | 57f653044843db4dea0cacc32c9165632362169b | 626,681 |
def round_nearest(value, multiple_of):
"""round to `multiple_of` value.
based on: https://stackoverflow.com/a/28425782/574981
"""
return round(value / multiple_of) * multiple_of | e103cf748b0c7bf15f7eb0600561bda96a7c93ca | 626,689 |
import json
def get_connection_string(credential_path):
"""Converts credentials JSON to a connection string."""
with open(credential_path) as file_ptr:
credential_dict = json.load(file_ptr)
connection_string = credential_dict['connection_string']
full_connection_string = connection_string.f... | 90a41fc4e260012cfe67a4ac5d997a5df0b9b119 | 626,690 |
def sextodec(xyz, delimiter=None):
"""Decimal value from numbers in sexagesimal system.
The input value can be either a floating point number or a string
such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " "
can be specified using the keyword ``delimiter``.
"""
divisors = [1, 60.0, 3600... | 01a18426e3dd63a2f411647b83ee72c40eccd847 | 626,699 |
def from_db(x):
"""
Convert from decibels to original units.
Inputs:
- x [float]: Input data (dB)
Outputs:
- y [float]: Output data
"""
return 10**(0.1*x) | 2262aaff83b8064f17a52b5f46263caaca4d6913 | 626,703 |
def index(seq):
"""
Build an index for a sequence of items. Assumes
that the items in the sequence are unique.
@param seq the sequence to index
@returns a dictionary from item to position in the sequence
"""
return dict((k,v) for (v,k) in enumerate(seq)) | 1367da75882ea1d7daaff0a515b09a3d72d38815 | 626,705 |
def calc_variables(df, var_list):
"""Calculate area-weighted values for variables.
Formula: x_pre=A_intersect1 / A_pre * x_bg1 + A_intersect2 / A_pre * x_bg2
Args:
df (DataFrame): the dataframe containing census spatially merged with precincts
var_list (list): names of variables to calcul... | 09f122842a5f32447e7c89ae6cae730976a50921 | 626,706 |
import requests
def request_ct(url):
"""Performs a get request that provides a (somewhat) useful error message."""
try:
response = requests.get(url)
except:
raise IOError(
"Couldn't retrieve the data, check your search expression or try again later."
)
else:
... | 0c1299724ae1141358349d4fd7b98b94c9a3154f | 626,708 |
def replace_spaces(text):
"""
Replace spaces with a dash.
"""
if not isinstance(text, str):
return text
return text.replace(" ", "-") | fb32adfc90f9aba00cc65473a6a4cf09b01968a5 | 626,709 |
def log_format_metadata(metadata):
"""Return a string representation of the metadata formatted for log output.
"""
return ", ".join("{}={}".format(k, v) for k, v in metadata.items()) | a3449491996a8412fd6fb6c579283267f2ab8e26 | 626,710 |
import math
def shubert04(ind):
"""Shubert04 function defined as:
$$ f(x) = \sum_{i=1}^n \sum_{j=1}^5 j cos((j+1)x_i) + j $$
with a search domain of $-10 < x_i < 10, 1 \leq i \leq n$.
"""
return sum(( sum((-j * math.cos((j+1) * ind[i] + j) for j in range(1, 6))) for i in range(len(ind)))), | ed764bffa7b37286d1caa6e16dfe96804976e75e | 626,711 |
def safe_sum(v1, v2):
"""Sum two integers (string type) accounting for the possibility that one or both
is missing; returns an integer."""
if v1:
if v2:
return int(v1) + int(v2)
else:
return int(v1)
if v2:
return int(v2)
return 0 | 2fcae1373ce981079ccc50472e4e1e3d27d52c60 | 626,713 |
def render_services(args, df):
""" replace service number with service name, for common services"""
for col in ['srcport', 'dstport']:
df[col][df[col] == '22'] = 'ssh'
df[col][df[col] == '23'] = 'telnet'
df[col][df[col] == '53'] = 'domain'
df[col][df[col] == '80'] = 'http'
... | adee9b81f84cb91e23b9c6797864fb350e7a4c3e | 626,714 |
def tuple_add(tuple_a: tuple, tuple_b: tuple) -> tuple:
"""Return the result of the addition of two tuples."""
return tuple(map(lambda x, y: x + y, tuple_a, tuple_b))
# Source: https://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum | 0ffa95ce1f47ef87687ac675b750348f6985f631 | 626,715 |
def signal_percent_to_dbm(percent: int) -> int:
"""
arbitrary conversion factor from Windows WiFi signal % to dBm
assumes signal percents map to dBm like:
* 100% is -30 dBm
* 0% is -100 dBm
Parameters
----------
percent: int
signal strength as percent 0..100
Returns
--... | 83b6ce9c47c6966d0bc97b76a5dc28280e4e26f5 | 626,716 |
def fibonacci(n):
"""
This is the original function, it will be used to compare execution times.
"""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | 1ca15b9bfd259712b924f7f2f67f34183a701555 | 626,719 |
def find_by_name(name, items):
"""
Find the object with the specified name attribute.
:param name: str: name to look for
:param items: [object]: list of objects to look for
:return: first item matching name or None if not found
"""
for item in items:
if item.name == name:
... | 7b12dde6ca985143ce8eca86baf7884acfb85657 | 626,723 |
def disc(x):
"""
Returns 'x' rounded to the nearest integer.
"""
return int(round(x)) | 726d08f3d1b02fdce809ef53b936b87f84628b29 | 626,728 |
def _read_filepath(source: str) -> str:
"""
Read file contents
"""
with open(source, 'r', encoding='utf-8') as infile:
contents = infile.read()
return contents | cb22c6eee9a5fc54c513b751e36440f9b86e4522 | 626,729 |
def is_podcast_series_id(item_id):
"""Validate if ID is in the format of a Google Music series ID."""
return len(item_id) == 27 and item_id.startswith('I') | e17f7a5419d40689c6a0ac8a99da7260aca48774 | 626,733 |
import torch
def format_abstract_tensile(cycles, predictions):
"""
Format abstracted tensile test data, where only the yield strength
and ultimate tensile strength are available.
This method relies on the input cycles being:
* 0: in the elastic regime
* 1: for the first 1/2 of the remaining t... | e59116b10c34a9106b2b004613eaf4814f6333a6 | 626,734 |
def get_set_vertices_u_0(g_or_n):
"""Get indexes for the belief vector:"
0: capture
1,...n: vertices"""
if isinstance(g_or_n, int):
n = g_or_n
else:
n = len(g_or_n.vs)
V = list(range(1, n + 1))
V_ext = [0] + V
return V_ext | a9e31c1b7bcd60a77bb5befebd8976507915b108 | 626,736 |
def instance_dist(novel, word):
"""
Takes in a particular word, returns a list of distances between each instance of that word in the novel.
>>> from gender_novels import novel
>>> summary = "Hester was her convicted of adultery. "
>>> summary += "which made her very sad, and then her Arthur was als... | bcc6f92754567fdfeee7e7005857919c5e62bc2e | 626,739 |
def define_constants_for_fixed_srht_with_momentum(n, d, m):
"""
As defined in Jonathan Lacotte, Mert Pilanci, Optimal Randomized First-Order Methods for Least-Squares Problems (https://arxiv.org/abs/2002.09488)
Args:
n: Number of rows of data matrix
d: Number of columns of data matrix
... | 984192fb26a475900c08e9beab26a8661290ed2b | 626,741 |
def _get_action_profile(x, indptr):
"""
Obtain a tuple of mixed actions from a flattened action profile.
Parameters
----------
x : array_like(float, ndim=1)
Array of flattened mixed action profile of length equal to n_0 +
... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains play... | ffeb0a38f07d16079723beddf73ce090135af43c | 626,742 |
def fromSI(value: str) -> float:
"""converts from SI unit values to metric
Args:
value (str): a value in SI units, e.g. 1.3u
Returns:
float: the value in metric units.
"""
return float(value.replace("u", "e-6")) | 1b63ec8453deace7583d9919519de4feda44e0dd | 626,744 |
def _get_jsonld_property(jsonld, property, default=None):
"""Return property value from expanded JSON-LD data."""
value = jsonld.get(property)
if not value:
return default
if isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict) and "@value" in value[0]:
value = valu... | 5cda221bc065b53411f460ab226d99200c68a148 | 626,746 |
def dfa_word_acceptance(dfa: dict, word: list) -> bool:
""" Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict df... | fdc85a810d79c715c6fbeffc65248495ea551ffb | 626,747 |
def avseth_gassmann(ksat1, kf1, kf2, kmin, phi):
"""
Applies the Gassmann equation.
Args:
ksat1 (float): Ksat1.
kf1 (float): Kfluid1.
kf2 (float): Kfluid2.
kmin (float): Kmineral.
phi (float): Porosity.
Returns:
float: Ksat2.
"""
s = ksat1 / (km... | 738f2c91517b5a225c5d397c2b983f96cedb6a7c | 626,748 |
import re
def snakify(name: str, *, sep: str = '_',
_re_upper=re.compile(r'([A-Z])')) -> str:
"""Lowercase ``name`` adding ``sep`` before in-word-uppercase letters.
>>> snakify('CamelCase')
'camel_case'
"""
return (name[:1] + _re_upper.sub(rf'{sep}\1', name[1:])).lower() | 72adb24ad471e89828c1170a3afb3f649fb4288f | 626,749 |
def model_values(model):
"""Get the values out of a Z3 model.
"""
return {
d.name(): model[d]
for d in model.decls()
} | 7a4d70e73d34e670c47b8a16d024165746b14e8f | 626,752 |
def add_suffix(string,suffix):
"""if suffix, appends suffix to string with underscore. otherwise return it unchanged."""
if suffix is None:
return string
else:
return "{}_{}".format(string, suffix) | d0c1818f4c2b987c378ed81ac0539d75926894f3 | 626,753 |
import torch
def _collate_fn(batch):
"""
Custom collate function to manually specify how samples are batched from the DataLoader.
See https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#iterating-through-the-dataset
for an introduction.
In particular, the batch represents a collection of
... | 1364fb58d4963b42821c72e49d8790ada8babf7e | 626,754 |
def findTerm(ont,name):
"""
Searches an ontology for a specific term name and returns the first hit
Args:
ont (pronto Ontology): Ontology to search
name (str): Search query
Returns:
pronto Ontology: Term that matched name or None if not found
"""
for term in ont:
if term.name == name:
return term
re... | 7cbf24cfb111cca31d89381d932df5dd4d0ce1d1 | 626,755 |
from typing import Union
from pathlib import Path
def find_file(path="~", file="LabRecorderCLI.exe") -> Union[Path, None]:
"""find a file recursively
args
----
path:str
the root folder
file:str
the file name
returns
-------
filepath: Union[Path, None]
... | 73f8ef7ca9ba74ea688f98cb46ef33093c39c5dd | 626,756 |
def make_strategy_id(strategy):
"""
Return a string that will identify a strategy - just concatenate
the numbers of transfers per gameweek.
"""
strat_id = ",".join([str(nt) for nt in strategy[0].values()])
return strat_id | 50dea9aa8724a974ba22790e191c88d9eb6e0bae | 626,760 |
import torch
def focal_loss(input,
target,
reduction='mean',
beta=0.5,
gamma=2.,
eps=1e-7,
**kwargs):
"""
Focal loss, see arXiv:1708.02002
input: [B, 1, H, W] tensor that contains predictions to compare
target: [B, 1, H,... | d698fffeb252ae8c2f4a43a45094ac75532f3ce2 | 626,763 |
import torch
def create_xyz_tensor(sl):
"""
Return an 32 x 32 x 32 x 3 tensor where each len 3 inner tensor is
the xyz coordinates of that position
"""
incr_t = torch.arange(sl, dtype=torch.float64)
z = incr_t.expand(sl, sl, sl).unsqueeze(3)
y = incr_t.unsqueeze(1).expand(sl, sl, sl).unsqu... | f410c0cfa1fd121373ec43235e7a6700bec3ac08 | 626,770 |
def _build_rtw88_config(rtw88_config):
"""Builds the wifi configuration for the rtw88 driver.
Args:
rtw88_config: Rtw88Config config.
Returns:
wifi configuration for the rtw88 driver.
"""
result = {}
def power_chain(power):
return {
'limit-2g': power.limit_2g,
'limit-5g-1': po... | 10836cbe85003c5b51d5deffbf1cb862525ed67e | 626,773 |
import re
def get_process_id_and_name(header):
"""Get process id from header."""
m_process_num = re.match(r'(.*)[(]\s*(\d+)[)]', header)
if not m_process_num:
return None
return int(m_process_num.group(2)), m_process_num.group(1).strip() | 2d7412de3865e1a36ea1ff013193a5f2951fc7ab | 626,776 |
def get_n_control_ts(model):
"""Get number of timesteps in the model's control variable"""
return len(model.wells.event_dates) | 24b7a3d5ec3b18b4f9025629889a1a3b2ab33492 | 626,777 |
def allow(whitelist):
"""
Decorates a handler to filter all except a whitelist of commands
The decorated handler will only be called if message.command is in the
whitelist:
@allow(['A', 'B'])
def handle_only_a_and_b(client, message):
pass
Single-item whitelists may be ... | c193dddb1a530132d69a8b7d378751430aec0198 | 626,779 |
def stats_file_values(pop_size, gene_number, generation_number, diversity, viability_ratios, viability_ratios_db):
"""Return a dict usable with csv.DictWriter for stats file"""
values = {
'popsize': pop_size,
'genenumber': gene_number,
'generationnumber':generation_number,
... | fa945943fba8368e2ba775eaa629880bf32d483f | 626,785 |
def selection_sort_counting(A):
"""
Instrumented Selection Sort to return #swaps, #compares.
"""
N = len(A)
num_swap = num_compare = 0
for i in range(N - 1):
min_index = i
for j in range(i + 1, N):
num_compare += 1
if A[j] < A[min_index]:
m... | 783aa83086c38deefd503ddd6767bd759e298721 | 626,787 |
def to_fahrenheit(temp):
"""
Converts a temperature in celsius to fahrenheit.
"""
return (temp * 1.8) + 32 | 11e06263f472e79096656373cf190fc86ac1acf9 | 626,789 |
import re
def regression_test_almost_match_file_names(old_fname, new_fname):
"""Checks whether the two file names match (if the files match up to name_i*.ext, it counts
as if they match)
"""
if old_fname == new_fname:
return True
if '_i' in old_fname:
if re.sub('_i[0-9]*', '', old... | 00452a0929552c9ef1da802780a2ec31f61834cc | 626,791 |
def site_client(client, site):
"""Returns a client tied to a specific site."""
client.config['default_site'] = site['id']
client.default_site = site['id']
return client | 6e879a5011fb5b2ed9eb917392e3c22b20e4a6bc | 626,795 |
def time_frog_jumps(other_side_position: int, leaf_positions: list) -> int:
"""
Returns the earliest time that a frog can jump to the other side of the river.
Uses a Set to store unique values from leaf_positions[].
When the size equals to other_side_position, means the leaves have covered all position... | 39f0d52bfe821a3b46380db4b1459fbc06968a11 | 626,801 |
from typing import Tuple
def calc_pad_value(src_value: int,
dst_value: int) -> Tuple[int, int]:
"""
Calculate a padding values for a pair of source and destination numbers.
Parameters:
----------
src_value : int
Source number.
dst_value : int
Destination num... | 6231eae061c3a534f0b2fe4a313987dc3d4eed98 | 626,808 |
import re
def parse_line(line):
""" parse model.js line-by-line using voodoo-regexp:
'{title: "Bungeejumper", url: "modellen/Bungeejumper.xml"},\n'
=> ["Bungeejumper", "modellen/Bungeejumper.xml"]
[\"|'] --> match " or '
(.[^'|\"]*) --> group: match anything except " or '
[\"|'] ... | b28ca8d4c9622c54d11970b6c407b8d07f37b8ec | 626,815 |
async def readyz():
"""
Readyz endpoint.
"""
return {"status": "ready"} | 7f089fc63ee74ce8eec872d80eeb5129fc267272 | 626,816 |
def IoU(boxA, boxB):
"""
Computes the Intersection over Union (IoU) metric, given
two bounding boxes.
Input:
"boxA": bounding box A
"boxB": bounding box B
Output:
"score": IoU score
"""
# Compute the intersection points of the two BBs
xLeft = max(boxA[0], boxB[0])
yLeft ... | b3e026dc40f329e2013102127e0cddcb5832b697 | 626,817 |
def is_transition(allele1, allele2):
"""Is the pair of single bp alleles a transition?
Args:
allele1: A string of the first allele, must be 1 bp in length.
allele2: A string of the second allele, must be 1 bp in length.
Returns:
True if allele1/allele2 are a transition SNP.
Raises:
ValueError... | 0fe36568156029fef42808e78f8bec8fcb116b7e | 626,819 |
def example_choices(field, arg=3):
"""
Returns a number (default: 3) of example choices for a ChoiceFiled (useful for CSV import forms).
"""
examples = []
if hasattr(field, 'queryset'):
choices = [(obj.pk, getattr(obj, field.to_field_name)) for obj in field.queryset[:arg + 1]]
else:
... | 5206254abc339b8941596ccb29538cd4fcc1e8a1 | 626,824 |
def f1(x):
"""
A simple quadratic function.
"""
y = x**2 - 3.*x + 5.
return y | fa29c665b314ae2731cd395148ee3dffc3423572 | 626,826 |
def arithmetic_sum_n(a_1, d, n):
"""Calculate the sum of an arithmetic series.
Parameters:
a_1 The first element of the series
d The difference between elements
n The number of elements in the series to sum
Return:
The sum of n numbers in the arithmetic seri... | 3a391886a0ecab60b35632c1bf429131d3f08373 | 626,827 |
def apply_text_replacements(path, text, text_replacements):
"""
If path appears in text_replacements, replace each old value with new value in order.
"""
if path in text_replacements:
for old_val, new_val in text_replacements[path]:
text = text.replace(old_val, new_val)
retur... | 1618f8ea395bd930c448e2ce6524762d1df1f111 | 626,828 |
import re
def humanish(remote_url):
"""Get the humanish part of a remote git url
equivalent of the following multiexpression sed search and replace:
sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g'
https://stackoverflow.com/questions/13839879/how-to-determine-the-humanish-part-of-a-git-repos... | bc12ee3b2a14dd4e5f3b6f9aeed5fab32f1ad804 | 626,830 |
def is_shared_to(video: dict) -> bool:
"""
Checks if a video was shared to an account.
Returns True if it was shared to another account, False otherwise.
"""
shared = video.get('sharing')
if shared and shared.get('to_external_acct'):
return True
return False | ba2a5799bfe32ee9d1ea67c238fe41cdbf550778 | 626,832 |
def input_data_task_id(conf):
# type: (dict) -> str
"""Retrieve input data task id
:param dict conf: configuration object
:rtype: str
:return: task id
"""
return conf['task_id'] | da0dc2cc199d39369d160beecc403b772e0ed17c | 626,835 |
from typing import Any
from typing import List
def listify(collection: Any) -> List:
"""
Takes a given collection and returns a list of the elements, handling strings correctly
Parameters
----------
collection: tuple, set, str
Any type of collection or string
Returns
-------
... | c17c852a6b2a767a2009a2535fc5bfd53ce3b87f | 626,836 |
def normalize_strides(
strides
):
"""Normalize strides of the same format.
Args:
strides: An integer or pair of integers.
Returns:
A pair of integers.
Raises:
ValueError: Input strides is neither an integer nor a pair of integers.
"""
if isinstance(strides, (list, tuple)) and len(strides)... | 447bd01f69fc0a0044741e3d28f6b6d298067459 | 626,839 |
def realign_shifted_streams(tokens, durations, F0s, shifts):
"""
Durations are shifted by 1, F0 by 2
>>> tokens = ["<s>", "t1", "t2", "t3", "</s>", "x", "x"]
>>> durations = ["<0>", "<0>", "d1", "d2", "d3", "<0>", "x"]
>>> F0s = ["<0>", "<0>", "<0>", "f1", "f2", "f3", "<0>"]
>>> shifts = [1,... | e29675e36fd68a16c46f351874ef4002ffde81d4 | 626,843 |
def ssv(words):
"""Convert a words list into space separated values"""
line = ""
for w in words:
if len(line) != 0:
line += ' '
line += w
return line | fa852de3005140a1cfc8d4379fb0c202718e9a3d | 626,845 |
def get_region_filename(region, subregion):
"""Returns the filename needed to download/manage PBF files.
Parameters
----------------------
region : str
subregion : str
Returns
----------------------
filename : str
"""
base_name = '{}-latest.osm.pbf'
if subregion is None:
... | a55c42aa2a5ac572ad06748e4104d54966250dcb | 626,846 |
from typing import Dict
from typing import Any
def is_aromatic(n: str, d: Dict[str, Any]) -> bool:
"""Adds indicator of aromaticity of the atom to the node data.
:param n: Node name, this is unused and only included for compatibility with the other functions.
:type n: str
:param d: Node data
:typ... | 005d65ec07233379df4ebd5546ebeb7df8c052b7 | 626,847 |
from typing import OrderedDict
def get_data_types(data):
"""
returns a dictionary with column names and their respective data types
:param pandas.DataFrame data: a dataframe
:rtype: dict[str,str]
"""
dtypes = data.dtypes
return OrderedDict(zip(dtypes.index, dtypes.astype(str))) | 5dcaf1ca6fde0d1011210e60913ee7052dfb58d4 | 626,848 |
def _bool_to_str(val):
"""
Convert Python bool to string 'true' or 'false'.
Note we cannot use the standard conversion to str, as Python uses 'True'
and 'False', whereas C++ uses 'true' and 'false'.
"""
return 'true' if val else 'false' | b4c8ff69f6be5bac17ddd4735d44e823bf748e99 | 626,851 |
import time
def timestamp2date(timestamp):
"""
时间戳转换为日期
Parameters
----------
timestamp: int or str
用户账号
Returns
-------
datetime:
转换好的日期:年-月-日 时:分:秒
"""
time_array = time.localtime(int(timestamp))
datetime = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
... | 72c6465ba5886e32a778dac3f83ea057d645cf7c | 626,858 |
def __data_to_string(write_data):
""" Converts data array to string."""
return "".join(["{:08b}".format(data) for data in write_data]) | 04e697701494da6541193d059ce620551959a059 | 626,861 |
import codecs
def open_enc(fn, utf16):
"""
Open a file for reading with either the standard built-in open() or the
open in the codecs module for reading UTF-16 encoded files.
:param fn: Name of the file to open
:param utf16: Boolean flag to specify a UTF-16 file
"""
if utf16:
retu... | 3b0bf61e16a3cb5c46bc47fdcae761cce13940d1 | 626,866 |
from pathlib import Path
def account_exists(account_id='jodel_account'):
"""Checks whether an account has already been created."""
if Path('./' + account_id + '.pkl').is_file():
return True
else:
return False | d5163967d6af2809204f2dce7d8bd3cc492219e9 | 626,868 |
import zlib
def crc32File(filename, skip=0):
"""Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file.
"""
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xfffffff... | f591971106b4b54376e8bc971c12bb2fd2040fda | 626,872 |
def sanitize_package_name(name):
""" Sanitize package name
Args:
name (str): package name.
Returns:
str: sanitized package name.
"""
return name.replace("+", "plus").strip(" ") | 02d94441d77343e3e7ce5c676a091c191152c22e | 626,876 |
def json_get(item, path, default=None):
"""
Return the path of the field in a dict.
Arguments:
item (dict): The object where we want to put a field.
path (unicode): The path separated with dots to the field.
default: default value if path not found.
Return:
The value.
... | 0860fe65e5a6802d3f623c5bbea1543d2a98b0ec | 626,877 |
from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
... | 0002b28f2b4722c7554487db737327e333fbde54 | 626,879 |
def lng180(lng):
"""Returns a longitude in degrees between {-180, 180] given a longitude in degrees."""
newlng = float(lng)
if lng <= -180:
return lng + 360
if newlng > 180:
return lng - 360
return lng | 7ca14cc485cdb7c56b622ab38398c0e559ce4532 | 626,882 |
from datetime import datetime
def _calc_elapsed(start, fmt=True):
"""Returns hours, minutes, seconds;
formats to {H}h, {m} min., {s}s if fmt"""
elapsed = datetime.now() - start
hours, remainder = divmod(elapsed.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
if fmt:
... | 4a80656b6d71d2c7ed22fb80504f8a076ef43bdd | 626,886 |
def divide_by(value, arg):
"""
Returns the result of the division of value with arg.
"""
result = 0
try:
result = value / arg
except:
# error in division
pass
return result | f1ff4eee6f6392c9bb9ec8b3fd4fe5ec295c048f | 626,888 |
def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (nn.Variable): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method use... | 6c1b721dd8e4721a4159de8b56ef753ea65962db | 626,890 |
import torch
def nms(boxes, scores, overlap=0.7):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
scores: (N) FloatTensor
boxes: (N, 4) FloatTensor
overlap: (float) The overlap thresh for suppressing unn... | 91ad89a607d52b5a51398b882c9e83bf5cccea73 | 626,897 |
import inspect
def is_generator(obj):
"""
Return True if ``obj`` is a generator
"""
return inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) | c0b7f570351d2af9d3e70bdb0eff73245a9c599b | 626,898 |
import codecs
def decode_text_part(part):
"""Extract the payload from a text/plain mime part as a unicode string"""
txt = part.get_payload(decode=True)
charset = part.get_content_charset('latin1')
# Make sure the charset is supported and fallback to 'ascii' if not
try:
codecs.lookup(charse... | a8a6ebf795eec0acef9d6d73b0d3491b9e418dbf | 626,904 |
def calcite(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... | 7c96972d8a71118fd3262c2f7cc0d5d741e6f014 | 626,905 |
import re
def _without_nbt_style(s: str) -> str:
"""
Given a full string with NBT styling, return the string without coloring
and recomb symbols.
:param s: The given string.
:return: The given string without NBT styling.
"""
return re.sub('§ka|§.', '', s).strip() | bc6a5c24847f43038bcf7b8de84da4330df4b0eb | 626,908 |
import random
def randbytes(length: int) -> bytes:
"""
Generate a random bytes object.
:param length: Length of the random bytes object.
:return: Random bytes object.
"""
return bytes(random.getrandbits(8) for _ in range(length)) | 928f60010dc294dfdd030e5a8c9796f05f4ba1d7 | 626,909 |
def MoveStr2List(mv: str) -> list:
"""
param:
mv: str [x_src, y_src, x_dst, y_dst]
return:
mv_list: List-> [int: x_src, y_src, x_dst, y_dst]
"""
mv_list = []
if mv != " ":
mv_list = list(map(int, mv[1:-1].split(",")))
return mv_list | dedb0d2b044c5e1dd990d76fbf4986661408ebf2 | 626,913 |
from pathlib import Path
def sorted_glob(p: Path, pattern="*"):
"""
return sorted filenames for matched files.
"""
names = [x.name for x in p.glob(pattern)]
names.sort()
return names | 4b36944a8cd2097eb1bdc26164c6194e058c7e87 | 626,916 |
import torch
def generate_linear_data(n=1000):
"""
Generates an example dataset that can be seperated linearly
Output:
inputs : nx2 dimension FloatTensor
targets : nx1 dimension LongTensor with range [0,1]
"""
torch.manual_seed(123)
inputs = torch.rand(n,2)
targets = torch.s... | c3cc6167afc75b848f5e9c416609daf3854a0ff5 | 626,918 |
def nonstandard(cls):
"""
Testcase decorator that marks the test as being non-standard.
These tests are not automatically added to the "standard" group.
"""
cls._nonstandard = True
return cls | e444b636cc182cee2720bb2c301b23c25e2f5ed9 | 626,920 |
import torch
def quadratic_bezier(params: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""Evaluate a batch of quadratic bezier curves at different points.
Args:
params: torch.Tensor of size [batch, 3, D]. Each batch item is interpreted as four points corresponding to
the start point, the fir... | 890e888d71695a539c51cc704302cc42f699c56c | 626,926 |
def OR_AND_product_fuzzy(Z_n, U_d):
"""
Compute probability of emitting a zero for fuzzy vectors under OR-AND logic.
"""
out = 1
for l in range(Z_n.shape[0]):
out *= 1 - Z_n[l] * U_d[l]
return 1 - out | adfa85c81589566664b658dd6b5ac2cdef4294db | 626,928 |
def get_log_params(prog: str, cfg: dict, def_logfile: str) -> tuple:
"""Get the log file, level and size for the given program from config
The logfile is supposed to be defined by a variable called logfile
within the hierarchy of the config dictionary. Thus, the poller log file
will be {'poller': {'log... | 893740ac086bd0eaede6eaa649646379f7b234bb | 626,929 |
def has_view_restrictions(page):
"""Returns True if the page has view restrictions set up, False
otherwise."""
return page.view_restrictions.count() > 0 | 97780a4091c1461bdbeabb04f2fd8cd5a28b18ae | 626,932 |
def drop_prefix(s, pattern):
"""
Remove prefix pattern of a string.
:param s: string
:param pattern: string pattern
"""
if s.startswith(pattern):
return s[len(pattern):]
return s | ea8ceb13089eb907f550174d82118e1e9c32bddf | 626,935 |
def getAPNTopicFromX509(x509):
"""
Given an L{X509} certificate, extract the UID value portion of the
subject, which in this context is used for the associated APN topic.
@param x509: the certificate
@type x509: L{X509}
@return: C{str} topic, or empty string if value is not found
"""
s... | ad6b6922727c73aea7240a931bc2ed783a649680 | 626,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.