content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pdb(coords, types, a, b, c, alpha, beta, gamma, model=1):
"""
Return string in the protein databank atomic structure format.
Arguments:
coords[i, j] (float): j-th Cartesian coordinate of the i-th atom
types[i] (str): chemical symbol of atom i
a, b, c (float): lenghts of the three latt... | 7bb69e717c14e1a272321f0247d833f4ca9f8405 | 635,825 |
import os
def overrides_file(base_package, args):
""" Find the location of the hook. """
while True:
result = args.hook_file
if result is not None:
break
result = os.path.abspath(
os.path.join(base_package, 'overrides.py'))
if os.path.exists(result):
... | e4e26360ad61e19d558db7ad6c53bf84ad4a7058 | 635,826 |
def test_fact_active(constant_dict, constants, predicate, relationships):
"""Given relationships, determine whether the truth value of a fact could be predicted by a relationship"""
if predicate in relationships:
if all(body_pred in constant_dict[constants] for body_pred in relationships[predicate]):
... | b0ec0bff9c446e554c2aedd39e80c36139e108b5 | 635,827 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
divlist = []
counter = 0
for item in range(1, num + 1):
if num % item == 0:
divlist.append(item)
counter = count... | d904273e6e988f8643f39a1fcf45ad9f2699a87a | 635,828 |
def CARAutility_invP(u, alpha):
"""
Evaluates the derivative of inverse of constant absolute risk aversion (CARA)
utility function at utility level u given risk aversion parameter alpha.
Parameters
----------
u: float
Utility value
alpha: float
Risk aversion
Returns
... | df6f7e5cf65eb5876c26d54f2c8926780a0b53e5 | 635,829 |
def firstNotNone(*args):
"""
Returns first not-None value from a given list of arguments
>>> firstNotNone(None, None, 1, 2, 3)
1
"""
retVal = None
for _ in args:
if _ is not None:
retVal = _
break
return retVal | 450f927a62a460bd26206a44c9bd64d82c9e5666 | 635,832 |
def carry_around_add(a, b):
"""
дополняющая сумма
:param a: первое слагаемое
:param b: второе слагаемое
:return: дополняющая сумма a и b
"""
c = a + b
return (c & 0xFFFF) + (c >> 16) | 2ee8182a7217e8e8a95f6d986dbd6d5781712b30 | 635,833 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Tuple
def _get_target_principal_and_delegates(
impersonation_chain: Optional[Union[str, Sequence[str]]] = None
) -> Tuple[Optional[str], Optional[Sequence[str]]]:
"""
Analyze contents of impersonation_chain... | 87fb76f10568b22115a1f671da28d4d35ae947da | 635,834 |
def mean(array):
"""
Returns the mean (average) of a numpy array
:param array: A one dimensional numpy array
"""
return float(sum(array) / max(len(array), 1)) | 43517e91ae838357c5df3a3dc5798825c4c02bde | 635,835 |
def should_quit(string_given) -> bool:
"""
This function determines if the string_given should exit
:param string_given:
:return: Returns if the string is 'q' or 'quit'
"""
return string_given in ['q', 'quit'] | 53ef5055ea4271934962afcb7b27e5eb47c1616b | 635,836 |
def linked_embeddings_name(channel_id):
"""Returns the name of the linked embedding matrix for some channel ID."""
return 'linked_embedding_matrix_%d' % channel_id | da3a095d86add49741fcb15f28059c124e6e7916 | 635,838 |
import os
def get_ext(filepath):
"""Returns the extension from a filepath"""
return os.path.splitext(filepath)[1] | 5cf46221530a28973a4e70195b255da877015735 | 635,839 |
def update_counter(network,
update_deltas,
name,
shape=(),
default_inits=None):
"""
stores and updates a counter
"""
new_name = "counter(%s)" % name
if default_inits is None:
default_inits = []
old = network.crea... | a84dd59e1bbfab1662f525eb09a6fa3ce9105851 | 635,840 |
def hamming_weight(number):
"""Returns the number of bits set in number"""
return bin(number).count("1") | e0be33c5ad03b4a6d8329a680cf6cf56e19ce857 | 635,841 |
def search_for_vertex_at_pos(chromosome, position, location_dict):
""" Given a chromosome and a position (1-based), this function queries the
location dict to determine whether a vertex
fitting those criteria exists. Returns the row if yes, and __ if no.
"""
try:
return location_di... | 38f77b0cbfeb2548908fab6142ebc1b348e1b06b | 635,842 |
import hashlib
def sha256sum(file: str) -> str:
"""
Returns the sha256 sum of a file
:param file: (str) path to file
:return: (str) checksum
"""
sha256 = hashlib.sha256()
try:
with open(file, "rb") as file_handle:
while True:
data = file_handle.read(65... | f2fc1f36faea123fc59e1f7289816dcb9bc731c4 | 635,843 |
async def get_information():
"""
Get this resource to obtain mission debrief
"""
return {
"message": f"Welcome Collector. "
f"Your purpose is collect. Have them all."
f"And have them all logically. "
f"Use every method at your fingertips t... | be464b18474262c42705badfc376da6ad070d638 | 635,844 |
def crop_torch_image(img, d=32):
"""
Make dimensions divisible by d
image is [1, 3, W, H] or [3, W, H]
:param pil img:
:param d:
:return:
"""
new_size = (img.shape[-2] - img.shape[-2] % d,
img.shape[-1] - img.shape[-1] % d)
pad = ((img.shape[-2] - new_size[-2]) // 2, ... | 32e694f3393da91318288eaa03f6df04706701e4 | 635,845 |
import time
def mod_bot_display(bot_dictionary):
"""Function that takes data from mod_bot_comparator and
displays it in a comprehensive Markdown table.
"""
formatted_lines = []
line_format = "| u/{} | {:.2f} | {:,} | {} | {:.2%} | {:,} | {:,} | {:,} | {} |"
# Format each line of the table.
... | 295566b1e477849a4c0d91734d97539da4f033cc | 635,846 |
def add_user_defined_feature(df, features):
"""Append 'user-defined-feature' to the data frame"""
# Fetch data frame
x = df.copy()
# ====>
"""
x["daily_return"] = df.cloase.pct_change(1)
"""
# <====
return x | 25ada0cf635858c3fbcef4d3f71e416ed64a42c3 | 635,847 |
def scatter_geo(ds, prop="pressure", stat="count"):
"""
Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
... | 8ad34b181df030d370a2014846f53a29b4b1496b | 635,848 |
def nice_number(number, lang='', speech=True, denominators=None):
"""Format a float to human readable functions
This function formats a float to human understandable functions. Like
4.5 becomes 4 and a half for speech and 4 1/2 for text
Args:
number (int or float): the float to format
l... | c62b8617d1f0c0f42a68e860f50b2bcb30cc3d1b | 635,849 |
def error_page_404(status, message, traceback, version):
"""
Display an error if the page does not exists
"""
return "Error %s - This page does not exist." % status | 125963abeeaf927067188324ff551925f3a0cd39 | 635,850 |
import torch
def code_proj(init_pt, m, attr_index, logit=None):
"""Unconditional projection
"""
c = init_pt
if logit is not None:
pred = logit
else:
pred = m(c)
grad = torch.autograd.grad(pred[:, attr_index], c)[0]
grad = grad/(torch.norm(grad, p=2, dim=1)+1e-9)
re... | a577bc212079913486b3a5de0771f767dba1b369 | 635,851 |
def compare_rows(row_check, dataframe_check, drop_column="idx"):
"""Find all the matched rows in dataframe_check given a row to check (row_check)"""
# all(1) means that all items of row_check should match with
# rows in dataframe_check except for drop_column
dataframe_matched = dataframe_check[(datafram... | 54c7aca6985d83685b7c205fbeb8ccd5e2861cf0 | 635,852 |
def search_cord_start(xy_cord):
"""
Find at the index of the coordinate corresponding
to the coordinate -11.810 cm in order to exclude
the doses at positions at which there are no detectors
"""
for idx in range(len(xy_cord)):
if abs(xy_cord[idx] + 11.810) < 0.01:
return idx | 0d787c66693a46b68bb400ed32c5fa7d966d8b98 | 635,853 |
from typing import Set
from typing import Tuple
def rotate_90(state: Set[Tuple[int, int]], origin: Tuple[int, int], additive: bool=False) -> Set[Tuple[int, int]]:
""" Rotate the object 90 degrees to the left with respect to the provide origin
:param state: original state
:param origin: The point of the r... | 0926de03d36a591c853e0c8ea593fd68ce7f439c | 635,854 |
import os
import requests
def _getSteamInfo(steamId):
"""
Takes a steamId and returns info about the steam user.
Returns None if the request fails, the user doesn't exist, or if the
response is malformed.
"""
options = {'key': os.environ.get('BB_STEAM_API_KEY'),
'steamids':... | 59d86edcf7b3ca7b575d1c487ea6872ed08de150 | 635,855 |
def joinInterfaces(into, merge):
""" Merges the first interface into the second.
"""
result = False
for mc in merge.calls:
for c in [c for c in into.calls if c.name == mc.name]:
if len(mc.args) != len(c.args):
continue
if c.args == mc.args:
... | 23047a78273c1c12747324b40a73792c6a26cd5b | 635,856 |
def get_trid_isrc_full_con(tr_id, tr_exc, exid2next_dic, nexts_cisrc_dic):
"""
Get intron-spanning read count for transcript with ID tr_id. Also return
if transcript exons are fully connected by intron-spanning reads
(True, False).
tr_id:
Transcript ID
tr_exc:
Transcript exon c... | 3efc5d16e95b4cd98924e25a166b8793df4ae42e | 635,857 |
import json
def dna_from_json(filename=None, file_path=None):
"""
This function loads the DNA sequence from a .json file. if both filename
and path are provided for file, then path is preferred.
:param filename: filename(string) e.g., filename.mat. Looked in
default folder 'dataset/'
:param pa... | db6e2d66ded2e47bd52815a85f937f5a47cf988e | 635,858 |
def aic_scorer(estimator, X, y_true = None) -> float:
"""AIC score for Gaussian Mixture Model Metric
can be used in GridSearch for hyperparameter tuning
:param estimator: must have ``aic`` method which returns aic score
:param X:
:param y_true:
:return: the protocol requires greater the better,... | 1a7a96cd57176992cc032d75a12fc662fa67f66b | 635,860 |
async def read_body(receive):
"""
Read and return the entire body from an incoming ASGI message.
"""
body = b''
more_body = True
while more_body:
message = await receive()
body += message.get('body', b'')
more_body = message.get('more_body', False)
return body | 7a45893cc2ff66a4266af158b9c556b55093d1ff | 635,861 |
def inInfo(item,info,alt='None'):
"""
Checks if item is in given list.
return item if true, else return alt
Args:
item: the item to be compared
info: the list to be checked
alt: alternative output
"""
if item in info:
return info[item]
... | 135b91e25f060e137f6340ff95c0435b8d881d0b | 635,862 |
import re
def extract_features_for_clustering(text):
"""
Extracts the presence of specific word phrase features that are used to
determine the overall structure of the document.
:param text: original report in str form
:return: feature vector
"""
key_phrases = [
'Electronically sig... | 9c5805e7f788b5cefc92364d45b62edfb2b80e4d | 635,863 |
def executeScriptToGetData():
""" Simulate some actions for text tile exemple"""
return {
"items":
["Leader: 5",
"Product Owner: 0",
"Scrum Master: 3",
"Developer: 0"]
} | b23f19866dc6e709244f65f4b56abded4f732a12 | 635,864 |
def _process_pmid(s: str) -> str:
"""Process provenance column."""
if not s.startswith('pubmed:'):
raise ValueError(f'Non pubmed: {s}')
return s[len('pubmed:')] | fe7a694e85edddbb03d064792c415b16ea8e6d81 | 635,865 |
def create_edge_str(source_id, target_id):
"""Creates edge for the GML file
:param source_id: The id of the source node
:param target_id: The id of the target node
"""
edge_str = "\tedge\n\t[\n\t\tsource " + str(source_id) + "\n"
edge_str += "\t\ttarget " + str(target_id) + "\n\t]\n"
re... | 62871deaa08d6a1d34cb925ac48d9dc705788fbe | 635,866 |
import json
def map_category_names(cat_to_name:str, classes:list) -> list:
"""Map category labels to category names
Args:
cat_to_name: Path to JSON file with category to name mapping
classes: list of predicted classes
Returns:
List of category names
"""
with open(cat_to_n... | bbe9ddfebc4a138ab4d3378275a7559bf6eac70d | 635,867 |
def query_chips_dict(ibs, *args, **kwargs):
"""
Runs query_chips, but returns a json compatible dictionary
RESTful:
Method: GET
URL: /api/query/chip/dict/
"""
kwargs['return_cm_dict'] = True
return ibs.query_chips(*args, **kwargs) | 03925523ac478d5052ce5d0baa0df9bf04d21e88 | 635,868 |
def multiply(string, times):
"""
Repeats a string a given number of times.
:param str string: given string
:param number times: number of repeats
:return str: repeated string
"""
return string * times | dc1df8534d5be18eda66c18e6f005538e42b2078 | 635,869 |
import threading
def RLock():
"""
Make the container thread safe if running in a threaded context.
"""
return threading.RLock() | 52438e37130876a03124e5befa9a4fd4a42a2ed9 | 635,870 |
import re
def extract_dependencies(content):
"""Extract dependencies by parsing import statements"""
deps = set()
for line in content.split('\n'):
line = line.strip() # we don't care about indentation
if not (line.startswith("from") or
line.startswith("import")):
... | 39799fa79a30768f4751a0cbc39dadd812d7f893 | 635,871 |
def check_program(pred, gt):
"""Check if the input programs matches"""
# ground truth programs have a start token as the first entry
for i in range(len(pred)):
if pred[i] != gt[i+1]:
return False
if pred[i] == 2:
break
return True | 93c5abf959e1d01790cb7d363778e20959623786 | 635,872 |
import re
def is_non_legacy_callback_interface_from_idl(file_contents):
"""Returns True if the specified IDL is a non-legacy callback interface."""
match = re.search(r'callback\s+interface\s+\w+\s*{', file_contents)
# Having constants means it's a legacy callback interface.
# https://heycam.github.io/... | e31a64864631741266d24bb2441eae6b44a01000 | 635,873 |
def dict_from_str(s):
"""Convert 'key:value, ...' string to dict."""
d = {}
for item in s.split(','):
key, value = item.split(':')
d[key.strip()] = value.strip()
return d | cce94e0b934ae6ac3ebef3b7ea402b8eddd28477 | 635,874 |
import time
def rest(seconds: int) -> int:
"""Rest function."""
# can't use f-strings with mypy checking: https://github.com/python/mypy/issues/2265
print("starting rest {seconds}".format(seconds=seconds))
time.sleep(seconds)
print("ending rest {seconds}".format(seconds=seconds))
return second... | 3e987b4619c239fe56b4e1be2bdfe7cc658e7ece | 635,875 |
import os
def ensure_path(path):
"""Ensures the path exists.
:param path: the path to validate.
:type path: ``str``.
:return: the same path.
:rtype: ``str``.
"""
if not os.path.exists(path):
os.makedirs(path)
return path | 9c7d1f83fb5d2b89d161b615915c9ac2007b443c | 635,876 |
def node_dict(nodes):
"""
:param nodes:
:return: dict of frozenset(labels) to list(nodes)
"""
d = {}
for node in nodes:
key = frozenset(node.labels)
d.setdefault(key, []).append(node)
return d | f41b67cf4ba0959787e6b1e16e81a2a79d1ee81e | 635,878 |
import json
def import_hyperparams(hyperparams_file) -> dict:
"""
Import hyperparameters of an ae from json file.
@model_path :: String of the path to a trained pytorch model folder
to import hyperparameters from the json file inside
that folder.
returns :: Impor... | a5f0b0f85b96801cf00b282094372c3532fbb024 | 635,879 |
def rxxr(factor: float = 1) -> float:
"""
The horizontal width of the mounting rail in a
10-inch or 19-inch rack.
"""
return 15.875 * factor | 5e42cceb128fcee1b7971bf3c401a3320c396d24 | 635,880 |
import torch
def convert_mortality_data(train_dict, test=False):
"""Converts mortality data dictionary with keys ("train", "test") or just
("test") for testing only when train == False.
"""
#Hack for now
if "test_x" in train_dict.keys():
if test == False:
train_dict["train_x"]... | 78c9035b437c85eeacc50911c45bab3b72f48776 | 635,881 |
from typing import List
def word_block(text: str, blocked_words: List[str], replace: str = '****') -> str:
"""Replace blocked words in text."""
tmp_string: str = text
for word in blocked_words:
if word in tmp_string:
tmp_string = tmp_string.replace(word, replace)
return tmp_string | edf68c58ee462a23d4a518f71a1a61fbb3f5e5a4 | 635,882 |
import os
import json
import tempfile
import sys
def load_prophyle_conf(globconf, json_strs):
"""Loads configuration from a JSON string or a file.
The strings are first merged. If the string corresponds to a file,
it is loaded. Otherwise it is interpreted as a json string
(possibly without wrapping b... | 0a9dcdf5147d4f0159a8ddf230d7a51b2c8b833e | 635,883 |
from typing import Tuple
from typing import Counter
def generate_checksum_components(box: str) -> Tuple[int, int]:
"""
Generates the checksum components from the string and returns a tuple
indicating whether a character appeared twice or thrice in string. For
example a (1, 1) would indicate that at le... | bcd50361ad37a4973925ea7edb15a4903f619912 | 635,884 |
def identity(label):
"""Identity function that returns the input label.
Args:
label: A `Tensor` or anything that can be converted to a tensor using
`tf.convert_to_tensor`.
Returns:
The input label.
"""
return label | 4a2f09b14510353d419ea2986043bc95cbff76da | 635,885 |
def _is_currency(shape):
""" Check if this shape represents a Currency question; a 'ROUND_RECTANGLE' """
return shape.get('shapeType') == 'ROUND_RECTANGLE' | fb40d48c23be5918a7f06568f928e3620adf8487 | 635,886 |
import torch
def smooth_l1_loss(input, target, beta=1. / 9, size_average=False):
"""Smmoth L1 loss, as defined in the Fast R-CNN paper.
Girshick, R. (2015). Fast R-CNN.
"""
diff = torch.abs(input - target)
mask = (diff < beta)
loss = torch.where(mask, 0.5 * diff ** 2 / beta, diff - 0.5 * b... | a5a23f07235a650ddadb16e94644708fcc7c2548 | 635,887 |
def _inherit(cls, attributeName, tree, interfaces):
"""Lookup the parents to inherit their interfaces."""
try:
cls_parent = tree.pop(0)[0]
if hasattr(cls_parent, attributeName):
for interface in getattr(cls_parent, attributeName):
if interface not in interfaces:
... | c7c7c872847c8ef4c77c815973792227fdcbf1da | 635,888 |
import os
def get_filename(session: int,
person: int,
frame: int,
crop_type: str = 'body',
directory='/tmp2/ashesh/gaze360_data/imgs'):
"""
For session=22,person=0 and frame = 131,
example of filename: '/tmp2/ashesh/gaze360_data/imgs/rec_... | 27f6093647c0de571d9b1a7dcf1e899704166dfb | 635,890 |
import argparse
def make_base_parser():
"""Initiates a CL parser with base arguments used by standalone program and other calling modules"""
parser = argparse.ArgumentParser(description='''Character-based difference
highlighting and scoring, based on loose differences. By default, just print the docum... | 4736872765ea2c0c876a93b59c6c4f5865dc0958 | 635,891 |
import torch
def predict_rating(review, classifier, vectorizer,
decision_threshold=0.5):
"""
Predict the rating of a given review
:param review (str): the text to review
:param classifier (ReviewClassifier): the trained model
:param vectorizer (ReviewVectorizer): The correspo... | 3b7efa77ed64b44b31b87d9587d413726ed05308 | 635,892 |
from typing import OrderedDict
def secondary_settings(structure,form,primary_settings):
"""Return secondary settings, along with sensible default values.
Secondary settings depend on the structure, form,
and possibly primary setting values.
Primary settings are defined by xrsdkit.definitions.structur... | b1d42a6eaf68eee38e1448c6c2bd913df22cbef0 | 635,893 |
import json
def jsonify(obj):
"""Return Python objects as JSON (in bytes)."""
jsonified = "{}".format(json.dumps(obj)).encode()
return jsonified | 2bf3d52554665011863d60f04437ca9d3b52eb6d | 635,894 |
import pickle
def read_local_variables_and_params(arguments):
"""
Read other variables and params.
"""
l_vars, dataset_parameters = pickle.load(
open(arguments['<data_directory>'] + 'local_variables.pickle', 'rb'))
#pylint: disable=too-many-instance-attributes,too-few-public-methods
c... | 090bf8e86d48111d8b53d916f751ee2b253d9190 | 635,895 |
def expected_utility(a, s, U, mdp):
"""The expected utility of doing a in state s, according to the MDP and U."""
return sum(p * U[s1] for (p, s1) in mdp.T(s, a)) | 429e1c8e162206e558b5c61b676bf034dffe5440 | 635,898 |
import uuid
def load_table(service, source_schema, source_csv,
projectId, datasetId, tableId, num_retries=5):
"""
Starts a job to load a bigquery table from CSV
Args:
service: an initialized and authorized bigquery
google-api-client object
source_schema: a valid big... | 11f3a7cbbfbd30e48fe167c9b0bb4f0aae8a80f2 | 635,899 |
def ro_worker_name():
""" Fixture to share ro Orders worker name
"""
return 'ro-worker' | bdd190a892f3cae25348ccb099c947c08ef910ed | 635,900 |
def is_name(text):
"""
Checks if text sounds like a name or abbreviation (title or upper case).
:param text: the text to check.
:return: True if it might be a name.
"""
return text.istitle() or text.isupper() | 9704ee763c43dbc26cff97b547b5ee6d1a55771b | 635,901 |
def nodes_iter(topology):
"""Get an iterator for all nodes in the topology"""
return topology.nodes_iter() | 66613676ae76d1705c9a45eeb336862d99df2ebe | 635,902 |
def vac_to_air_apogee(vac_wvs, a=0.0, b1=5.792105e-2, b2=1.67917e-3, c1=238.0185, c2=57.362):
"""
converts vaccuum wavelengths in angstroms to air wavelengths.
the default constants are those suggested by APOGEE.
"""
#assume that the vac_wvs are provided in angstroms
#micron_wvs = vac_wvs/10**4
... | b282f47da1f04fffd90bd01ee39483152cc7707f | 635,903 |
def indent(text, prefix=" "):
"""
Return `text` indented using `prefix`.
"""
return "\n".join(prefix + repr(line) for line in text.splitlines()) | 7417aa0fcdfd1e8bb056b4b8d6ccd32a462551c4 | 635,904 |
def deploy_plugin(request):
"""
Deploy a plugin on a machine.
Deploy a plugin on the specific machine.
READ permission required on cloud.
EDIT_CUSTOM_METRICS required on machine.
---
cloud:
in: path
required: true
type: string
machine:
in: path
required: tru... | a28e70bdbc41f143f1e860ff1e9ef46ce7aaa003 | 635,907 |
import re
def split_config(log_config):
"""
splits log config into the config name and its arguments
This is not fully implemented. it will split on ' ' or
on ':' depending what occurs first
"""
splitvals = re.split(r'(?:\s+|:)', log_config, 1)
if len(splitvals) == 2:
... | 47682db5cef8e0cd9e975c7d15f2fb1aab0bed02 | 635,908 |
def heegner_index_work(E):
"""
Prepare the input and output for computing the heegner index.
INPUT:
- ``E`` -- an elliptic curve
OUTPUT:
- a Heegner index
- the discriminant used
EXAMPLES::
sage: from sage.schemes.elliptic_curves.BSD import heegner_index_work
sage:... | 37e33929a50ebeb651e07ce3dea55a60efd844f7 | 635,909 |
def format_number(num):
"""Format a number in a string.
>>> format_number(1234567) -> '1 234 567'
>>> format_number(1234.56789) -> '1 234.56' # round with 2 decimals
>>> format_number(None) -> '???'
>>> format_number('not a number') -> 'not a number'"""
if isinstance(num, int):
return f"... | cc7972959f9c0f26a907e91d7342a24465bee3e9 | 635,910 |
def pressure_plane_strain_R_disp(r, p, ri, ro, E, nu, dT, alpha):
"""
Assumption of plane strain (axial strain = 0)
"""
A = ri**2 * ro**2 * -p / (ro**2 - ri**2)
C = p * ri**2 / (ro**2 - ri**2)
u = (-A*nu - A + C*r**2*(-2*nu**2 - nu + 1))/(E*r)
return u | 3e2004f3de184822d0f263ad4bb5f914372630e3 | 635,911 |
from typing import OrderedDict
def remove_repeated_elements(tokens):
""" removes repeated tokens
args:
tokens: a list of tokens
returns:
filtered_tokens: a list of tokens without repeated tokens
"""
filtered_tokens = list(OrderedDict((token, None) for token in tokens))
return f... | b7dd36ea222c29fcbb2bfcc6fe0b0d1150755db5 | 635,912 |
import torch
def gradient_retriever(model):
"""fn to retrieve gradients from model
:param model: torch model
:returns: gradient norm, gradient tensor
:rtype: (float, tensor)
"""
grads = []
grad_norm = 0
for p in model.parameters():
grads.append(p.grad.clone())
grad_no... | 4e60b7746538fdb2e1b52fdaf2ea246cf07f421e | 635,913 |
def alpha (v, dt, dx):
"""
Calculate Courant number, alpha = v*dt/dx.
For 2D, this function can be used if dx=xz
"""
return (v*dt/dx) | 6cde4bb1a7d96a297648f881b44d7c07d2d204f9 | 635,914 |
import numpy
def calc_rotation_matrix_ij_by_euler_angles(alpha, beta, gamma):
"""Calculate rotational matrix from Euler angle.
Tait-Bryan convection for angles is used.
psi - x-axis
theta - y axis
phi - z axis
0 <= psi <= 2 pi ???
-pi/2 <= theta <= pi/2
0 <= phi <= 2 pi
... | 711e62f84001a5f2e61887bec76731a00d4f2c15 | 635,915 |
def get_model_form_field(model, name, formfield_callback=None, **kwargs):
"""
Utility to create the formfield from a model field.
When a field is not editable, a ``None`` will be returned.
"""
field = model._meta.get_field_by_name(name)[0]
if not field.editable: # see fields_for_model() logic i... | 936edc77e50b584d22ef52a678ba6dab717aeab2 | 635,917 |
def funct_worker(input_list,pre_text):
"""
Worker Function: define function that each process should do
e.g. create string from content in input_list while begin with pre_text => "[pre_text] [input_list]
"""
output_string = f"{pre_text}"
output_string = output_string + " ".join(input_list)
... | e28c0bb9d07d6df7c0d88b11869fa58f098825cd | 635,918 |
def _models_count_all_function_name(model):
"""Returns the name of the function get the number of models in the database"""
return '{}_count_all'.format(model.get_table_name()) | 22ea542e640e1b53fefe22d467c2dd852203b8a9 | 635,919 |
def add_weeks_to_range(topic_weeks_range):
"""
Accepts range of weeks for specific topic, returns dictionary of this range size that maps week days.
"""
weeks = [
'الأسبوع الأول',
'الأسبوع الثاني',
'الأسبوع الثالث',
'الأسبوع الرابع',
'الأسبوع الخامس',
'الأ... | 75ee99f12e325f1734466759d92f8e3628a7a364 | 635,920 |
def tleft(fn, lo, hi):
"""
fn の結果が最も小さくなるインデックスを三分探索する
:param callable fn:
:param int lo: 最小のインデックス
:param int hi: 最大のインデックス + 1
:return: lo <= ret < hi
"""
left = lo
right = hi
while abs(right - left) >= 3:
r1 = (left * 2 + right) // 3
r2 = (left + right * 2) // ... | c58af8f6d38fcc59a5dbdd5960899144d967c054 | 635,922 |
def user_input(prompt, lower=True):
""" User input string for python independent version """
r = input(prompt)
return r.lower() if lower else r | 8ad250f6cd8f90770572439fa0566686302d2a59 | 635,923 |
import os
def index_filename_for_xtc(xtcfile):
"""
Get the filename for the index file of a xtc file.
In general, the index file is located in the same directory as the xtc file.
If the xtc file is located in a read-only directory (for the current user)
and does not exist, the index file will be ... | f15c98ca4f01d013b0d54eb8d8cd1ddeb60eb297 | 635,924 |
def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh):
"""Applies no answer threshhold"""
new_scores = {}
for qid, s in scores.items():
pred_na = na_probs[qid] > na_prob_thresh
if pred_na:
new_scores[qid] = float(not qid_to_has_ans[qid])
else:
... | ef38ddb6fead9791e3ceeefc90fe022e6a6031c1 | 635,925 |
def cut_file(source_file, aim_path, chunk_size):
"""
this function will take a source file, cut it into pieces with chunk size
store them to the aim path
return a list of cut names
"""
ori_bin = open(source_file, 'rb')
chunk_list = []
while True:
cur_bin = ori_bin.read(chunk_size... | a3128fccc389da9bae9ccd6cc2b3454fa6505db7 | 635,926 |
def is_datetime(input):
"""
Template tag to check if input is Datetime
:param input: Input field
:return: True if is datetime, False if not
"""
return input.field.widget.__class__.__name__ == "DateTimeInput" | 1b9016a90c363fb9c4a5ce9c180635db3223f5ed | 635,927 |
import numpy
def assert_equivalent_snapshots(gsd_snap, hoomd_snap):
"""This is the same as the function in test_simulation.
Except that if a prop is None in the gsd_snap, it instead checks that the
array or list is empty in the hoomd_snap additionally it handles the
differences in the way the two sna... | e56defea95ac0b5a1c83be165f87c0a5237ce699 | 635,928 |
def weighted_mid_price(book):
""" weighted mid """
bids,asks = book['bids'],book['asks']
#asks.reverse()
level = 0
bp = bids[level]['price']
ap = asks[level]['price']
bq = bids[level]['price']
aq = asks[level]['price']
tq = bq + aq
bf = bq/tq
af = aq/tq
wmid = bp * bf + a... | 405250b4000360f599128562fe83a4e0cb8f6aac | 635,930 |
def isEqualVirtualHost(first, second) -> bool:
"""
Checks that two VirtualHost objects are similar. There are some built
in differences with the implementations: VirtualHost created by ParserNode
implementation doesn't have "path" defined, as it was used for Augeas path
and that cannot obviously be ... | bc0830398b62cf6fbcf0a21f993a26986b1f5f93 | 635,931 |
import math
def get_biorhythms(days_elapsed: int):
"""바이오리듬을 반환합니다.
Args:
days_elapsed: 출생일로부터의 경과일
Returns:
바이오리듬(신체, 감성, 지성)의 튜플
"""
def biovalue(circle, elaspeddays):
"""바이오리듬 값(%)"""
return math.sin(2 * math.pi * elaspeddays / circle) * 100
physical = bi... | 5f284903d38d2e83595a488cda92194b4b6c8005 | 635,932 |
def seq_for_table_attr(table, attribute, offset, seq_for, table_config):
"""Generate or update sequence numbers for each attribute that has a sequence
>>> table_config = {'calls': {'attrs': {'id': {'seq': {'start': 300}}}}}
>>> seq_for_table_attr('calls', 'id', 200, {}, table_config)
(500, {'calls': {'... | 08d69058da15aa5dfe56413f995d10d684518d1a | 635,934 |
def convert_tokens_to_ids_and_pad(word_pieces, max_length, token_converter):
"""Converts the input tokens to padded ids and mask.
Args:
word_pieces: list of word-piece tokens.
max_length: length sequences should be padded/truncated to.
token_converter: the tokenizer used.
Returns:
word_piece_id... | 86e220c621bec1d2adbe1b865c61a54cb9e6f06c | 635,935 |
def get_screen(img, nscreens, screenidx):
"""extract screen from image"""
width, height = img.size
width_per_screen = int(width/nscreens)
left = int(width_per_screen*screenidx)
right = left + width_per_screen
top, bottom = 0, height
screenimg = img.crop((left,top,right,bottom))
return screenimg | f50bb4ec46cbf05e0cd1c2931d32f4985950836c | 635,936 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
# local variables
zero_shift = []
number_merge = []
result = []
blank = 0
cache = 0
# initializing blank list
for idx in range(len(line)):
number_merge.append(0)
# shifting zeroes in i... | 24057ed3dac00c8a20042c0457ee5d3cd3d607cd | 635,937 |
def fsextract(string,method):
"""
Extracts the indices or filenames from a comma-separated string
Input Parameters
----------------
string : str
a comma separated string of either file names or file index numbers.
method : {'index','filename'}
'index' if the values passed are ... | 5236976a196c727eb6c9e5e888bafd4973fa0b9f | 635,939 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.