content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def check_for_solve(grid):
""" checks if grid is full / filled"""
for x in range(9):
for y in range(9):
if grid[x][y] == 0:
return False
return True | 5fc4a8e7a2efaa016065fc0736aa5bdb7d4c92f8 | 6,299 |
import copy
def _normalize_annotation(annotation, tag_index):
"""
Normalize the annotation anchorStart and anchorEnd,
in the sense that we start to count the position
from the beginning of the sentence
and not from the beginning of the disambiguated page.
:param annotation: Annotation object
:param tag_inde... | a7da5810711ada97a2ddcc308be244233fe813be | 6,301 |
import click
def parse_rangelist(rli):
"""Parse a range list into a list of integers"""
try:
mylist = []
for nidrange in rli.split(","):
startstr, sep, endstr = nidrange.partition("-")
start = int(startstr, 0)
if sep:
end = int(endstr, 0)
... | 321496a1170b81d02b8378d687d8ce6d6295bff6 | 6,303 |
import os
def intersect_by_tf(emotion_dict):
""" Takes multiple emotion word lists and intersects them by their term frequency, leading to the emotional
difference between sets of any size.
Args:
emotion_dict: dict of summed up emotional scores based on the tf scores of the underlying words
... | f46a02b736a76bd3adcc1efaf7638452241567ce | 6,304 |
def transcript_segments(location_descriptors, gene_descriptors):
"""Provide possible transcript_segment input."""
return [
{
"transcript": "refseq:NM_152263.3",
"exon_start": 1,
"exon_start_offset": -9,
"exon_end": 8,
"exon_end_offset": 7,
... | 3ca9041ff278dcd19432b6d314b9c01de6be1983 | 6,305 |
def encode_label(text):
"""Encode text escapes for the static control and button labels
The ampersand (&) needs to be encoded as && for wx.StaticText
and wx.Button in order to keep it from signifying an accelerator.
"""
return text.replace("&", "&&") | b4402604f87f19dab9dbda4273798374ee1a38d8 | 6,306 |
from warnings import filterwarnings
def calcRSI(df):
"""
Calculates RSI indicator
Read about RSI: https://www.investopedia.com/terms/r/rsi.asp
Args:
df : pandas.DataFrame()
dataframe of historical ticker data
Returns:
pandas.DataFrame()
dataframe of calcula... | 4c2c76159473bf8b23e24cb02af00841977c7cd3 | 6,307 |
import struct
def add_header(input_array, codec, length, param):
"""Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the prepended encoded ... | 228db86bb6eb9e3c7cc59cc48b67e443d46cc36d | 6,308 |
def _get_positional_body(*args, **kwargs):
"""Verify args and kwargs are valid, and then return the positional body, if users passed it in."""
if len(args) > 1:
raise TypeError("There can only be one positional argument, which is the POST body of this request.")
if "options" in kwargs:
raise... | c777296ab9c0e95d0f4d7f88dfd4ae292bfc558f | 6,309 |
def question_input (user_decision=None):
"""Obtains input from user on whether they want to scan barcodes or not.
Parameters
----------
user_decision: default is None, if passed in, will not ask user for input. string type.
Returns
-------
True if user input was 'yes'
False is... | afb7f3d4eef0795ad8c4ff7878e1469e07ec1875 | 6,310 |
def depth(d):
"""Check dictionary depth"""
if isinstance(d, dict):
return 1 + (max(map(depth, d.values())) if d else 0)
return 0 | 6fd72b255a5fba193612cfa249bf4d242b315be1 | 6,311 |
import logging
def validate_analysis_possible(f):
"""
Decorator that validates that the amount of information is
sufficient for attractor analysis.
:param f: function
:return: decorated function
"""
def f_decorated(*args, **kwargs):
db_conn, *_ = args
if db_conn.root.n_agg... | 9de0cbf2e18e47d14912ae3ebdff526a73f2c25d | 6,312 |
def remove_whitespace(sentences):
"""
Clear out spaces and newlines
from the list of list of strings.
Arguments:
----------
sentences : list<list<str>>
Returns:
--------
list<list<str>> : same strings as input,
without spaces or newlines.
"""
return [[w.... | ed50124aec20feba037ea775490ede14457d6943 | 6,313 |
def mongo_stat(server, args_array, **kwargs):
"""Method: mongo_stat
Description: Function stub holder for mongo_perf.mongo_stat.
Arguments:
(input) server
(input) args_array
(input) **kwargs
class_cfg
"""
status = True
if server and args_array and kwar... | 45ae8fd66a1d0cae976959644837fae585d68e65 | 6,314 |
import pkg_resources
def get_pkg_license(pkgname):
"""
Given a package reference (as from requirements.txt),
return license listed in package metadata.
NOTE: This function does no error checking and is for
demonstration purposes only.
"""
pkgs = pkg_resources.require(pkgname)
pkg = pkg... | 238f2b3d33de6bf8ebfcca8f61609a58357e6da1 | 6,315 |
import traceback
def get_err_str(exception, message, trace=True):
"""Return an error string containing a message and exception details.
Args:
exception (obj): the exception object caught.
message (str): the base error message.
trace (bool): whether the traceback is included (default=T... | 0ede3de80fb1097b0537f90337cf11ffa1edecf7 | 6,316 |
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 685ff34e14c26fcc408e5d4f9219483118bfd3c0 | 6,317 |
import platform
import pickle
def load_pickle(f):
"""使用pickle加载文件"""
version = platform.python_version_tuple() # 取python版本号
if version[0] == '2':
return pickle.load(f) # pickle.load, 反序列化为python的数据类型
elif version[0] == '3':
return pickle.load(f, encoding='latin1')
raise ValueErro... | 33db0ba6dbd8b1d2b3eba57e63d4069d91fbcb0b | 6,318 |
from typing import Any
def check_int(data: Any) -> int:
"""Check if data is `int` and return it."""
if not isinstance(data, int):
raise TypeError(data)
return data | 814155f2407cd0e8b580372679f4cecfcc087d9e | 6,319 |
def getFirstValid(opts, default):
"""Returns the first valid entry from `opts`, or `default` if none found.
Valid is defined as ``if o`` returns true."""
for o in opts:
if o: return o
return default | 799a6ea4a993f0a112fa38b882566d72a0d223e0 | 6,320 |
def check_string_is_nonempty(string, string_type='string'):
"""Ensures input is a string of non-zero length"""
if string is None or \
(not isinstance(string, str)) or \
len(string) < 1:
raise ValueError('name of the {} must not be empty!'
''.format(string_type))... | 527e60b35f6a827ee9b1eae3c9a3f7abc596b7ff | 6,322 |
import hashlib
def md5(filename):
"""Hash function for files to be uploaded to Fl33t"""
md5hash = hashlib.md5()
with open(filename, "rb") as filehandle:
for chunk in iter(lambda: filehandle.read(4096), b""):
md5hash.update(chunk)
return md5hash.hexdigest() | 35068abafee2c5c4b1ac672f603b0e720a8c9a8c | 6,326 |
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) | 441466f163a7b968cf193e503d43a1b014be7c5d | 6,327 |
def compute_edits(old, new):
"""Compute the in-place edits needed to convert from old to new
Returns a list ``[(index_1,change_1), (index_2,change_2)...]``
where ``index_i`` is an offset into old, and ``change_1`` is the
new bytes to replace.
For example, calling ``compute_edits("abcdef", "qbcdzw"... | f729addf84207f526e27d67932bb5300ced24b54 | 6,328 |
def pre_order(size):
"""List in pre order of integers ranging from 0 to size in a balanced
binary tree.
"""
interval_list = [None] * size
interval_list[0] = (0, size)
tail = 1
for head in range(size):
start, end = interval_list[head]
mid = (start + end) // 2
if mid ... | 45ab688c627c19cd0b9c1200830a91b064d46bda | 6,329 |
def inner_product(D1, D2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for key in D1:
if key in D2:
result += D1[key] * D2[key]
return result | 95efb9f63d6a379e1c5f7c8f6ad4bfd4061e2032 | 6,331 |
def reorder_kernel_weight(torch_weight):
""" Reorder a torch kernel weight into a tf format """
len_shape = len(torch_weight.shape)
transpose_target = list(range(len_shape))
transpose_target = transpose_target[2:] + transpose_target[:2][::-1]
return torch_weight.transpose(transpose_target) | 2e289d768d31d3ed875fbb3613ec0e3061b65cd9 | 6,335 |
def interpolate(arr_old, arr_new, I_old, J_old):
# deprecated 2013-08-26
"""
input: array, i, j
output: value
(int(x),
int(y)+1)
+ + (int(x)+1, int(y)+1)
(x,y)
+ + (int(x)+1, int(y))
(int(x),
int(y))
be careful - floor(x)=ceil(x)=x for intege... | bcb34c33ca462c43390ff0dd8802d05dc0512dd3 | 6,336 |
import numpy
def movmeanstd(ts, m=0):
"""
Calculate the mean and standard deviation within a moving window passing across a time series.
Parameters
----------
ts: Time series to evaluate.
m: Width of the moving window.
"""
if m <= 1:
raise ValueError("Query length must be long... | 8a9e56db4f26862bff972a3dbfac87f6ea5b8c35 | 6,337 |
def get_sec (hdr,key='BIASSEC') :
"""
Returns the numpy range for a FITS section based on a FITS header entry using the standard format
{key} = '[{col1}:{col2},{row1}:row2}]'
where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2.
"""
if key in hdr :
s = hdr.get(key) # WITHOUT CARD COMMENT
ny = hdr['NAXIS2']
sx = ... | 3927e6f5d62818079fa9475976f04dda1824e976 | 6,338 |
def string_to_gast(node):
"""
handles primitive string base case
example: "hello"
exampleIn: Str(s='hello')
exampleOut: {'type': 'str', 'value': 'hello'}
"""
return {"type": "str", "value": node.s} | a3dcd89e893c6edd4a9ba6095cd107bb48cc9782 | 6,341 |
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area,
wing_span, TURBOPROP):
""" The function estimates the operating empty mass (OEM)
Source: Raymer, D.P. "Aircraft design: a conceptual approach"
AIAA educational Series, Fourth edition (2006)... | 5b9bed8cef76f3c10fed911087727f0164cffab2 | 6,342 |
def getSqTransMoment(system):
"""//Input SYSTEM is a string with both the molecular species AND the band "system"
// Electronic transition moment, Re, needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2
// //Allen's Astrophysical quantities, 4.12.2 - 4.13.1
// // ROtational & vibrational constants for... | 19c5311f7d8fde4bb834d809fd2f6ed7dd2c036e | 6,343 |
def is_configured():
"""Return if Azure account is configured."""
return False | 5662656b513330e0a05fa25decc03c04b5f367fa | 6,344 |
def box_strings(*strings: str, width: int = 80) -> str:
"""Centre-align and visually box some strings.
Args:
*strings (str): Strings to box. Each string will be printed on its own
line. You need to ensure the strings are short enough to fit in the
box (width-6) or the results wi... | b47aaf020cf121b54d2b588bdec3067a3b83fd27 | 6,345 |
def buildDictionary(message):
"""
counts the occurrence of every symbol in the message and store it in a python dictionary
parameter:
message: input message string
return:
python dictionary, key = symbol, value = occurrence
"""
_dict = dict()
for c in message:
if ... | 71b196aaccfb47606ac12242585af4ea2554a983 | 6,348 |
import six
def logger_has_handlers(logger):
"""
Check if given logger has at least 1 handler associated, return a boolean value.
Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself.
"""
if six.PY3:
return logger.hasHandlers()
else:
c =... | dc0093dd25a41c997ca92759ccb9fa17ad265bdd | 6,350 |
def setup_train_test_idx(X, last_train_time_step, last_time_step, aggregated_timestamp_column='time_step'):
""" The aggregated_time_step_column needs to be a column with integer values, such as year, month or day """
split_timesteps = {}
split_timesteps['train'] = list(range(last_train_time_step + 1))
... | 256fbe66c0b27b651c8190101e5068f7e0542498 | 6,351 |
def add_lists(list1, list2):
"""
Add corresponding values of two lists together. The lists should have the same number of elements.
Parameters
----------
list1: list
the first list to add
list2: list
the second list to add
Return
----------
output: list
... | e4efbc079a981caa4bcbff4452c8845a7e534195 | 6,352 |
def optimize_solution(solution):
"""
Eliminate moves which have a full rotation (N % 4 = 0)
since full rotations don't have any effects in the cube
also if two consecutive moves are made in the same direction
this moves are mixed in one move
"""
i = 0
while i < len(soluti... | 4be6bf0e4200dbb629c37a9bdae8338ee32c262b | 6,353 |
def read_file(filename):
"""
read filename and return its content
"""
in_fp = open(filename)
content = in_fp.read()
in_fp.close()
return content | c707a412b6099591daec3e70e9e2305fee6511f9 | 6,354 |
import argparse
def get_arguments():
"""Return the values of CLI params"""
parser = argparse.ArgumentParser()
parser.add_argument("--image_folder", default="images")
parser.add_argument("--image_width", default=400, type=int)
args = parser.parse_args()
return getattr(args, "image_folder"), get... | 288bb7a589bae308252a36febcb14b9349371603 | 6,355 |
def divide(x,y):
"""div x from y"""
return x/y | 74adba33dfd3db2102f80a757024696308928e38 | 6,356 |
def r2(data1, data2):
"""Return the r-squared difference between data1 and data2.
Parameters
----------
data1 : 1D array
data2 : 1D array
Returns
-------
output: scalar (float)
difference in the input data
"""
ss_res = 0.0
ss_tot = 0.0
mean = sum(data1) / l... | d42c06a5ad4448e74fcb1f61fa1eed1478f58048 | 6,357 |
import torch
def l1_loss(pre, gt):
""" L1 loss
"""
return torch.nn.functional.l1_loss(pre, gt) | c552224b3a48f9cde201db9d0b2ee08cd6335861 | 6,358 |
def get_image_unixtime2(ibs, gid_list):
""" alias for get_image_unixtime_asfloat """
return ibs.get_image_unixtime_asfloat(gid_list) | 2c5fb29359d7a1128fab693d8321d48c8dda782b | 6,361 |
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0):
"""Wrap the values in an array (e.g., angles)."""
rng = wrapHigh - wrapLow
arr = ((arr-wrapLow) % rng) + wrapLow
return arr | e07e8916ec060aa327c9c112a2e5232b9155186b | 6,364 |
def largest_negative_number(seq_seq):
"""
Returns the largest NEGATIVE number in the given sequence of
sequences of numbers. Returns None if there are no negative numbers
in the sequence of sequences.
For example, if the given argument is:
[(30, -5, 8, -20),
(100, -2.6, 88, -40, -... | b7326b3101d29fcc0b8f5921eede18a748af71b7 | 6,365 |
def filter_resources_sets(used_resources_sets, resources_sets, expand_resources_set, reduce_resources_set):
""" Filter resources_set used with resources_sets defined.
It will block a resources_set from resources_sets if an used_resources_set in a subset of a resources_set"""
resources_expand = [expand_... | 2ecd752a0460fff99ecc6b8c34ed28782e848923 | 6,367 |
def dump_cups_with_first(cups: list[int]) -> str:
"""Dump list of cups with highlighting the first one
:param cups: list of digits
:return: list of cups in string format
"""
dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} '
ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerat... | 5fe4111f09044c6afc0fbd0870c2b5d548bd3c1a | 6,368 |
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3):
"""
Function initializes krls dictionary. |br|
Args:
strKernel (string): Type of the kernel
iKernelPar (float): Kernel parameter [default = 1]
iALDth (float): ALD threshold [default = 1e-4]
iMaxDict (int): Max... | 652e0c498b4341e74bcd30ca7119163345c7f2cc | 6,369 |
from typing import Optional
from pathlib import Path
import site
def get_pipx_user_bin_path() -> Optional[Path]:
"""Returns None if pipx is not installed using `pip --user`
Otherwise returns parent dir of pipx binary
"""
# NOTE: using this method to detect pip user-installed pipx will return
# N... | ccf9b886af41b73c7e2060704d45781938d8e811 | 6,370 |
def _normalize_int_key(key, length, axis_name=None):
"""
Normalizes an integer signal key.
Leaves a nonnegative key as it is, but converts a negative key to
the equivalent nonnegative one.
"""
axis_text = '' if axis_name is None else axis_name + ' '
if key < -length o... | 9b58b09e70c20c9ac5ee0be059333dd5058802ef | 6,371 |
from typing import Iterable
def prodi(items: Iterable[float]) -> float:
"""Imperative product
>>> prodi( [1,2,3,4,5,6,7] )
5040
"""
p: float = 1
for n in items:
p *= n
return p | 3b8e52f40a760939d5b291ae97c4d7134a5ab450 | 6,372 |
def hexString(s):
"""
Output s' bytes in HEX
s -- string
return -- string with hex value
"""
return ":".join("{:02x}".format(ord(c)) for c in s) | 22c1e94f0d54ca3d430e0342aa5b714f28a5815b | 6,373 |
from typing import List
def normalize_resource_paths(resource_paths: List[str]) -> List[str]:
"""
Takes a list of resource relative paths and normalizes to lowercase
and with the "ed-fi" namespace prefix removed.
Parameters
----------
resource_paths : List[str]
The list of resource re... | ec7e5020ae180cbbdc5b35519106c0cd0697a252 | 6,374 |
from functools import reduce
def update(*p):
""" Update dicts given in params with its precessor param dict
in reverse order """
return reduce(lambda x, y: x.update(y) or x,
(p[i] for i in range(len(p)-1,-1,-1)), {}) | de7f5adbe5504dd9b1be2bbe52e14d11e05ae86f | 6,375 |
def rangify(values):
"""
Given a list of integers, returns a list of tuples of ranges (interger pairs).
:param values:
:return:
"""
previous = None
start = None
ranges = []
for r in values:
if previous is None:
previous = r
start = r
elif r ==... | 672b30d4a4ce98d2203b84db65ccebd53d1f73f5 | 6,376 |
def site_geolocation(site):
""" Obtain lat-lng coordinate of active trials in the Cancer NCI API"""
try:
latitude = site['org_coordinates']['lat']
longitude = site['org_coordinates']['lon']
lat_lng = tuple((latitude, longitude))
return lat_lng
except KeyError: # key ['org... | 9fefcd3f49d82233005c88e645efd1c00e1db564 | 6,378 |
def get_scaling_desired_nodes(sg):
"""
Returns the numb of desired nodes the scaling group will have in the future
"""
return sg.get_state()["desired_capacity"] | 5a417f34d89c357e12d760b28243714a50a96f02 | 6,379 |
def notas(* valores, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param valores: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma... | a6915e9b7b1feef0db2be6fdf97b6f236d73f282 | 6,381 |
def append_OrbitSection(df):
"""Use OrbitDirection flags to identify 4 sections in each orbit."""
df["OrbitSection"] = 0
ascending = (df["OrbitDirection"] == 1) & (df["QDOrbitDirection"] == 1)
descending = (df["OrbitDirection"] == -1) & (df["QDOrbitDirection"] == -1)
df["OrbitSection"].mask(
... | 4f2cad6cb2facf6a7a8c7a89ed7b3df0a56a54c2 | 6,382 |
def hex_to_64(hexstr):
"""Convert a hex string to a base64 string.
Keyword arguments:
hexstr -- the hex string we wish to convert
"""
B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
## internals
# bits contains the bits read off so far that don't make enou... | ca8c48bedf4ac776288a8faad06ec80c0289c11e | 6,383 |
def is_private(name):
"""Check whether a Python object is private based on its name."""
return name.startswith("_") | d04dfd84884bbc8c8be179c6bc5fc1371f426a78 | 6,385 |
import warnings
def get_suitable_output_file_name_for_current_output_format(output_file, output_format):
""" renames the name given for the output_file if the results for current_output format are returned compressed by default
and the name selected by the user does not contain the correct extension.
out... | 6925d721f06e52c8177c5e4f6404629043642cc4 | 6,386 |
def count_ents(phrase):
"""
Counts the number of Named Entities in a spaCy Doc/Span object.
:param phrase: the Doc/Span object from which to remove Named Entities.
:return: The number of Named Entities identified in the input object.
"""
named_entities = list(phrase.ents)
return len(named_en... | 7e592442ebaf504320a903c4084454ff73896595 | 6,388 |
def get_Q_UT_CL_d_t_i(L_CL_d_t_i, Q_T_CL_d_t_i):
"""冷房設備機器の未処理冷房潜熱負荷(MJ/h)(20b)を計算する
Args:
Q_max_CL_d_t_i(ndarray): 最大冷房潜熱出力
L_CL_d_t_i(ndarray): 冷房潜熱負荷
Q_T_CL_d_t_i: returns: 冷房設備機器の未処理冷房潜熱負荷(MJ/h)
Returns:
ndarray: 冷房設備機器の未処理冷房潜熱負荷(MJ/h)
"""
return L_CL_d_t_i - Q_T_CL_d_... | 4f46048e6df08d634153b176b241ac1caaae252f | 6,389 |
import struct
def txt2domainname(input, canonical_form=False):
"""turn textual representation of a domain name into its wire format"""
if input == ".":
d = b'\x00'
else:
d = b""
for label in input.split('.'):
label = label.encode('ascii')
if canonical_form:
... | d5312ab1333810eaba6bac2f16e15441ea290dc9 | 6,392 |
import os
import logging
def create_dir(path_dir):
""" create a folder if it not exists
:param str path_dir:
"""
path_dir = os.path.abspath(path_dir)
if not os.path.isdir(path_dir):
os.makedirs(path_dir, mode=0o775)
else:
logging.warning('Folder already exists: %s', path_dir)
... | e26004caed69c6d29de20ea08004bd54aa1f6cf8 | 6,393 |
def sample(x, n):
"""
Get n number of rows as a sample
"""
# import random
# print(random.sample(list(x.index), n))
return x.iloc[list(range(n))] | 3802f976f2a97a08945d8246093784c06fb07e67 | 6,394 |
def issubset(list1, list2):
"""
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
"""
n = len(list1)
for startpos in range(len(list2) - n + 1):
... | 2f4acbba54b303b7041febbe485d8960baa6528f | 6,396 |
from typing import Any
def is_none_or_empty(obj: Any) -> bool:
"""Determine if object is None or empty
:param obj: object
:return: if object is None or empty
"""
return obj is None or len(obj) == 0 | a90245326e4c776ca1ee0066e965a4f656a20014 | 6,397 |
def reshape2D(x):
"""
Reshapes x from (batch, channels, H, W) to (batch, channels, H * W)
"""
return x.view(x.size(0), x.size(1), -1) | 29851e54bb816fb45184d3ea20e28d786270f662 | 6,398 |
def get_fr_trj_ntrj(rslt, start, end, a_params):
"""Check whether event exhibits "blowup" behavior."""
# get spks during candidate replay event
spks_evt = rslt.spks[(start <= rslt.ts) & (rslt.ts < end), :]
# get mask over trj and non-trj PCs
pc_mask = rslt.ntwk.types_rcr == 'PC'
sgm_cu... | 7cb2f0262debba36789e4e230b4d26dd096cf950 | 6,399 |
def add_to_group(ctx, user, group):
"""Adds a user into a group.
Returns ``True`` if is just added (not already was there).
:rtype: bool
"""
result = ctx.sudo(f'adduser {user} {group}').stdout.strip()
return 'Adding' in result | abb7b432f4e4206a3509d1376adca4babb02e9f0 | 6,400 |
import sys
def trim_docstring(docstring):
"""
This is taken from PEP257, and was slightly modified to work with Python 3
(and renamed), but is otherwise included verbatim.
https://www.python.org/dev/peps/pep-0257/
"""
if not docstring:
return ''
# Convert tabs to spaces (foll... | a4f115541dc6106749caecea44a530a095a92f57 | 6,401 |
import torch
def load_ckp(model, ckp_path, device, parallel=False, strict=True):
"""Load checkpoint
Args:
ckp_path (str): path to checkpoint
Returns:
int, int: current epoch, current iteration
"""
ckp = torch.load(ckp_path, map_location=device)
if parallel:
model.modu... | 4fe4e368d624583216add3eca62293d5d1539182 | 6,402 |
from typing import List
from typing import Any
from typing import Generator
def neighborhood(
iterable: List[Any],
) -> Generator[Any, Any, Any]:
""" """
if not iterable:
return iterable
iterator = iter(iterable)
prev_item = None
current_item = next(iterator) # throws StopIteration i... | 4d07ee920e4861fce88658b1fc5ce719907ba897 | 6,405 |
def _slice_slice(outer, outer_len, inner, inner_len):
"""
slice a slice - we take advantage of Python 3 range's support
for indexing.
"""
assert(outer_len >= inner_len)
outer_rng = range(*outer.indices(outer_len))
rng = outer_rng[inner]
start, stop, step = rng.start, rng.stop, rng.step
... | 4430ae752fbc9d7db6414418b18a0b8186f3d328 | 6,407 |
def dump_adcs(adcs, drvname='ina219', interface=2):
"""Dump xml formatted INA219 adcs for servod.
Args:
adcs: array of adc elements. Each array element is a tuple consisting of:
slv: int representing the i2c slave address plus optional channel if ADC
(INA3221 only) has multiple channels. ... | b9c0aec3e6098a5de28a467910f4861e8860d723 | 6,408 |
def is_isbn_or_key(q):
"""
判断搜索关键字是isbn还是key
:param q:
:return:
"""
# isbn13 13位0-9数字;isbn10 10位0-9数字,中间含有 '-'
isbn_or_key = 'key'
if len(q) == 13 and q.isdigit():
isbn_or_key = 'isbn'
if '-' in q:
short_q = q.replace('-', '')
if len(short_q) == 10 and short_q... | cf35f13e8188741bd37715a1ed91cf40667cff40 | 6,409 |
def get_upright_box(waymo_box):
"""Convert waymo box to upright box format and return the convered box."""
xmin = waymo_box.center_x - waymo_box.length / 2
# xmax = waymo_box.center_x+waymo_box.length/2
ymin = waymo_box.center_y - waymo_box.width / 2
# ymax = waymo_box.center_y+waymo_box.width/2
... | 2c301e3d60078ba416446dfe133fb9802c96f09c | 6,410 |
def update_two_contribution_score(click_time_one, click_time_two):
"""
user cf user contribution score update v2
:param click_time_one: different user action time to the same item
:param click_time_two: time two
:return: contribution score
"""
delta_time = abs(click_time_two - click_time_one... | df959e4581f84be5e0dffd5c35ebe70b97a78383 | 6,411 |
def fix_text_note(text):
"""Wrap CHS document text."""
if not text:
return ""
else:
return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text) | 56cbcbad7e8b3eee6bb527a240ad96701c4eea2f | 6,412 |
import multiprocessing
def _fetch_cpu_count():
"""
Returns the number of available CPUs on machine in use.
Parameters:
-----------
None
Returns:
--------
multiprocessing.cpu_count()
Notes:
------
None
"""
return multiprocessing.cpu_count() | 6c35446b706aa27b49bd678520b2378b1c7f8b90 | 6,414 |
def is_block_comment(line):
""" Entering/exiting a block comment """
line = line.strip()
if line == '"""' or (line.startswith('"""') and not line.endswith('"""')):
return True
if line == "'''" or (line.startswith("'''") and not line.endswith("'''")):
return True
return False | ea38c248964eeaec1eab928182022de6ecccad69 | 6,415 |
from typing import List
from typing import Dict
import requests
def get_airtable_data(url: str, token: str) -> List[Dict[str, str]]:
"""
Fetch all data from airtable.
Returns a list of records where record is an array like
{'my-key': 'George W. Bush', 'my-value': 'Male'}
"""
response = re... | f91326938a663ddedd8b4a10f796c7c36981da4e | 6,416 |
def displayname(user):
"""Returns the best display name for the user"""
return user.first_name or user.email | aecebc897803a195b08cdfb46dbeb4c9df9ede09 | 6,417 |
def price(listing):
"""Score based on number of bedrooms."""
if listing.price is None:
return -4000
score = 0.0
bedrooms = 1.0 if listing.bedrooms is None else listing.bedrooms
if (bedrooms * 1000.0) > listing.price:
score += -1000 - ((bedrooms * 750.0) / listing.price - 1.0) * 1000
... | 7087da4e4f9dedf03fdaed5661029f1be0703f0e | 6,418 |
import shlex
def shell_quote(*args: str) -> str:
"""
Takes command line arguments as positional args, and properly quotes each argument to make it safe to
pass on the command line. Outputs a string containing all passed arguments properly quoted.
Uses :func:`shlex.join` on Python 3.8+, and a for ... | b2d0ecde5a2569e46676fed81ed3ae034fb8d36c | 6,419 |
import torch
def normalized_state_to_tensor(state, building):
"""
Transforms a state dict to a pytorch tensor.
The function ensures the correct ordering of the elements according to the list building.global_state_variables.
It expects a **normalized** state as input.
"""
ten = [[ state[sval] ... | 4aea246f388f941290d2e4aeb6da16f91e210caa | 6,420 |
def translate_lat_to_geos5_native(latitude):
"""
The source for this formula is in the MERRA2
Variable Details - File specifications for GEOS pdf file.
The Grid in the documentation has points from 1 to 361 and 1 to 576.
The MERRA-2 Portal uses 0 to 360 and 0 to 575.
latitude: float Needs +/- i... | b1fb1824bfefce3fd58ca7a26f9603b910779a61 | 6,421 |
def disabled_payments_notice(context, addon=None):
"""
If payments are disabled, we show a friendly message urging the developer
to make his/her app free.
"""
addon = context.get('addon', addon)
return {'request': context.get('request'), 'addon': addon} | b77dc41cf8ac656b2891f82328a04c1fe7aae49c | 6,422 |
def construct_futures_symbols(
symbol, start_year=2010, end_year=2014
):
"""
Constructs a list of futures contract codes
for a particular symbol and timeframe.
"""
futures = []
# March, June, September and
# December delivery codes
months = 'HMUZ'
for y in range(start_... | 2917a9eb008f5ab141576243bddf4769decfd1f3 | 6,423 |
def getAllChannels():
"""
a func to see all valid channels
:return: a list channels
"""
return ["Hoechst", 'ERSyto', 'ERSytoBleed', 'Ph_golgi', 'Mito'] | d4fee111bad73f8476877a96645490aef37c07c9 | 6,425 |
from typing import Dict
from typing import Any
def merge_dicts(dict1: Dict[str, Any],
dict2: Dict[str, Any],
*dicts: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge multiple dictionaries, producing a merged result without modifying
the arguments.
:param dict1: the firs... | 869399774cc07801e5fa95d9903e6a9f2dadfc25 | 6,428 |
from datetime import datetime
def iso_date(iso_string):
""" from iso string YYYY-MM-DD to python datetime.date
Note: if only year is supplied, we assume month=1 and day=1
This function is not longer used, dates from lists always are strings
"""
if len(iso_string) == 4:
iso_string =... | 7f29b22744d384187e293c546d4c28790c211e99 | 6,430 |
def number_to_string(s, number):
"""
:param s: word user input
:param number: string of int which represent possible anagram
:return: word of alphabet
"""
word = ''
for i in number:
word += s[int(i)]
return word | 7997b20264d0750e2b671a04aacb56c2a0559d8c | 6,431 |
import torch
def softmax(x):
"""Softmax activation function
Parameters
----------
x : torch.tensor
"""
return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1) | 739219efe04174fe7a2b21fb8aa98816679f8389 | 6,434 |
def remove_element(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
sz = len(nums)
while sz > 0 and nums[sz - 1] == val:
sz -= 1
i = 0
while i < sz:
if nums[i] == val:
nums[i], nums[sz - 1] = nums[sz - 1], nums[i]
sz -= 1
... | 4d29e8a8d43f191fe83ab0683f5dff005db799ec | 6,435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.