content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def tweet_words(tweet):
"""Return the words in a tweet."""
return extract_words(tweet_text(tweet)) | 5,343,900 |
def meter_statistics(meter_id,api_endpoint,token,meter_list,web,**kwargs):
"""
Get the statistics for the specified meter.
Args:
meter_id(string): The meter name.
api_endpoint(string): The api endpoint for the ceilometer service.
token(string): X-Auth-token.
meter_list(list): T... | 5,343,901 |
def parse_image_size(image_size: Union[Text, int, Tuple[int, int]]):
"""Parse the image size and return (height, width).
Args:
image_size: A integer, a tuple (H, W), or a string with HxW format.
Returns:
A tuple of integer (height, width).
"""
if isinstance(image_size, int):
# ... | 5,343,902 |
def find_last_match(view, what, start, end, flags=0):
"""Find last occurrence of `what` between `start`, `end`.
"""
match = view.find(what, start, flags)
new_match = None
while match:
new_match = view.find(what, match.end(), flags)
if new_match and new_match.end() <= end:
... | 5,343,903 |
def convert_metrics_per_batch_to_per_sample(metrics, target_masks):
"""
Args:
metrics: list of len(num_batches), each element: list of len(num_metrics), each element: (num_active_in_batch,) metric per element
target_masks: list of len(num_batches), each element: (batch_size, seq_len, feat_dim) b... | 5,343,904 |
async def get_series(database, series_id):
"""Get a series."""
series_query = """
select series.id, series.played, series_metadata.name, rounds.tournament_id, tournaments.id as tournament_id,
tournaments.name as tournament_name, events.id as event_id, events.name as event_name
from serie... | 5,343,905 |
def n_mpjpe(predicted, target):
"""
Normalized MPJPE (scale only), adapted from:
https://github.com/hrhodin/UnsupervisedGeometryAwareRepresentationLearning/blob/master/losses/poses.py
"""
assert predicted.shape == target.shape
norm_predicted = np.mean(np.sum(predicted**2, axis=2, keepdims=T... | 5,343,906 |
def calc_distance(p1, p2):
""" calculates a distance on a 2d euclidean space, between two points"""
dist = math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
return dist | 5,343,907 |
def rgb2ycbcr(img, range=255., only_y=True):
"""same as matlab rgb2ycbcr, please use bgr2ycbcr when using cv2.imread
img: shape=[h, w, 3]
range: the data range
only_y: only return Y channel
"""
in_img_type = img.dtype
img.astype(np.float32)
range_scale = 255. / range
img *= range_sca... | 5,343,908 |
def _create_xctest_bundle(name, actions, binary):
"""Creates an `.xctest` bundle that contains the given binary.
Args:
name: The name of the target being built, which will be used as the
basename of the bundle (followed by the .xctest bundle extension).
actions: The context's action... | 5,343,909 |
def doFile(path_, *args, **kwargs):
"""Execute a given file from path with arguments."""
result, reason = loadfile(path_)
if result:
data = result(*args, **kwargs)
if data:
return data[1]
error(data[1])
error(reason) | 5,343,910 |
def setEcnEnabled(enabled):
""" Enable/disable threshold-based ECN marking. """
val = 'true' if enabled else 'false'
for src in xrange(1, NUM_RACKS + 1):
for dst in xrange(1, NUM_RACKS + 1):
clickWriteHandler('hybrid_switch/q{}{}/q'.format(src, dst),
'markin... | 5,343,911 |
def pformat(obj, verbose=False):
"""
Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj) | 5,343,912 |
def reanalyze_function(*args):
"""
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR, bool analyze_parents=False)
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR)
reanalyze_function(func_t pfn, ea_t ea1=0)
reanalyze_function(func_t pfn)
"""
return _idaapi.reanalyze_f... | 5,343,913 |
def categorical_sample_logits(logits):
"""
Samples (symbolically) from categorical distribution, where logits is a NxK
matrix specifying N categorical distributions with K categories
specifically, exp(logits) / sum( exp(logits), axis=1 ) is the
probabilities of the different classes
Cleverly ... | 5,343,914 |
def mass(d, r):
""" computes the right hand side of the differential equation of mass continuity
"""
return 4 * pi * d * r * r | 5,343,915 |
def bord(u):
"""
éxécution de bord("undébutuntructrucundébut")
i suffix estPréfixe
23 ndébutuntructrucundébut False
22 débutuntructrucundébut False
21 ébutuntructrucundébut False
20 butuntructrucundébut False
19 utuntructrucundébut False
18 tuntru... | 5,343,916 |
def is_unique_n_bit_vector(string: str) -> bool:
"""
Similiar to the dict solution, it just uses a bit vector instead of a dict or array.
"""
vector = 0
for letter in string:
if vector & 1 << ord(letter):
return False
vector |= 1 << ord(letter)
return True | 5,343,917 |
def print_error(err_str: str, once: bool = False) -> None:
"""Print info about an error along with pertinent context state.
category: General Utility Functions
Prints all positional arguments provided along with various info about the
current context.
Pass the keyword 'once' as True if you want th... | 5,343,918 |
def to_int_cmd(ctx, data: str):
"""
Convert ASCII string to a number.
"""
echo(NeoData.to_int(data)) | 5,343,919 |
def seq2msk(isq):
"""
Convert seqhis into mskhis
OpticksPhoton.h uses a mask but seq use the index for bit-bevity::
3 enum
4 {
5 CERENKOV = 0x1 << 0,
6 SCINTILLATION = 0x1 << 1,
7 MISS = 0x1 << 2,
8 BU... | 5,343,920 |
def split(ich):
""" Split a multi-component InChI into InChIs for each of its components.
(fix this for /s [which should be removed in split/join operations]
and /m, which is joined as /m0110.. with no separators)
:param ich: InChI string
:type ich: str
:rtype: tuple(str)... | 5,343,921 |
def crtb_cb(client, crtb):
"""Wait for the crtb to have the userId populated"""
def cb():
c = client.reload(crtb)
return c.userId is not None
return cb | 5,343,922 |
def test_basic():
"""Another test, to show how it appears in the results"""
pass | 5,343,923 |
def create_network(network_input, n_alphabets):
""" create the structure of the neural network """
model = Sequential()
model.add(LSTM(512,input_shape=(network_input.shape[1], network_input.shape[2]),return_sequences=True))
model.add(Dropout(0.3))
model.add(Bidirectional(LSTM(512, return_sequences=T... | 5,343,924 |
def create_derivative_graph(f, xrange, n):
"""Takes a function as an input with a specific interval xrange, then creates a list with the ouput
y-points for the nth derivative of f.
:param f: Input function that we wish to take the derivative of.
:type f: lambda
:param xrange: The interval on wh... | 5,343,925 |
def _matching_not_matching(on, **kwargs):
"""
Change the text for matching/not matching
"""
text = "matching" if not on else "not matching"
classname = "colour-off" if not on else "colour-on"
return text, classname | 5,343,926 |
def prepare_testenv(config=None, template=None, args=None):
"""
prepare an engine-ready environment for a test
This utility method is used to provide an `RelengEngine` instance ready for
execution on an interim working directory.
Args:
config (optional): dictionary of options to mock for a... | 5,343,927 |
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN that is... | 5,343,928 |
def vstack(arg_list):
"""Wrapper on vstack to ensure list argument.
"""
return Vstack(*arg_list) | 5,343,929 |
def metadata_to_list(metadata):
"""Transform a metadata dictionary retrieved from Cassandra to a list of
tuples. If metadata items are lists they are split into multiple pairs in
the result list
:param metadata: dict"""
res = []
for k, v in metadata.iteritems():
try:
val_json... | 5,343,930 |
def GetSetUpAndResponse():
"""
This method is called by an API acting as a client while performing the PSI protocol.
This method initialises a server object. (This API acts as server)
This method uses the PSI Request ID given by the calling API to identify the corresponding node list from the serve... | 5,343,931 |
def load_separator(
model_str_or_path: str = "umxhq",
niter: int = 1,
residual: bool = False,
slicq_wiener: bool = False,
wiener_win_len: Optional[int] = 300,
device: Union[str, torch.device] = "cpu",
pretrained: bool = True,
):
"""Separator loader
Args:
model_str_or_path (s... | 5,343,932 |
def IntermediateParticleConst_get_decorator_type_name():
"""IntermediateParticleConst_get_decorator_type_name() -> std::string"""
return _RMF.IntermediateParticleConst_get_decorator_type_name() | 5,343,933 |
def multiply_add_plain_with_delta(ct, pt, context_data):
"""Add plaintext to ciphertext.
Args:
ct (Ciphertext): ct is pre-computed carrier polynomial where we can add pt data.
pt (Plaintext): A plaintext representation of integer data to be encrypted.
context (Context): Context for extr... | 5,343,934 |
def ginput(n=1, timeout=30, debug=False):
"""
Simple functional call for physicists. This will wait for n clicks
from the user and
return a list of the coordinates of each click.
"""
x = GaelInput()
return x(n, timeout, debug) | 5,343,935 |
def retrieve_form_data(form, submission_type="solution"):
"""Quick utility function that groups together the processing of request data. Allows for easier handling of exceptions
Takes request object as argument
On Success, returns hashmap of processed data...otherwise raise an exception"""
if submissio... | 5,343,936 |
def existing_file(fname):
"""
Check if the file exists. If not raise an error
Parameters
----------
fname: string
file name to parse
Returns
-------
fname : string
"""
if os.path.isfile(fname):
return fname
else:
msg = "The file '{}' does not exist".... | 5,343,937 |
async def test_update_with_failed_get(hass, caplog):
"""Test attributes get extracted from a XML result with bad xml."""
respx.get(
"http://localhost",
status_code=200,
headers={"content-type": "text/xml"},
content="",
)
assert await async_setup_component(
hass,
... | 5,343,938 |
def keep_english_for_spacy_nn(df):
"""This function takes the DataFrame for songs
and keep songs with english as main language
for english version of spacy neural network for word processing"""
#Keep only english for spacy NN English preprocessing words
#Network for other languages like fre... | 5,343,939 |
def make_dealer_cards_more_fun(deck, dealer):
"""
to make dealercards more fun to make dealer win this game more.
:param dealercards: dealercards
:return: none
maybe has a lot of memory work will arise.
"""
dealercards = card_sorting_dealer(dealer)
count = 0
if jokbo(dealercards) =... | 5,343,940 |
def subinit1_initpaths_config_log():
"""
Initializes the paths (stored in global __PATHS):
1 Finds the project location
2 Reads config.ini
3 Reads the paths defined in config.ini
4 Checks that the paths exist
"""
# -------------------------------------------------------------------------------- 1) F... | 5,343,941 |
def update_draft(
url: str,
access_key: str,
dataset_id: str,
draft_number: int,
*,
status: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
) -> None:
"""Execute the OpenAPI `PATCH /v1/datasets{id}/drafts{draftNumber}`.
Arguments:
ur... | 5,343,942 |
def data(request):
"""Returns available albums from the database. Can be optionally filtered by year.
This is called from templates/albums/album/index.html when the year input is changed.
"""
year = request.GET.get('year')
if year:
try:
year = int(year)
except (ValueErro... | 5,343,943 |
def yaw_to_quaternion3d(yaw: float) -> Tuple[float,float,float,float]:
"""
Args:
- yaw: rotation about the z-axis
Returns:
- qx,qy,qz,qw: quaternion coefficients
"""
qx,qy,qz,qw = Rotation.from_euler('z', yaw).as_quat()
return qx,qy,qz,qw | 5,343,944 |
def typecheck(session: Session) -> Session:
"""Run type checking (using mypy)."""
args = session.posargs or locations
session.install("types-requests", "types-termcolor", "types-colorama")
session.install("mypy")
session.run("mypy", *args) | 5,343,945 |
def parse_coap_response_code(response_code):
"""
Parse the binary code from CoAP response and return the response code as a float.
See also https://tools.ietf.org/html/rfc7252#section-5.9 for response code definitions.
:rtype float
"""
response_code_class = response_code // 32
response_code... | 5,343,946 |
def modified_partial_sum_product(
sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict()
):
"""
Generalization of the tensor variable elimination algorithm of
:func:`funsor.sum_product.partial_sum_product` to handle markov dimensions
in addition to plate dimensions. Markov dimensions ... | 5,343,947 |
def load_scicar_cell_lines(test=False):
"""Download sci-CAR cell lines data from GEO."""
if test:
adata = load_scicar_cell_lines(test=False)
adata = subset_joint_data(adata)
return adata
return load_scicar(
rna_url,
rna_cells_url,
rna_genes_url,
atac_u... | 5,343,948 |
def ExtrudeNA(chain):
"""Computes ribbons for DNA/RNA"""
coord = []
coord.append(chain.DNARes[0].atoms[0].coords)
NA_type = chain.DNARes[0].type.strip()
atoms = chain.DNARes[0].atoms
missingAts = False
normal = numpy.array([0.,1.,0.])
if NA_type in ['A', 'G']:
... | 5,343,949 |
def binary_search(sorted_list, item):
"""
Implements a Binary Search, O(log n).
If item is is list, returns amount of steps.
If item not in list, returns None.
"""
steps = 0
start = 0
end = len(sorted_list)
while start < end:
steps += 1
mid = (start + end) // 2
... | 5,343,950 |
def _process_split(
pipeline,
*,
filename_template: naming.ShardedFileTemplate,
out_dir: utils.ReadWritePath,
file_infos: List[naming.FilenameInfo],
):
"""Process a single split."""
beam = lazy_imports_lib.lazy_imports.apache_beam
# Use unpack syntax on set to implicitly check that all values... | 5,343,951 |
def _scale_by(number, should_fail=False):
"""
A helper function that creates a scaling policy and scales by the given
number, if the number is not zero. Otherwise, just triggers convergence.
:param int number: The number to scale by.
:param bool should_fail: Whether or not the policy execution sho... | 5,343,952 |
def test_read_response_error_received(handshake):
"""
Test the response returned by the database is an error.
"""
handshake.next_state = Mock()
handshake.state = HandshakeState.INITIAL_RESPONSE
with pytest.raises(ValueError):
handshake.next_message(bytes("ERROR", "utf-8"))
assert ... | 5,343,953 |
def selectgender(value):
"""格式化为是/否
:param value:M/F,
:return: 男/女
"""
absent = {"M": u'男', "F": u'女'}
try:
if value:
return absent[value]
return ""
except:
traceback.print_exc() | 5,343,954 |
def Clifford_twirl_channel_one_qubit(K, rho, sys=1, dim=[2]):
"""
Twirls the given channel with Kraus operators in K by the one-qubit
Clifford group on the given subsystem (specified by sys).
"""
n = int(np.log2(np.sum([d for d in dim])))
C1 = eye(2**n)
C2 = Rx_i(sys, np.pi, n)
C3 = Rx... | 5,343,955 |
def unpack_batch(batch, use_cuda=False):
""" Unpack a batch from the data loader. """
input_ids = batch[0]
input_mask = batch[1]
segment_ids = batch[2]
boundary_ids = batch[3]
pos_ids = batch[4]
rel_ids = batch[5]
knowledge_feature = batch[6]
bio_ids = batch[1]
# knowledge_adjoin... | 5,343,956 |
def truncate(text: str, length: int = 255, end: str = "...") -> str:
"""Truncate text.
Parameters
---------
text : str
length : int, default 255
Max text length.
end : str, default "..."
The characters that come at the end of the text.
Returns
-------
truncated text... | 5,343,957 |
def write_matchcat(cat1,cat2,outfile,rmatch,c1fluxcol,c2fluxcol):
"""
Writes an output file in the format of the file produced by catcomb.c.
*** NOTE *** The catalog matching (with the find_match function in
matchcat.py) has to have been run before running this code.
Inputs:
cat1 - first c... | 5,343,958 |
def create_logger(log_dir, log_file, level="info"):
"""
Function used to create logger object based on log directory
and log file name
"""
handler = RotatingFileHandler(filename=path.join(log_dir, log_file),
mode='a', maxBytes=5000000, backupCount=10)
formatter ... | 5,343,959 |
def test_github_recon_return_none_with_none_input():
"""Test recon function return None with None input."""
assert github_recon(None) is None | 5,343,960 |
def gaussian_slice(x, sigma, mu):
"""
return a slice of x in which the gaussian is significant
exp(-0.5 * ((x - mu) / sigma) ** 2) < given_threshold
"""
r = sigma * sp.sqrt(-2.0 * sp.log(small_thr))
x_lo = bisect_left(x, mu - r)
x_hi = bisect_right(x, mu + r)
return slice(x_lo, x_hi) | 5,343,961 |
def preview(delivery_id):
"""
打印预览
:param delivery_id:
:return:
"""
delivery_info = get_delivery_row_by_id(delivery_id)
# 检查资源是否存在
if not delivery_info:
abort(404)
# 检查资源是否删除
if delivery_info.status_delete == STATUS_DEL_OK:
abort(410)
delivery_print_date = ti... | 5,343,962 |
def request_with_json(json_payload):
"""
Load interpolations from the interp service into the DB
"""
test_response = requests.post(INTERP_URL, json=json_payload)
test_response_json = test_response.json()
return test_response_json | 5,343,963 |
def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
... | 5,343,964 |
def cost_zpk_fit(zpk_args, f, x,
error_func=kontrol.core.math.log_mse,
error_func_kwargs={}):
"""The cost function for fitting a frequency series with zero-pole-gain.
Parameters
----------
zpk_args: array
A 1-D list of zeros, poles, and gain.
Zeros and ... | 5,343,965 |
def getTrainPredictions(img,subImgSize,model):
"""Makes a prediction for an image.
Takes an input of any size, crops it to specified size, makes
predictions for each cropped window, and stitches output together.
Parameters
----------
img : np.array (n x m x 3)
Image to be transformed
... | 5,343,966 |
def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in joi... | 5,343,967 |
def _sa_model_info(Model: type, types: AttributeType) -> Mapping[str, AttributeInfo]:
""" Get the full information about the model
This function gets a full, cachable, information about the model's `types` attributes, once.
sa_model_info() can then filter it the way it likes, without polluting the cache.
... | 5,343,968 |
def bll6_models(estimators, cv_search={}, transform_search={}):
"""
Provides good defaults for transform_search to models()
Args:
estimators: list of estimators as accepted by models()
transform_search: optional LeadTransform arguments to override the defaults
"""
cvd = dict(
... | 5,343,969 |
def bgColor(col):
""" Return a background color for a given column title """
# Auto-generated columns
if col in ColumnList._COLUMNS_GEN:
return BG_GEN
# KiCad protected columns
elif col in ColumnList._COLUMNS_PROTECTED:
return BG_KICAD
# Additional user columns
else:
... | 5,343,970 |
def _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):
"""Check that conv shapes are valid and are consistent with window_strides."""
if len(lhs_shape) != len(rhs_shape):
msg = "Arguments to {} must have same rank, got {} and {}."
raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape))... | 5,343,971 |
def merge_hedge_positions(df, hedge):
"""
将一个表中的多条记录进行合并,然后对冲
:param self:
:param df:
:return:
"""
# 临时使用,主要是因为i1709.与i1709一类在分组时会出问题,i1709.是由api中查询得到
if df.empty:
return df
df['Symbol'] = df['InstrumentID']
# 合并
df = df.groupby(by=['Symbol', 'InstrumentID', 'HedgeFla... | 5,343,972 |
def BackwardSubTri(U,y):
"""
usage: x = BackwardSubTri(U,y)
Row-oriented backward substitution to solve the upper-triangular, 'tridiagonal'
linear system
U x = y
This function does not ensure that U has the correct nonzero structure. It does,
however, attempt to catch the case where ... | 5,343,973 |
def discrete_model(parents, lookup_table):
"""
Create CausalAssignmentModel based on a lookup table.
Lookup_table maps inputs values to weigths of the output values
The actual output values are sampled from a discrete distribution
of integers with probability proportional to the weights.
Looku... | 5,343,974 |
def retrieve(datafile, provider):
"""
Retrieve a file from the remote provider
:param datafile:
:param provider:
:return: the path to a temporary file containing the data, or None
"""
r = _connect(provider)
try:
data = base64.b64decode(json.loads(r.get(datafile.storage_key))['da... | 5,343,975 |
def _insert_default_stacors(session,network_code,station_code):
"""
inserts 0. (ml) and 1. (me) corrections for horizontal channels
"""
statement = text("select net, sta, seedchan, location, min(ondate), max(offdate) "
"from channel_data where seedchan in ('SNN', 'SNE', 'BNN', 'BNE',... | 5,343,976 |
def edf_parse_message(EDFFILE):
"""Return message info."""
message = edf_get_event_data(EDFFILE).contents
time = message.sttime
message = string_at(byref(message.message[0]), message.message.contents.len + 1)[2:]
message = message.decode('UTF-8')
return (time, message) | 5,343,977 |
def test_items_is_none_or_empty():
"""
:return:
"""
with pytest.raises(ValueError) as _:
Keyboa(items=list())
with pytest.raises(ValueError) as _:
Keyboa(items=None) | 5,343,978 |
def read_abbrevs_and_add_to_db(abbrevs_path: str,
db: Connection) -> Dict[str, int]:
"""Add abbreviations from `abbrevs_path` to `idx` and `defns`."""
with open(abbrevs_path, 'rt') as ab:
abbrevs = read_abbrevs(ab)
abbrev_nid = add_abbrevs_to_db(abbrevs, db)
loggin... | 5,343,979 |
def is_encrypted(input_file: str) -> bool:
"""Checks if the inputted file is encrypted using PyPDF4 library"""
with open(input_file, 'rb') as pdf_file:
pdf_reader = PdfFileReader(pdf_file, strict=False)
return pdf_reader.isEncrypted | 5,343,980 |
def get_parameter_by_name(device, name):
""" Find the given device's parameter that belongs to the given name """
for i in device.parameters:
if i.original_name == name:
return i
return | 5,343,981 |
def LogPrint(email: str, fileName: str, materialType: str, printWeight: float, printPurpose: str, msdNumber: Optional[str], paymentOwed: bool) -> bool:
"""Logs a print. Returns if the task was successful.
:param email: Email of the user exporting the print.
:param fileName: Name of the file that was export... | 5,343,982 |
def lun_ops() -> None:
"""Interface Operations"""
print()
print("THE FOLLOWING SCRIPT SHOWS LUN OPERATIONS USING REST API PYTHON CLIENT LIBRARY:- ")
print("=================================================================================")
print()
lunbool = input(
"Choose the LUN Operati... | 5,343,983 |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, or editable.
"""
# Remove whitespace at the start/end of the line
line = line.strip()
# Skip blank lines, comments, and editable installs
return not (
... | 5,343,984 |
def print_trajectory_results(alg, results, s, v, out):
"""Prints a formatted version of one repetition of trajectory reconstruction experiments"""
out(f"Algorithm: {alg}")
if alg in ['CRiSP', 'OC_SVM']:
out(f"s: {s}\t v: {v}")
if results['rmse_orientation']:
out(f"\t\tRMSE ori: {results... | 5,343,985 |
def read_pose_txt(pose_txt):
"""
Read the pose txt file and return a 4x4 rigid transformation.
"""
with open(pose_txt, "r") as f:
lines = f.readlines()
pose = np.zeros((4, 4))
for line_idx, line in enumerate(lines):
items = line.split(" ")
for i in range(4... | 5,343,986 |
def gen_new_random_graph(nodecount: int, prob: float) -> None:
"""
Generate a new random graph using binomial generation.
Will save new network to file.
"""
newgraph = nx.binomial_graph(nodecount, prob)
np.save('./test/testnetwork.npy', nx.adjacency_matrix(newgraph).todense()) | 5,343,987 |
def get_futures(race_ids=list(range(1, 13000))):
"""Get Futures for all BikeReg race pages with given race_ids."""
session = FuturesSession(max_workers=8)
return [session.get(f'https://results.bikereg.com/race/{race_id}')
for race_id in race_ids if race_id not in BAD_IDS] | 5,343,988 |
def sum_of_proper_divisors(number: int):
"""
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
:param number:
:return:
"""
divisors = []
for n in range(1, number):
if number % n == 0:
divisors.append(n)
retu... | 5,343,989 |
def coddington_meridional(p, q, theta):
""" return radius of curvature """
f = p * q / (p + q)
R = 2 * f / np.sin(theta)
return R | 5,343,990 |
def read_analysis_file(timestamp=None, filepath=None, data_dict=None,
file_id=None, ana_file=None, close_file=True, mode='r'):
"""
Creates a data_dict from an AnalysisResults file as generated by analysis_v3
:param timestamp: str with a measurement timestamp
:param filepath: (str)... | 5,343,991 |
def get_player_macro_econ_df(rpl: sc2reader.resources.Replay,
pid: int) -> pd.DataFrame:
"""This function organises the records of a player's major
macroeconomic performance indicators.
The function uses a player's PlayerStatsEvents contained in a Replay
object to compose a... | 5,343,992 |
def test_collect_ref_info_return_list():
""" test fields in a reference file """
#GIVEN the variant info fields in input file
valid_variant = "0.00119999998;SNP;p.Glu17Lys"
allele_freq, variant_type, aa_hgvs = valid_variant.split(';')
valid_info_variant = "VARIANT_TYPE=SNP;AA_HGVS=p.Glu17Lys;AF=1e-... | 5,343,993 |
def get_seconds_from_duration(time_str: str) -> int:
"""
This function will convert the TM1 time to seconds
:param time_str: P0DT00H01M43S
:return: int
"""
import re
pattern = re.compile('\w(\d+)\w\w(\d+)\w(\d+)\w(\d+)\w')
matches = pattern.search(time_str)
d, h, m, s = matches.group... | 5,343,994 |
def get_protecteds(object: Object) -> Dictionary:
"""Gets the protected namespaces of an object."""
return object.__protecteds__ | 5,343,995 |
def pah2area(_position, angle, height, shape):
"""Calculates area from position, angle, height depending on shape."""
if shape == "PseudoVoigt":
fwhm = np.tan(angle) * height
area = (height * (fwhm * np.sqrt(np.pi / ln2))
/ (1 + np.sqrt(1 / (np.pi * ln2))))
return area
... | 5,343,996 |
def test_equals_identical():
"""Test comparing an conflict with it self."""
conflict = make_conflict()
assert conflict == conflict | 5,343,997 |
def caching_query_s3(
s3_url: str,
query_fun: Callable,
force_query=False,
df_save_fun: Callable = lambda df, loc: df.to_pickle(loc, compression="gzip"),
df_load_fun: Callable = lambda loc: pd.read_pickle(loc, compression="gzip"),
):
"""
Retrieve cached data if available, query and cache oth... | 5,343,998 |
def config(key, values, axis=None):
"""Class decorator to parameterize the Chainer configuration.
This is a specialized form of `parameterize` decorator to parameterize
the Chainer configuration. For all `time_*` functions and `setup` function
in the class, this decorator wraps the function to be calle... | 5,343,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.