content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def strLength(str,min,max):
"""
判读数据长度
"""
return len(str)>=min and len(str)<=max | 1e99f7643326c97435e01cc337b00574b40019bf | 626,016 |
def find_versions(dependencies, heuristics):
"""
Try to find version information by calling a series of functions in turn.
*dependencies*:
a list of Dependency objects.
*heuristics*:
a list of functions that accept a component as the single
argument and return a version number o... | 71784a084230d6d24e38cbca0537515d377997e1 | 626,018 |
def preprocess_input(cin: str):
"""
Maps user input into matrix indexes
Parameters
----------
cin : str
For example F5
Returns
-------
If the case was F5, it will return 4, 5
"""
letter = cin[0]
number = int(cin[1])
d = {'A': 0, 'B': 1, 'C': 2,
'D': 3,... | 54a85b79b8b1bb49d740d78a0a3894c203c82b6a | 626,019 |
from typing import Iterable
from typing import Any
from typing import Iterator
import itertools
def flatten(iterables: Iterable[Iterable[Any]]) -> Iterator[Any]:
"""Flatten an iterable of iterables into one consecutive iterator.
Only flattens one level (i.e., items which are themselves iterable
will be u... | 0e7c562314b726ab0f5379ce64584c5bca00db1c | 626,020 |
def subtract_numbers_from_lists(list1, list2):
"""Subtracts two integer lists"""
temp_list = []
for i in range(len(list1)):
temp_num = list1[i] - list2[i]
if temp_num < 1:
temp_num += 26
temp_list.append(temp_num)
return temp_list | ec8daa596136024f0732a6b60b1e0c9b3b618987 | 626,021 |
def hash_function_2(key):
"""
This is a hash function that can be used for the hashmap.
"""
hash = 0
index = 0
for i in key:
hash = hash + (index + 1) * ord(i)
index = index + 1
return hash | 73a61d6b4a5dd32180dfea5f780bd15cdf7ddefa | 626,022 |
def dlist(src):
"""
Convert dicts with numeric keys to lists
:param src: {"a": {"b": {"0":"red", "1":"blue"}, "c": "foo"}}
:return: {"a": {"b": ["red", "blue"], "c": "foo"}}
"""
if isinstance(src, dict):
for k in src:
src[k] = dlist(src[k])
if set(src) == set([str(k)... | f51413a9507c8b4c51c077999ccace57e2976493 | 626,023 |
def _list2str(array):
"""
Join a list with spaces between elements.
"""
return ' '.join(str(a) for a in array) | 722ece18cb869a6801761c7550e5ecc5c6d4b19a | 626,024 |
import os
def parse_list_file(list_file):
"""
Load the list file which contains 'dir/filename' format on each line
We sort these into one set per directory, the directory name then becomes the supervised
training label we want the model to learn.
"""
data_root = os.path.dirname(list_file)
... | 6d03ae812857251d1da2a71432085e6d6be646be | 626,025 |
def check_if_tuple_exists(cursor, table_name, kennziffer, year):
"""
Checks if the tuple is already in te DB.
:param cursor: for the db to check
:param table_name: name of the table to check in
:param kennziffer: this value is checked
:param year: this value is checked
:return: True if the t... | ae6bf3c4dab0e98ef01c0e1fcee7de351f66b0cd | 626,026 |
import math
def get_square_subplot_grid(n):
"""Get a (h, w) square arrangement for any number of subplots."""
side = math.ceil(n ** .5)
return side, side | 70d4c80758326bb15d5c4141713afdf3feb1c576 | 626,027 |
import hashlib
def hash_file(path):
"""Hashes a file specified by the path given and returns the hex digest."""
# If the hashing function changes, this may invalidate lots of cached data.
# Don't change it lightly.
h = hashlib.sha1()
with open(path, 'rb') as fh:
while True:
d... | 6191518a89e5263c4e944f8c6c17fb1193dac1cd | 626,028 |
def whitelist(d, fields):
"""Whitelists a dictionary by keeping ONLY the selected `fields`.
Non-destructive (creates and returns a new dict)."""
ret = type(d)()
for f in fields:
if f in d:
ret[f] = d[f]
return ret | 833d403dd228da5ee00a3741ab77ecb4ad52ef88 | 626,029 |
import math
def normal_round_float(x: float, dp: int = 0) -> float:
"""
Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 ->... | 0f3e2f0791917295eaf9ec1c3efc926cb66a2564 | 626,030 |
import tabulate
def format_summary(s):
"""
Summary has form {method: {dataset: {"tracking_error": ..., "feature_age": ...}}}
Prints summary in form:
| Dataset1 | Dataset 2 ....
--------------------------------------------------------
Method1 | age11 ...
...
| Datase... | 25dcd36b9847d6766cfdd6b966e7e9d4dec44a1f | 626,031 |
def getCentroids(proptable):
"""
Returns labeled object centroids and labels in a dictionary.
Parameters
----------
proptable : pd.DataFrame
labeled object properties with centroid & label columns
Returns
-------
props_dict : dict
Dictionary with 'centroids' and 'l... | 46d6ab7a1350abc24d2745e578441b712e71101b | 626,032 |
import re
def remove_tags(html):
"""
Function will clean html by removing html tags leaving behind plaintext.
Args:
html (string): The html to be cleaned
Returns:
(string): The plaintext
"""
# return BeautifulSoup(html, "lxml").text
html = re.sub("<[^<]+?>", "", html)
h... | 307b9db48b54abdcd0380a427b18c77d275b206d | 626,033 |
import torch
def load_melgan_torch(model_path='', device=None):
"""
用torch.load直接导入模型文件,不需要导入模型代码。
"""
global _model
global _denoiser
if device is None:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
_model = torch.load(model_path, map_location=device)
return _model | 87af0f6e8dc37bcb9f57797b944811738a0c7e57 | 626,035 |
import os
def is_azureml_mpirun() -> bool:
"""Check if run set up by azureml using OpenMPI image.
When running MPIRUN with OpenMPI images, AzureML sets a specific combination
of environment variables which we check for here, specifically::
OMPI_COMM_WORLD_RANK # the rank of the process
... | 92f3ec61eaf97795a1a1fc0947319bf0cc17e883 | 626,036 |
def inter_score_ds(graph, communities, partition, in_edges_analysis=False, negative_anomalies=False):
"""The name stands for Directed Signed InterScore. Ranks elements according to their number of
inter-community out/in edges compared to their community mean. This algorithm can be used to
identify users ope... | 37bf625a6d6a9beeb1501eff35757749ec147e3d | 626,037 |
def all(f, iterable) -> bool:
""" If all the conditions are True then return True, otherwise return False at the first failiure"""
for e in iterable:
if not f(e):
return False
return True | cb6b7d2d6b4a670012635c50c4c79b8ddacf124d | 626,039 |
def get_cve_id_from_vuln(vuln):
"""
Returns CVE ID from vulnerability document
When there is no CVE, returns "No-CVE" string
"""
return vuln.get('cve_id', "No-CVE") | a0f2162a02e18e0e322f706662de86bc654b3927 | 626,040 |
import os
def add_abspath(command):
"""Returns the absolute path to the command, if a path is specified at all.
Args:
command: Command to get the full path of. If it does not contain a "/", it's
considered to be in the PATH.
Returns:
The original string (if it doesn't contain a "/"), or the absolut... | 1791af5399958f85a4b129b70342ba5614d0ac8b | 626,041 |
def _flatten_nested_list(x):
"""
Flatten nested list
Argument
--------
x : list
nested list with different leveling of different objects
Returns
-------
flatten version of list
"""
out = []
for xi in x:
if type(xi) is list:
out += _flatten_nested... | 88bf948dbd97af26e73e6c2830a1b99ec335acc0 | 626,042 |
import click
def shell_print(text: str, color: str = "green"):
"""Shell Print"""
return click.secho(f"{ text }", fg=color, bold=True) | 2ae31705ce06b77ea7a72f6abdb4958d9fca6580 | 626,043 |
def is_spoiler(message_text: str, link: str) -> bool:
"""
Finds the given link in the message and tells if it's inside spoiler tag or not.
"""
link_pos = message_text.find(link)
spoiler_tags_count = message_text[:link_pos].count('||')
return spoiler_tags_count % 2 == 1 | 73a7502d5ade68fba9f330e3bfeffc694567e3cd | 626,044 |
def svm_predict(model, samples):
"""Returns the predictions"""
return model.predict(samples)[1].ravel() | 4b1c382a261ea27de5c88f33bb11cbc381769f6d | 626,045 |
def datetime_to_str(date, milliseconds=False):
"""datetime_to_str方法用于日期转字符串
Parameters
----------
date : datetime
日期
milliseconds: bool
是否保留毫秒
Returns
----------
"""
if milliseconds:
return date.isoformat(sep=' ', timespec='milliseconds')
else:
re... | 50b70d43fabd969921ad74c06fc66bf3f672b38f | 626,048 |
def u_func(h, c, par):
"""
Cobb-Douglas utility function for consumption and housing quality
Args:
h (float): housing quality and equal to housing price
c (float): other consumption
par: simplenamespace containing relevant parameters
phi (float): C-D weights
... | 4396740a793e0d37328bfc89ae9ea9f029b0e2d3 | 626,050 |
def median_of_3(
array: list, first_index: int, middle_index: int, last_index: int
) -> int:
"""
>>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
>>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1)
12
"""
if (array[first_index] > array[middle_inde... | 3de97a81e9d14b8cf8db1c7c1ab0e5cec3806d25 | 626,051 |
from datetime import datetime
def datetime_keep_yyyyMMdd(dt):
"""
由于万得取出来时间有会带一个0500的小尾巴
这个在处理数据时可能会导致问题,所以处理一下
:return:
"""
t = dt.timetuple()
return datetime(t.tm_year, t.tm_mon, t.tm_mday, 0, 0) | 0336a04932cd04520ba8ce46ecfc3fe4fc67f25f | 626,052 |
def get_package_name() -> str:
"""
Get name of the package.
"""
return __name__.split('.', 1)[0] | 7890a0cb7eb2a5f89317304ef318fde0a8e26942 | 626,053 |
import calendar
def nthday(nth, day, mdate):
"""Calculate the Nth day of the month"""
# Generate calendar
cal = calendar.monthcalendar(mdate.year, mdate.month)
# Get all the specified days
days = [week[day - 1] for week in cal]
# Remove any zeros (zeros indicate that week doesn't include that ... | 7a5afdab06e754f79a6e1c794863f9aea412dde4 | 626,054 |
import os
def rmdir_existing(dir_path):
""" Remove a directory in a path if it exists and returns true. If
directory doesn't exists returns false.
:param dir_path: The directory path
:return bool: True if directory exits
"""
if os.path.exists(dir_path):
os.rmdir(dir_path)
retu... | f52b0f057daffdea0331d1cb5128c681f6cac3b1 | 626,055 |
import sys
def _cmd(cmd_str):
"""creates a command string for sending out via sockets - this handles Python v2 vs v3"""
if sys.version >= '3.0':
return bytes(cmd_str, 'ascii')
return cmd_str | 2e27a4ffabb38e5773013c5fd89756a96638489d | 626,056 |
def getValues(params):
"""Extracts the attribute data
Parameters:
params (dict) Dictionary (node_attribute: value)
Returns:
(tuple) Tuple of the node attributes
"""
path = params.get("path")
name = params.get("name")
order = params.get("order")
shape = params.get... | d9131e720b4316bda9be19a0611e736b2bb7504b | 626,057 |
from typing import List
def quick_sort(collection: List, reverse=False) -> List:
"""A pure Python implementation of quick sort algorithm.
:param collection: a mutable collection of comparable items
:return: the same collection ordered by ascending"""
if len(collection) < 2:
return collection
pivo... | 2e72efee0f542ea67c824906b254d2d700a4b9ee | 626,058 |
from typing import Tuple
def precisionRecallF1(correct: int, extracted: int, groundTruth: int) -> Tuple[float, float, float]:
"""
Calculates metrices.
:param correct: Number of correct keywords.
:type correct: int
:param extracted: Number of extracted keywords.
:type extracted: int
:param... | e35b2bbeef22e3eeace40484544fc08dc528f13d | 626,059 |
def count_object(network, class_ids, scores, bounding_boxes, object_label, threshold=0.75):
"""
Counts objects of a given type that are predicted by the network.
:param network: object detection network
:type network: mx.gluon.nn.Block
:param class_ids: predicted object class indexes (e.g. 123)
... | 31dd31319a6d579d98929ec9a57892a560b058f3 | 626,060 |
def strike(text: str) -> str:
"""Make text to strike."""
return f'~{text}~' | 89f83b130e3650ef5f96355329f103ba4f609a46 | 626,061 |
import colorsys
def hls_to_rgb(hue, saturation, lightness):
"""Convert HSL back to RGB."""
t = colorsys.hls_to_rgb(hue, saturation, lightness)
return tuple(int(round(x * 255)) for x in t) | 5fe8cb1def731ab5fa00fbb4db7c1e853685febf | 626,062 |
def runCode(instructions, executed, current, acc, change):
"""Executes the given list of instructions.
Each instruction has an integer value to be used for its function, this
can be positive or negative.
Supported instructions:
* acc: adds its integer value to the accumulator value
* j... | da7e756b9688bd3f17511e9b877d3ba6f1dd118b | 626,063 |
def _check_download_type(img_url):
"""根据img_url分析是花瓣网图片还是堆糖网图片,特征:
#: 花瓣
https://hbimg.b0.upaiyun.com/ec4433d815c45742a4ec1d5b6810c4ce9fe2f4d86e636-SoEBVh
#: 堆糖
https://b-ssl.duitang.com/uploads/item/201904/26/20190426115802_dUaAA.jpeg
"""
if img_url:
if img_url.startswith("https://h... | 210008b0672830ef1326831cca52fbeec7087950 | 626,064 |
def _rgba_to_rgb(im):
"""
Drops the alpha channel in an RGB image.
"""
return im.convert("RGB") | b49916b826629e0be231dc5993c7563e4d94424d | 626,065 |
import yaml
import io
import sys
def load_config(config_file):
"""
load_config
===========
Method to load a the base config file for building recipes. The config file should be a yaml file
Parameters:
----------
1) config_file: (str) The file path to the config file for buliding recipes
... | 527559cadc564605b84b42f0a062ae81073687bf | 626,066 |
def get_lr(lr, total_epochs, steps_per_epoch, lr_step, gamma):
"""get_lr"""
lr_each_step = []
total_steps = steps_per_epoch * total_epochs
lr_step = [i * steps_per_epoch for i in lr_step]
for i in range(total_steps):
if i < lr_step[0]:
lr_each_step.append(lr)
elif i < lr... | 0ce017aa810e4104d0b0342143c38b3c3c4b5d9a | 626,067 |
def get_para_range(num, mag_num=2):
"""
Function:
Get the magnitude m of the input number
Take 1e^(m - 3) ~ 1e^(m + 3)
:param
num: float
mag_num: int
:return:
range list, [min, max]
refer:
python基础-python3-格式化浮点数方法-%e、%f、%g: https://www.cnblogs.com/sum... | 91bee41064650329c1c6c38787369a42bc645ef1 | 626,068 |
from typing import Callable
from typing import Optional
from typing import Tuple
from typing import Any
from typing import Union
import time
def combined_timeout(
func: Callable, timeout: Optional[float] = None
) -> Tuple[Any, Union[float, None]]:
"""Call func(timeout) and return reduced timeout for subsequen... | 5edf16e2288ac4536eb111e78b90639fc4b0f5bc | 626,069 |
def results_ready(results):
"""Check if some asynchronous results completed.
Given a list containing results of asynchronous computations
dispatched to a worker pool, verify if some of them are ready for
processing.
Parameters
----------
results : List[(multiprocessing.pool.AsyncResult, an... | e4cc4e3b23e71d380376d98166552d978ca1dba3 | 626,070 |
def plotwidth(figure, nrows, ncols):
"""Calculate the plot width of the figure, assuming square subplots.
Does this by calculating the height per plot and multiplying by number of
columns.
"""
height = figure.get_figheight() / nrows
return height * ncols | ab6bf687357717157c319cffe2918a7ac2775302 | 626,071 |
from typing import List
from typing import Callable
import os
import glob
import itertools
def get_source_list(filename: str, include_folders: List[str], find_function: Callable) -> List[str]:
"""
Recursively extract all (include) files used by the specified file.
Parameters
----------
filename :... | f1dc7daea5eb6a270a60922a6a4be0cc5585f16d | 626,072 |
def pf(i, n):
"""Calculates the present worth factor.
:param i: The interest rate.
:param n: The number of periods.
:return: The calculated factor.
"""
return (1 + i) ** -n | 1bf86e3fdbe5c2708caf2c51640603dcaf549b18 | 626,073 |
def first_translatable(store):
"""returns first translatable unit, skipping header if present"""
if store.units[0].isheader() and len(store.units) > 1:
return store.units[1]
else:
return store.units[0] | 483380882efe037e89098275cabf870f9302f61e | 626,074 |
def time_to_threshold_revs_query(user_id, project, args):
""" Obtain revisions to perform threshold computation """
return [] | 86ba9a188d43ab8b0d8e1026829dbaaf700b2d71 | 626,075 |
import torch
def batch_center_mask(img_size, num_pixels, batch_size):
"""Masks all the output except the num_pixels by num_pixels central square
of the image.
Parameters
----------
img_size : see single_random_mask
num_pixels : int
Should be even. If not even, num_pixels will be repl... | 978708db1c209ae0e3493d2e2d256e1f7f0a0b76 | 626,077 |
def check_date(date: str, text: str) -> bool:
""" Compares the date in the card with the specified date.
"""
return date == text[:len(date)] | 54ed8f29a87c5b000b790b14231a9a6107addc4e | 626,078 |
def left_pad(string, length, character=" "):
"""Left pad a `string` to `length` characters with `character`."""
if not isinstance(string, str):
string = str(string)
if not isinstance(character, str):
character = str(character)
return string.rjust(length, character) | 8b55c3527d7653b89cc1c55642c95d19e640f166 | 626,080 |
def distinct_records(query_res):
"""
Given a list of tuples from the result of a sqlalchemy join query returns
unique record info for the substrates, phosphosites and kinases in the query
result.
:param query_res: sqlalchemy join query result (list of tuples)
:return: three sets of unique subst... | b39600baa6762db34ee8953d71c39cb5093f1ba4 | 626,081 |
def is_not_closed(request):
"""Check if the request is open or a draft."""
return not request.is_closed | 191bbf232bc24f8e1eb936dea17fd29fc0e3d00c | 626,082 |
def get_default_value_for_field_from_model(model, field):
"""
Get default value, if any, for a specified field in a specified model.
"""
if not hasattr(model._meta, 'fields'):
return None
for f in model._meta.fields:
if field == f.name:
if hasattr(f.default, '__name__'):... | f71f0c3c7b2ba31d7871715aed855cf2384d8e65 | 626,083 |
def row_major_index (i, j, N):
"""Return the index within a matrix block."""
# Row-major storage.
return i*N+j | f8aeed11620da462446eb6cb61d6c0f448fb5f3e | 626,084 |
def _count_enabled_bits(hexstr: str) -> int:
"""Parse a raw value like f202 to number of bits enabled."""
if hexstr == '':
return 0
value_int = int(hexstr, 16)
enabled_bits_count = bin(value_int).count('1')
return enabled_bits_count | 79513d1562c398eb66a0112728bba6e656009f5a | 626,085 |
def compress_dna(text: str) -> int:
"""Compress a DNA string into a bit string
Arguments:
text {str} -- DNA string to compress
Returns:
int -- integer bit-string representing DNA
Example:
>>> compress_dna("ACGT")
283
"""
bit_string = 1
for nt in text... | 218cd554bd143a93905f406369dca14a8be61aa4 | 626,086 |
def get_quad_tag_parts(reftag:str):
"""
Return a 4-tuple given a tag
"""
# Split tag into parts
tag_parts = reftag.split("/")
if len(tag_parts) < 3 or len(tag_parts) > 4:
return None, None, None, None
tag_prefix = tag_parts[0]
tag_context_name = tag_parts[1]
tag_value_name... | 40d20c75625da3440484c707b6507964eca441df | 626,087 |
def convert_bool(s):
"""Convert pseudo-boolean string values into Python boolean.
If given argument is any of '1', 'enable', 'on', 't', 'true', 'y', or 'yes'
it is considered True, else False.
"""
return s in ('1', 'enable', 'on', 't', 'true', 'y', 'yes') | 4c3b15ac960a71861f33c99f2af5c415824f1108 | 626,088 |
def gain_cal(Tlna, Tf, R1, R2, R3, R4, R5, Tp, Fghz, TP4corr):
"""
Computes minical parameters from minical data
This uses the Stelreid/Klein calibration algorithm
Stelzried and Klein, Proc. IEEE, 82, 776 (1994) to
compute B, BC and CC, as well as Tnd.
The true gain is B ( BC*R + B*CC*R^2 )
@type Tlna... | cc5bc5ff40887f77c3eb3ffb27af7a6544bf89f8 | 626,089 |
from typing import List
from typing import Dict
def filter_output_columns(columns: List[str], output_schema: Dict[str, str]) -> List[str]:
""" Private function used to infer columns which are part of the output """
return [col for col in columns if col in output_schema.keys()] | 1e7ed1f741aef44b5f42e587107f10993cf02e4c | 626,090 |
def is_in_bounds(mat, roi):
"""Check if ROI is fully contained in the image.
Parameters
----------
mat : ndarray
An ndarray of ndim>=2.
roi : (int, int, int, int)
Region of interest (x, y, width, height) where (x, y) is the top-left
corner.
Returns
-------
bool
... | 987cb7669afb6d0ab1ef9d8fae4d6ea95a9bed8d | 626,091 |
from typing import Tuple
from typing import Callable
from typing import Optional
import inspect
def import_function(path: str) -> Tuple[Callable, Optional[type]]:
"""Import and evaluate a function. If the function is defined in a class,
evaluate the class additionally.
Args:
path (str): The path ... | a5acb81a98e723951c330a51553bdbf105affaf5 | 626,092 |
def split_datetime(dataframe):
""" Split the date-time feature of a dataset into date and hour
Parameters
----------
dataframe : dataframe, shape(n_samples, 64), the full dataset
Returns
-------
dataframe : the dataframe with the date-time feature split into... | e6d17cf2882e20b1d2632539f947348f1b386d56 | 626,093 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#use list index as the hash_table value and list item as hash_table key
hash_table = {}
for i, num in enumerate(nums):
if target - num in hash_table:
return hash_table[target... | 0dafda9f5aec64793e6b8b92bae46fdb1fd725a2 | 626,094 |
import time
def measure(stats, duration):
"""
Return the measured duration of one begin/end cycle of a TimeStats object
of a given intended duration. The runtime behavior may be that the actual
duration is larger than the intended duration, therefore we need to measure
the actual duration.
""... | b89899c9c36412c456a8f69d4c5cc57549dcb3bc | 626,095 |
def get_next_redirect_url(request, redirect_field_name="next"):
"""
Returns the next URL to redirect to, if it was explicitly passed
via the request.
"""
redirect_to = request.REQUEST.get(redirect_field_name)
# light security check -- make sure redirect_to isn't garabage.
if not redirect_to ... | 497f06684406353c6cd60cf394777a4ae6fad1ee | 626,096 |
import os
def check_wgs_file_exists(wgs_accession, dest_dir):
"""
Check if a WGS sequence file was copied in the correct location
param wgs_accession: A valid Whole Genome Shotgun accession
return: True if the file exists, False otherwise. Defaults to True
"""
wgs_prefix = wgs_accession[0:6... | 99c24f889731aa0148b1da8990d5b1a57ee3080a | 626,098 |
import requests
def get_versions_from_devpi(url):
"""
Get list of versions for package from devpi server.
:param url: package url
:type: str
:rtype: list
"""
response = requests.get(url, headers={'Accept': 'application/json'})
if not response.ok:
return []
payload = respo... | e3ead228648ad8ad5ed9ef54e86aa2674f88d8a3 | 626,099 |
import glob
def IsCoopPinball(file_name):
"""
Is this a cooperative pinball (i.e. has > 1 thread)?
Count the number of result files for the pinball. If there are more than
one, then it's a cooperative pinball.
This will probably have to be changed when PinPlay implements the
capability to g... | d71526c3b7bdf5c7dacfe61c0c46b03c4c002b71 | 626,100 |
def mock_invalid_postgres_config():
"""Mock invalid Postgres config."""
return {"username": "lime"} | fffcb9a8beca4352d8eec4dc5bd3a2a158f47295 | 626,101 |
def binary_search(listData, value):
"""inputs: sorted array, value
outputs: value if it is in the array, -1 otherwise
efficiency: O(log(n))
method:
Find mid value of array; return value if equal to given value.
Perform same procedure on portion of list before or after mid value,
depending on... | 2578255135dc7c682d9e2c147110d4cf957fda72 | 626,102 |
import time
def get_timestamp():
"""Return current timestamp"""
try:
return time.perf_counter_ns()
except AttributeError:
return (int)(time.time()*(1000000000)) | a90273d3ad2855220ae2f23d7e6071fd15b69e0f | 626,103 |
def card_sorting_dealer(dealer):
"""
sorting dealer's card (including sequence like Changing num to J, Q, k, A)
:param dealer: dealer's card
:return: dealer's card
"""
dealerlist = [[]] * len(dealer)
for i in range(len(dealer)):
dealerlist[i] = [dealer[i]["suit"], dealer[i]["rank"]]
... | 689fd0e31a6875fc7ae06cd5ea5e847f6a63e2ce | 626,104 |
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not ... | a9c77002ad8aededecde48726bf03a8722c076fc | 626,105 |
import numpy
def ring_index(this_array, inds):
""" Index an array as a ring
Takes a numpy array and indexes it as if it were a ring, for instance,
given a 10 element array, ring_index(arr, 0) == ring_index(arr, 10)
Arguments:
this_array: numpy array
inds: index or list of indices
... | a544d456bdbefda1d3cf1d7c0788b4606d2cfe04 | 626,107 |
def create_test_docs(count):
"""Produce some test documents."""
def doc(i):
return '{"name": "name", "_key": "%s", "is_public": true}' % i
return '\n'.join(doc(i) for i in range(0, count)) | 4393776f1f3998fb768026ee1fe75043b25628cf | 626,109 |
def get_xy(artist):
"""
Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections.
"""
xy = None
if hasattr(artist, 'get_offsets'):
xy = artist.get_offsets().T
el... | 2c62aba32febf4ec4156c2f60e6b320b5a198ee6 | 626,110 |
import os
def determine_redis_provider():
""" determine redis connection url
"""
return os.environ.get("REDIS_URL", None) or "redis://localhost:6379/0" | 3d69444e76755094a4fcdee5bd55b703a87e97ae | 626,111 |
def increase_by_one(liste, n):
"""
Parameters
----------
liste : list
n : int
Returns
-------
bool
True, if it can continue. False, if not.
"""
i = 1
liste[-i] += 1
while i <= len(liste) and liste[-i] == n:
liste[-i] = 0
i += 1
if (i == l... | 55018bc9e9a9f2534702a06610b4038f73943f34 | 626,112 |
import re
def has_uri(s: str, _re=re.compile(r"(https?|ftp|file)(://[-_.!~*\'()a-zA-Z0-9;/?:@&=+$,%#]+)")):
"""
>>> has_uri("hoge://fuga.com")
False
>>> has_uri("https://qiita.com/?hoge=fuga")
True
"""
return _re.search(s) is not None | 0177585dd7ce4f42e03b43603a795e6f466d5152 | 626,114 |
def class_name_to_function_name(name):
"""Convert a python class name in CamelCase to a lower case function_name with underscores."""
function_name = ""
for char_idx, char in enumerate(name):
if char == char.upper() and char_idx > 0 and name[char_idx - 1] == name[char_idx - 1].lower():
f... | 64bc6303053821c4778a6d0f9205dc735e1fc334 | 626,115 |
import json
import os
def json_loads(content):
"""
Loads a JSON string into a dictionary.
If the string is not a valid json, it will be part
of the raised exception.
:param content: the string to load
"""
try:
return json.loads(content)
except ValueError as e:
raise... | 45a3c83473cd8ccb80955cbf58ffc2f71b5ab868 | 626,116 |
import torch
def center_size(boxes):
""" Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.ca... | 4ee92c5bb3985bd653c5ee3d855e2cc0c93c5468 | 626,117 |
def pier_flip_astrometry(header_in):
"""Adjust FITS astrometry CD* keywords to emulate a pier flip (rotate FOV 180 deg)
header_in : input FITS header
return value : copy of header_in with CD* keywords adjusted"""
header = header_in.copy()
header['CDELT1'] *= -1
header['CDELT2'] *= -1
header... | 8c02f25ff86a6df1066a6fe0f9da1c925d99eb14 | 626,118 |
def screenSizer(self, posx, posy, width, height, app):
"""func to get size of screen and scale window accordingly"""
sizefactor = round(app.primaryScreen().size().height()*0.001) # factor for scaling window, depending on height
posx *= sizefactor
posy *= sizefactor
width *= sizefactor
... | 488bf2a799bbd0300ff419207912169e73b12e60 | 626,120 |
def _trace_mm(x, y):
"""
Computes ``trace(x.T @ y)``.
"""
assert len(x.shape) >= 2
assert len(y.shape) >= 2
return (x * y).sum((-1, -2)) | ef6abd1bab214c1adc7be7683e822c7fd1fb1c8c | 626,121 |
from bs4 import BeautifulSoup
def parse_xml_response(response):
"""Parses XML response to Python dict
Parameters
----------
response : str
XML string response from Regon API operation
Returns
-------
dict
XML data converted to dict.
Raises
------
TypeError
... | fe46fc432559e542196d9898e7ba37d36694cebf | 626,122 |
import os
def ext_path(id, ext, dir='.'):
"""Generate a path for a given local ID and extension"""
return os.path.join(dir,id) + '.' + ext | 5dd8cc8b72eaa76811d99c0a3da8a43d2e7bc7e5 | 626,123 |
def find_divisors_v1(n):
"""Finds all divisors for a given number 'n' different than that number."""
if n == 1:
return [1]
return [x for x in range(1, n) if n%x == 0] | 8ac88a66b90e9c85a6d8c341f25c03ae8fefed29 | 626,125 |
import os
def temp_folder():
"""Get the path to the temp folder"""
return os.getenv('TMPDIR', os.path.expanduser('~/tmp')) | 935d5668695345e155170c8a14723eefa0580cb7 | 626,126 |
def centred_covariance(set1, set2):
"""
set1: numpy.matrix
set2:numpy.matrix
"""
return set1.transpose()*set2 | 35baf3e256db5e340ec4254936eea3dfbc1611d1 | 626,127 |
from math import radians, cos, sin, asin, sqrt
def haversine(point1, point2):
"""
Рассчет расстояния (в км) между двумя географическими точками
:param point1: координаты 1ой точки
:param point2: координаты 2ой точки
:return: double - расстояние между точками
"""
lat1, lon1 = point1
lat... | 3ceef8f89be1c32ba4ff3f2d629d551f9f6230f6 | 626,128 |
import os
def lock_file(lock_path: str, session_id: str) -> bool:
""" Creates a file if it does not exist.
"""
try:
lck_fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.write(lck_fd, session_id.encode())
os.close(lck_fd)
return True
except FileExistsErro... | 8a5921c3bdaad54ccef48552f1fae0c6e4b3967d | 626,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.