content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def show_function_info(func):
"""関数情報表示用デコレータ関数
:param func: 対象関数
:return: wrappaer関数
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""内部ラッパー関数
"""
print('--------------------------------------------------------------')
print(f'Name: {func.__name__}')
pri... | ac5e4ad9bdb09a9aed02aabae7589dda6b6b2a26 | 3,617,200 |
def datacite_format_contributors(contributors):
""" Format a list of contributors to match the datacite schema
:param contributors_list: list of OSFUsers to format
:return: formatted json for datacite
"""
creators = []
for contributor in contributors:
name_identifiers = [
{
... | 39f8be1e83c5bc0b3fccd568c16206e093878f39 | 3,617,201 |
def get_drought_stress_days(culture_id, trial_dates, climate_data, soilVolume,
availMoistCap, precipitation, irrigation,
stress_threshold=10.0, flowerDate='2012-07-01'):
"""
calculates the number of drought stress days before and after the flowering
da... | bc91a456a8bd28219c8e79d8519e8696be516d54 | 3,617,202 |
import torch
import time
def ppo(env_fn, actor_critic=MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=50, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4,
vf_lr=1e-3, train_pi_iters=80, train_v_iters=80, lam=0.97, max_ep_len=1000,
target_kl=0.01, logger_kwargs=dict(), save_freq=1... | 68d67eb84c013864b218fd5375ab13e557571c07 | 3,617,203 |
def errorhandler(e):
"""Handle error"""
return apology(e.name, e.code) | 5e45b0a36f3d2b1b8c8b87c9e23802c490d73d63 | 3,617,204 |
import os
import json
import time
def start():
"""
Start Quota Manager
"""
first_time = True
automatic_bricks = []
automatic_pass = 0
while True:
brick_path = os.environ.get("BRICK_PATH", None)
if brick_path is not None:
if brick_path.lower() == 'auto':
... | ab132cfc73cadfc7a1ad055b2143f55566a797a1 | 3,617,205 |
from google.colab import output
def _detect_light_colab_theme() -> bool:
"""Detect if it's light theme in Colab."""
try:
get_ipython # type: ignore
except NameError:
return False
ipython = get_ipython() # noqa: F821
if "google.colab" in str(ipython.__class__):
try:
... | e4f2f6096bb65ad6d67accf3f9d4b6130203c93c | 3,617,206 |
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs,
extra_args=None, **argv):
"""Convenience function to execute multiple effect predictions in one call
# Arguments
model: Keras model
ref: Input sequence with the ... | 27c528da568d257d129ae219f504ecf4f23b93f2 | 3,617,207 |
def list_semantic_shift_tokens(snapshot_emb):
"""
Check which tokens have undergone a continuous semantic shift over time (ignoring new words).
Inputs:
- snapshot_emb [dict: {str: SimplePretrainedEmbeddings}]: embedding snapshots for all snapshot dates (as computed with compute_emb_snapshots)
... | 528d0054d152c094ae1f42870cc8499ae39fe44b | 3,617,208 |
from typing import Concatenate
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'):
"""Inception-ResNet block.
"""
if block_type == 'block35':
branch_0 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(branch_1, 32, 3)
bra... | 67f13c601b54f68a4c09366832d68b91c9a22244 | 3,617,209 |
def get_frame_acc(seconds_fr,num_frame,fs,samples_per_channel_in_frame,list_acc_frontiers,acc_time):
"""
Returns the index of the accumulation period corresponding to this frame, the relative number of the frame into the acc period,
and the seconds corresponding to the first sample.
Parameters
... | f829b889f1f42d1cf4184c7c2761bff6a64aec09 | 3,617,210 |
def Search_Form():
"""Render the search form"""
return render_template("search.html") | ce1a6c5c0c6c61fae36b10472f635c2ab7be85d4 | 3,617,211 |
def function_mask_wrapper(func, x0, mask, arg, kwarg, x):
"""
Wrapper function for Python function using a mask.
To be used with partial:
`obj = partial(function_mask_wrapper, func, x0, mask, arg, kwarg)`
This allows then calling obj with only the non-masked parameters:
`fx = obj(x)`
... | da49cbede225ab6b457893a7d5aba6bbe5f06d26 | 3,617,212 |
def filt_velocity_boundary(
x, y, melt=None, blon=186, blat=-82.68, dlon=13, dlat=0.06, return_index=False
):
"""
params for 3km grid: blon=186, blat=-82.68, dlon=13, dlat=0.06
"""
X, Y = np.meshgrid(x, y)
lon, lat = transform_coord(3031, 4326, X, Y)
lon[lon < 0] += 360
(ii, jj) = np.whe... | 3dea3c764f07cef71f151b860b0739bfe6e7f41f | 3,617,213 |
def generateRules(L, supportData, minConf=0.7):
"""
Generate rules of (k)-itemset implied by (k-1)-itemset
:param L: list of all Lk
:param supportData: dict of support data value
:param minConf: minimum confidence of rule interested in
:return: list of all the rules implied by L
"""
rule... | a0d4a1e0d36f7e7bb5ef6efe2577926394ea255b | 3,617,214 |
def get_pronoun(pronoun, gender='MALE', sep='_'):
""" Gets the correct gender pronoun
Arguments:
pronoun {str} -- HE_SHE pronoun that needs to be converted
Keyword Arguments:
gender {str} -- [description] (default: {'MALE'})
sep {str} -- [description] (default: {'_'})
... | a9f3d7aa3f09af305ac110e1cc8c9ac977051d8b | 3,617,215 |
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) and callable(obj.compute) | 18f1825947852f6dd307e0a2ab07c8d95f213151 | 3,617,216 |
def addstr(str1, str2):
"""Concatenate strings str1 & str2"""
return str(str1) + str(str2) | 209c932bca262a458013afcafd6899e6cf02b3b6 | 3,617,217 |
def ampfitfn1_1d(coeffs,x):
""" PN inspired ampitude fit a0 + a1*nu**a2"""
a0, a1, a2 = coeffs[:3]
nu = gwtools.q_to_nu(x)
return a0 + a1*nu**a2 | 0894211f617746aaddcc0e8975495969204ef817 | 3,617,218 |
def Ve_correct(Ve, Ig, Ic, Rprotect):
"""Because we use a resistor connected in a serries on the emitter circuit
in order to stabilize emission current, we need to correct voltage dropping
at the resistor, which is called as "Protection Resistor" or somthing like that.
Inputs -- Ve, Ig, Ic, Rprotect
... | 377122accd5cb173daef7487abfdbf86353a7819 | 3,617,219 |
from typing import Tuple
from typing import List
from typing import Optional
import os
def plot(
data: DataSetProtocol, save_pdf: bool = True, save_png: bool = True
) -> Tuple[
DataSetProtocol,
List[matplotlib.axes.Axes],
List[Optional[matplotlib.colorbar.Colorbar]],
]:
"""
The utility functio... | 4f67b01992cd1363a7c624651a2e72e25678f9a9 | 3,617,220 |
def getSph2CartTransfArr(r):
"""(Array version) Compute the transformation matrix from a spherical basis to a Cartesian
basis at the field point given by the input 'r'.
The output 'transf_sph2cart' is defined such that:
[[v_x], [v_y], [v_z]]=transf_sph2cart*matrix([[v_r], [v_phi], [v_theta]])."""
... | e46efc25cd733bd49b6cf18add85754107263d2f | 3,617,221 |
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title):
"""
Visualize the Pauli Transfer Matrix of a process.
:param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix
:param ax: The matplotlib axes.
:param labels: The labels for the operator basis states.
:param title: The ti... | 1dc8d7ff2ef85d66d7718e38993f3f0625b8f160 | 3,617,222 |
def group_anagrams1(words : list[str]) -> list[str]:
"""
O(N logN ) solution.
Args:
words (list[str]): words
Returns:
list[str]: sorted by anagrams
"""
def get_word_value(word):
value = 0
for letter in word.lower():
if letter == ' ': c... | d55679c1d04f18ae29daade739e97bed98e9fc40 | 3,617,223 |
def create_camera_ray_frame(K, T, size=0.1, color=[0, 0, 1]):
"""
K: 3x3
T: 4x4
"""
T, K, color = np.asarray(T), np.asarray(K), np.asarray(color)
sanity.assert_T(T)
sanity.assert_K(K)
sanity.assert_shape_3(color, "color")
# Pick 4 corner points
# Assumes that the camera offset i... | a8695c502a43d16b7ed4b6e151e45fa269e2a02d | 3,617,224 |
import difflib
def get_name_similarities(name_pairs):
"""Get char LCS similarity for each signature pair."""
return [difflib.SequenceMatcher(None, sig1, sig2).ratio() for sig1, sig2 in name_pairs] | a124e36387d4a72968985967fde0c48dc4d3b21d | 3,617,225 |
import subprocess
def run_cmd(cmd_args, cwd=None, shell=False):
"""Runs a command and returns output as a string."""
process = subprocess.Popen(
cmd_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd)
output = process.communicat... | 792d966bffac12aada63e5c36795cd7043ead4ec | 3,617,226 |
def _get_resource_image_registry_namespace(resource_type):
"""
Get image_registry_namespace by resource type.
:param resource_type: Type of resource (job, function, model, stream)
:return: str default name prefix by resource type when resource type is defined, else None
"""
if... | e0aa13acf0f12e12593a7cda3e6239bb17190519 | 3,617,227 |
import ast
from typing import List
from typing import Tuple
def _get_sim203(node: ast.UnaryOp) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls where an unary 'not' is used for an in-check.
"""
errors: List[Tuple[int, int, str]] = []
if (
not isinstance(node.op, ast.Not)
... | c4577fac32d4b3bd88092464ea993aa4cd5d02ea | 3,617,228 |
def _get_key_and_value(field_string):
""" Extracts the key and value from a Java Thrift field string.
For example: "ids:[1,2,3]" --> "ids", [1,2,3]
:param field_string: the Java Thrift field string
:type field_string: str
:returns: a tuple of key and value of the represented field
:rtype: tupl... | be87277bc5dadb49ecb82d217d7774102a4b3296 | 3,617,229 |
import sys
def extract_ut_args():
"""Extract unittest specific arguments from sys.argv"""
# -h -v -q -f -c -b
# --locals
# anything not starting with a -
newargs = []
for i in range(1, len(sys.argv)): # must ignore progname in argv[0]
arg = sys.argv[i]
if arg in ["-h", "-v", "... | a899dee319466e9e91c727f00be6f7a130127c8f | 3,617,230 |
def RemoveOutliers( array, max_deviations ):
"""
Function used to remove outliers from an array.
Args:
array (numpy.array): the interested array.
max_deviations (int): the maximum number of std.
Returns:
numpy.array: the array without outliers.
Testing:
>>>... | 5c123104b6fe337e967196407c82d24d637472b5 | 3,617,231 |
def to_spark(spark_session):
"""Convert pandas df to spark."""
def _(df: pd.DataFrame, *args, **kwargs):
return spark_session.createDataFrame(df, *args, **kwargs)
return _ | 04b4045f01dc0cc84f62df64e62627ea87e23138 | 3,617,232 |
def nonconserved_bond_stereo_keys(ste_tsg, check=True):
""" Determine bond stereo centers which are not conserved by the reaction.
This includes bonds which are stereogenic for the products but not for the
reactants ("created" stereo centers) and bonds which are stereogenic for
the reactants but not fo... | 3138553045dc4cbc00fd696b58cc59478b895f82 | 3,617,233 |
from typing import Optional
import warnings
def build_bucket_table(
X: pd.DataFrame,
y: np.ndarray,
column: str,
bucketer=None,
bucket_mapping: Optional[BucketMapping] = None,
epsilon=0.00001,
display_missing=True,
verbose=False,
) -> pd.DataFrame:
"""
Calculates summary statis... | be08401ff999b27303e7dc2e092928189d08e27e | 3,617,234 |
def available_classifier_paths(*restrictions):
"""Returns all classifier paths with given restrictions.
Args:
restrictions: Strings that should be included in the paths as :class:`str`.
Returns:
The path of the classifiers as :class:`list` of :class:`pathlib.Path`.
"""
paths = list... | 0a40adcdbd57e4c9eb361b21389059484bbffbee | 3,617,235 |
def createHTMLTable(matrix, batches, groups, caption=None, base_indent=8, indent=4, column_labels=None, skip_base_column=False):
"""
Givena a matrix, and a suitable column and row names, create an HTML table of the data
values in the matrix.
"""
if column_labels is None:
column_labels = {}
... | cf814a21c21276481ac14db87129206cb72aaf91 | 3,617,236 |
from typing import Union
from typing import List
from typing import Iterable
def get_matched_headers(
headers: CaseInsensitiveDict, match_headers: Union[ParamList, bool]
) -> List[str]:
"""Get only the headers we should match against as a list of ``k=v`` strings, given an optional
include list.
"""
... | 4a0efbf77e808827dd44b6abe4a9e1f90fb86cc3 | 3,617,237 |
def parse_predictions_dict(predictions, num_growths):
"""Parses predictions dictionary to remove graph generated suffixes.
Args:
predictions: dict, predictions dictionary directly from SavedModel
inference call.
num_growths: int, number of model growths contained in export.
Ret... | fbb1789cf317e7c4d0015271bf8690ea4bddf0ef | 3,617,238 |
def normalized(a, axis=-1, order=2):
"""Utility function to normalize the rows of a numpy array."""
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis) | 69530dab7190dd35a132cbf398abf668d854e62e | 3,617,239 |
import os
def get_audio_sentiment_analysis(audio_filename:str):
"""
A function to get sentiment/emotion analysis from the audio
"""
audio = AudioSegment.from_file(audio_filename, "wav")
chunk_length_ms = 4000
chunks = make_chunks(audio, chunk_length_ms)
#Export all of the individual chunk... | 1bfaf5f6af1079af41e9b73202cb439c78abc73b | 3,617,240 |
import os
def create_idx_to_path(lfw_dir):
"""
Create a dictionary where the key is the image index and the value is the
path to the image.
"""
labels = sorted(os.listdir(lfw_dir))
idx = 0
idx_to_path = {}
for label in labels:
for img in sorted(os.listdir(os.path.join(lfw_dir, ... | 7e9e475a04c04637902103f7ba4e7cc181d8ab88 | 3,617,241 |
import pathlib
def allowed_task_name(name: str) -> bool:
"""Determine whether a task, which is a 'non-core-OSCAL activity/directory is allowed.
args:
name: the task name which is assumed may take the form of a relative path for task/subtasks.
Returns:
Whether the task name is allowed or ... | 11d1a65ef21439919e728557e72af9ae6e22dc94 | 3,617,242 |
import subprocess
def create_movie(name, folder):
"""
Creates the movie with all the images present in the given directory
:param name:
:param folder:
:return: result of subprocess
"""
cmd = ["ffmpeg", "-framerate", "1", "-i", folder + "/pic%04d.png", "-c:v",
"libx264", "-r", "3... | 392f5b88d1da63ad241402e313ab8f601ebe997c | 3,617,243 |
async def get_run_command(
commandId: str,
engine_store: EngineStore = Depends(get_engine_store),
run: Run = Depends(get_run_data_from_url),
) -> PydanticResponse[SimpleBody[pe_commands.Command]]:
"""Get a specific command from a run.
Arguments:
commandId: Command identifier, pulled from ro... | f09dc35f1bef2701f4c4065da6c297122d229022 | 3,617,244 |
def is_fully_paid(cart: Cart, taxes, discounts):
"""Check if checkout is fully paid."""
payments = [
payment for payment in cart.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
cart_total = cart.get_total(discounts=discounts, taxes=taxes).gross.amount
retur... | c6fb68ddc65462a7fb6d8b7ed2b263d973a5e8f7 | 3,617,245 |
def rescale_bbox(annot: namedtuple) -> namedtuple:
"""Return rescaled coordinates of bbox in the image size.
YOLO requires the bounding box coordinates should be
(relative_center_x, relative_center_y, relative_w, relative_h)
:param namedtuple annot: holds each vertex absoulte positions.
:ret... | 476117ebe8650c12819e8887f173fc06b04b3551 | 3,617,246 |
def uu_get_price():
"""
(可拿到当天数据)
获取股票历史交易数据,可以通过参数设置获取日k线、分钟k线数据。获取数据的基本属性如下
:param :security: 一支股票代码或者一个股票代码的list
start_date: 字符串或者[datetime.datetime]/[datetime.date]对象, 开始时间, 默认是’2015-01-01’. 注意:
当取分钟数据时, 时间可以精确到分钟, 比如: 传入 datetime.datetime(2015, 1, 1, 10, 0, 0) 或者 '2015-01-01... | c2b9af1352edda21c542ec9476102eac5d70c49f | 3,617,247 |
def profile_article(document):
"""
Temporary, profile the article by folder names in test data set
In real code we still want this to return the same values
"""
soup = parser.parse_document(document)
# elife id / doi id / manuscript id
fid = parser.doi(soup).split(".")[-1]
# volume
... | 12904080aecae79f37bbef8db38ee23a11ae2a44 | 3,617,248 |
def get_distribution(dataframe, target_column):
"""
method to find the distribution of a certain column in a given dataframe.
Shows the generated visualization to the user.
:param dataframe:
:param target_column: column upon which the distribution needs to be applied
:return: dictionary of uniqu... | 65b71aa375bb7b1ca4af6ddd03322cdd672e98d0 | 3,617,249 |
from typing import Union
def high_pass_2_pole(candles: np.ndarray, period: int = 48, source_type: str = "close", sequential: bool = False) -> \
Union[
float, np.ndarray]:
"""
(2 pole) high-pass filter indicator by John F. Ehlers
:param candles: np.ndarray
:param period: int - defa... | ec2765b8537f1fb47c52d2f82946c05514191505 | 3,617,250 |
import pandas as pd
import os
def twins(path):
"""data from Exercise 7.14, p225
The `twins` data frame has 24 rows and 3 columns.
This data frame contains the following columns:
id
Twin number
age
Age of twin's death from CHD, months
death
Death (male twin) from CHD indicator (1=dea... | b44a081b0ff685238678653ded3bbf0079b09a65 | 3,617,251 |
def watchlist(request, listing_id):
"""Add on watch list, when watch list button is click"""
if request.method == "POST":
listing = get_object_or_404(Listing, pk=listing_id)
request.user.watch_listing.add(listing)
return HttpResponseRedirect(reverse("watchlist_view"))
return render(r... | c0912735510b18741646db491248a7201c439e0b | 3,617,252 |
def stat(hdfs_url):
"""
stat the hdfs URL, return None if does not exist.
Returns a dictionary with keys
filename: base name of file
blocks: number of blocks
block_size: size of each block
mod_date: last modification
replication: number of copies in hdfs
"""
... | 76edcdb4dac9646f7c790df69fd9e5e8c0a4c02b | 3,617,253 |
def lerp(a, b, x):
"""Linear interpolation."""
return a + x * (b - a) | 6f82114a774ed4e9c8da90649fe0c67c996754bb | 3,617,254 |
from typing import List
def create_feeds(length: int = 10) -> List[Feed]:
"""
Generate list of dummy feeds
:param length: length of list
:return: list of dummy feeds
"""
return rands(Feed, length) | fe26576c2c3f5df1942593bdef767a217c03ada0 | 3,617,255 |
async def handle_hid_event(event: mdl.HidEvent = Depends(identify_sender)) -> mdl.GenericResponse:
"""Parse the event dict JSON"""
try:
if event.name == "rfid_reader":
logger.debug(f"Handling RFID event. String: {event.string}")
if WORKBENCH.employee is not None:
... | c1375dbfd24e6560c2b73021004fbee4782c5748 | 3,617,256 |
import json
def render_template(handler):
"""Render a set of templates against a dataframe and formhandler actions on it."""
orgdf = get_original_df(handler)
payload = json.loads(handler.request.body.decode('utf8'))
fh_args = payload['args']
templates = payload['template']
df = pd.DataFrame.fr... | 17fea9d133b18f50d18e9ae738c9d5c95b160a48 | 3,617,257 |
def logbeta(*args):
"""
Log multivariate beta function.
args
----
*args : arguments
returns
-------
float
"""
return loggamma(args).sum() - loggamma(sum(args)) | 1c8e93906fed2421c63289a883aca7baa6e4cf3c | 3,617,258 |
def a3() -> rank.Arborescence:
"""Get the third SA of case in [camerini1980ranking]."""
g = nx.DiGraph()
g.add_edge("b1", "b4", label="e2", weight=1)
g.add_edge("b3", "b2", label="e4", weight=10)
g.add_edge("b4", "b3", label="e6", weight=8)
res = rank.Arborescence(g)
return res | 8456001acd74d62d812362ccd2ada3869ac62661 | 3,617,259 |
import socket
import time
def connect_forwarder(forward_host=None,
forward_port=None,
max_retries=-1,
sleep_interval=1.0):
"""connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the for... | 9e4e14f3d3d26c78fcc32b2090611815e2dc84d6 | 3,617,260 |
import torch
def _softmax(x, implicit=False):
"""Safe softmax (with implicit class)"""
if implicit:
x = _pad_zero(x)
x = torch.softmax(x, dim=1)
return x | f79c556b9910a96a615b3533d365639fca4f5b6c | 3,617,261 |
def get_word_pattern(word: str) -> str:
""" Get word pattern.
This pattern is useful to break substitution cipher.
:param word: Word to get pattern for.
:return: Word pattern.
"""
# There is no ordered set type in Python, but we can get that behaviour using
# dict keys because since python... | ce81624bd3690c2037c5b570e19ba2340907a24a | 3,617,262 |
import requests
def check_matcher_data_is_loaded(response: requests.Response) -> bool:
""" Check that the matcher data is loaded """
try:
assert ('results' in response.json())
logger.debug('Matcher seems healthy')
return True
except Exception:
logger.debug('Matcher does not... | ec380003a9dd71e9b7da70093e6a3b851e3269f4 | 3,617,263 |
def noll_to_zern(j):
"""
Convert from linear Noll index to a tuple of Zernike indicies.
:param int j: Linear Noll Index
"""
if (j < 0):
raise ValueError("Noll indices start at 0. j={:d}".format(j))
n = np.ceil((-3 + np.sqrt(9 + 8*j))/2)
m = 2*j - n*(n+2)
if not int... | 4006426f5d367318c1ab5256e5882fa8198a348d | 3,617,264 |
import time
def print_menu(main_list_of_contacts, p_id_number_itterate): # this takes as a parameter "main_list_of_contacts", which is an instance of the class ContactList.
"""The main interface where the user interacts with their contact list. Allowable actions are add, edit, delete, or list."""
user_selec... | 786366840992a01980f48c1a8337a268d522011b | 3,617,265 |
def LF_radiograph_view(c):
"""
Check if the term view occurs between the pain and anatomy mentions
in a candidate
:param c: pain-anatomy candidate
:return: -1 if True, 0 otherwise
"""
between_tokens = list(get_between_tokens(c))
between_phrase = ' '.join(between_tokens)
v = 'view'... | 9f7b8bd027945ddc1a3b1127edb54c0702cc7405 | 3,617,266 |
def compute_centroids(x_mat: ndarray, idx_vec: ndarray):
"""
根据之前的聚类中心下标和样本,计算移动后的平均聚类中心值。
:param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数
:param idx_vec: 聚类中心下标
:return: 新的聚类中心
"""
x_mat = __t.r2m(x_mat)
idx_vec = __t.c2r(idx_vec)
m, n = x_mat.shape
k = np.max(idx_vec) + 1
cent... | 5a6b059738e4364c7dbc5821c6d01dcea6e99158 | 3,617,267 |
def R_hill2(rho_p, P,e=0):
"""
compute hill radius of a planet from its density rho_p in g/cm3 and period in days.
Returns
--------
R-hill: array-like;
radius of hill sphere in unit of planetary radius
"""
G = 498.23383
return (1-e)*(G*rho_p*P**2/(9*np.pi))**(1/3) | 467ea02f4ad21afbeb28dd4dd209c30ce9a750d5 | 3,617,268 |
def dir_checked():
"""The absolute path of the checked homeworks.
This path is valid on the storer machine."""
return abspath('checked') | 52fdfcdf55860cd7bb1ee325384f2c60d6c258a7 | 3,617,269 |
def color_diff(rgb1, rgb2):
"""
Calculate distance between two RGB colors. See discussion:
http://stackoverflow.com/questions/8863810/python-find-similar-colors-best-way
- for basic / fast calculations, you can use dE76 but beware of its problems
- for graphics arts use we recommend dE94 and perha... | 056f0354d102802f612e3fa090df45d7d2d9e1b4 | 3,617,270 |
def clientid_to_accountid(clientid):
"""
Transform Clientid To Accountid
Parameters:
clientid : int
Returns:
None
"""
for i in _ba.get_game_roster():
if i['client_id'] == clientid:
return i['account_id']
return None | 4ee4ffe92fedf078b73138b4d7382982ef4459eb | 3,617,271 |
def get_cube(ds, edge_um=1000, lev=0, center_yt=None):
"""
Extract a cube of raw data from 3D FLASH yt dataset.
Uses yt's "covering grid" method to ensure losslessness.
Replaces get_magnetic_field. This will take the center, edge length,
AMR Level, and data set, and it will return a co... | efd286d8b0b80976f2f6a8a15e343459b94577aa | 3,617,272 |
def tf2ss(sys_):
"""
Convert transfer function model to state space model.
:param sys_: the system
:type sys_: TransferFunction
:return: corresponded transfer function model
:rtype: StateSpace
"""
try:
nump = np.poly1d(sys_.num)
denp = np.poly1d(sys_.den)
except Att... | 7296d5896ff55402c7cb9aa4bfc2262be86a0823 | 3,617,273 |
def get_c_phi(rule,parses,psg,bigrams=None,start='S'):
"""wrapper
Arguments
rule : (lhs,rhs)
parses : list of (operation string, bigram string) pairs
psg : operations PSG
bigrams: bigram markhov chain
start : start category
"""
# get the charts and bigrams from the parses
... | d8e9d6b4b454e9304572920b5c5032e3a8927992 | 3,617,274 |
def softmax_2D(x, use_float64=False):
"""Compute softmax values for each row in x.
Parameters:
-----------
x: a 2D matrix
each row represents a set of entries over which a softmax
should be applied
Returns:
-------
normalized softmax entries, where each row is normalized usin... | e8d221a7073e1902d521cea3555f981176b2a665 | 3,617,275 |
def _run_op_1(task):
"""Test function using the function decorator."""
return task.run() | b2d3b220dcd1371f9140859b4ffe025f8231b4da | 3,617,276 |
import numpy
import sys
def make_dtopo_from_subfaults(subfaults, dtopo_params):
"""
Create a dtopo file named *fname* based on applying the Okada
model to each of the subfaults specified in the list *subfaults*.
This should be a list of dictionaries that specify the necessary
Okada parameter... | 067a0ee3c95ae07c0a53919bd6a9a336fe87f0a7 | 3,617,277 |
from typing import Type
from typing import Optional
from typing import Union
def _wrap(
native_estimator: Type[T_NativeEstimator] = None,
*,
name: Optional[str] = None,
base_wrapper: Optional[Type[EstimatorWrapperDF[T_NativeEstimator]]] = None,
native_estimator_bound: Optional[type] = None,
ba... | a056b5f6a5509354e9b56b8837f700548d171bd3 | 3,617,278 |
import typing
def create_local_gateway_routes_for_peers(
client: VNS3Client, local_network: str, peer_ips: typing.List[str]
):
"""Create route to local underlay gateway for IPs. This is commonly done for explicit routes
to VNS3 peers.
Arguments:
client {VNS3Client}
local_network {s... | 0a24202f6f38b5577be12b12afeb2efa48499e76 | 3,617,279 |
def bagnet9(**kwargs):
"""
BagNet-9 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
... | 83c9eaaee3100fc54c369958d70aa9d19bd6ba53 | 3,617,280 |
def create_df(dass_words, dfcp_words):
"""
this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context
it returns this dictionary
"""
dass = {}
dfcp = {}
data = [dass, dfcp]
for listed_values in dass_words: # access single lis... | 43e5715808247d726a353e7841a5dbc2aa117740 | 3,617,281 |
import string
def t(message):
"""Replace $country and $language in message with dat from settings"""
tpl = string.Template(message)
return tpl.substitute(country=settings.COUNTRY_NAME, language=settings.LANGUAGE_NAME) | 6e9464ebaa915e15420499768f40199a9abc57c5 | 3,617,282 |
def login_handler(fn):
"""
A decorator to redirect users to AWS Cognito login if they aren't already.
If already logged in user will redirect redirect uri.
Use this decorator on the login endpoint.
This handle will not return to handle the respose rather redirect to
redirect uri.
"""
@wr... | f9a84963b50314f4b37c5fc7bf295cd8074b5a89 | 3,617,283 |
def launch(tenant, addrs=DEFAULT_ADDRESS, period=DEFAULT_PERIOD):
""" Initialize the module. """
return RSSITracker(tenant, addrs=addrs, every=period) | 8784326a2083cc12247183de5f5d1e7327cfc821 | 3,617,284 |
import inspect
def register(cls_obj=None, encode=None, decode=None):
"""Register a serializer class.
By default the serializer will use the class type "__getstate__" and "__setstate__" methods if an encode and decode
method is not given.
Args:
cls_obj (class/type): Class/Type/object to regis... | 273868278a777299c4362c30278669b19ee9b6fd | 3,617,285 |
def random_resize(image, min_image_size, max_image_size, max_out_prob=0.,
resize_method=tf.image.ResizeMethod.BILINEAR):
"""Randomly resize the image while preserving aspect ratio.
Args:
image: 3D image tensor.
min_image_size: minimum size for the longer side of the image.
max_image_s... | 2afcbcff8dcaa2514b8b1fe464ab0182603e51ed | 3,617,286 |
def broyden_class_update(y, s, mat, phi=0.0):
"""
Scale free implementation of the broyden class update scheme.
:param y:
difference in gradient
:param s:
search direction in previous step
:param mat:
current hessian approximation
:param phi:
convex combination p... | e1ee7f0eab5a05e3867f367ff305a743f742377c | 3,617,287 |
def resolve_jobs(job_counts, start, length):
"""
:param job_counts: list of blocks(queue, registry, job_count)
:param start: job start index for datatables
:param length: number of jobs to be returned for datatables
:return: list of jobs of len <= "length"
It may happen during processing some j... | 436314b4370806b7f172e0f02ef28a5af0a72104 | 3,617,288 |
def star(x, y, points=20, outer=100, inner=50, **kwargs):
""" Draws a star with the given points, outer radius and inner radius.
The current stroke, strokewidth and fill color are applied.
This is about 20x slower than fast_star; use it only if you need the path returned.
"""
p = BezierPath(... | 44d361471df0f920978914aba2190cf17155aec9 | 3,617,289 |
def q_in_valid_range(q):
"""
Asserts that q is either 1, 2 or 3.
For other values, the formulas have not been implemented.
"""
assert 1 <= q <= 3, "Please enter q in {1,2,3}"
return True | 6ef79efde7376f0743bc840fe394707a8f9b213f | 3,617,290 |
import hashlib
def sha512_first_half(message: bytes) -> bytes:
"""
Returns the first 32 bytes of SHA-512 hash of message.
Args:
message: Bytes input to hash.
Returns:
The first 32 bytes of SHA-512 hash of message.
"""
return hashlib.sha512(message).digest()[:32] | 591a0096e643af32326ae051f9a993db82a758c5 | 3,617,291 |
def find_svc_icon(id):
"""
Locate the absolute path of an ICON for a AWS service.
:type id: str
:param id: service id, for main service it is ``ec2``, for sub service it is
``ec2-instances``
:rtype: str
"""
if id in svc_icon_mapper:
return Icons.abspath(svc_icon_mapper[id])... | 542ff27cc154d9843b2a1df16d77b18c8a420539 | 3,617,292 |
import re
def order_parquet_files_into_batches(parquet_files):
"""
Order the parquet files by searching for a digit within their name.
Returns the parquet files without their numbering or extension.
Parameters
----------
parquet_files : List
List of parquet files to be ordered.
""... | 0d748c5ae50ef49ba98386ee172db0e850a8b9a8 | 3,617,293 |
def get_xml_temperature (root):
"""
Get the temperature from the unit diagnostics XML.
Parameters:
root -- An XML element to the root of the unit diagnostics.
Return:
The system temperature or -1 if the temperature redaing isn't valid.
"""
if (get_xml_string_va... | d2490b6b5f6df63943c042255b7aa0776baa1a72 | 3,617,294 |
def median(arr: list):
"""
Returns the median and its index in the array.
"""
indices = []
list_size = len(arr)
median = 0
if list_size % 2 == 0:
indices.append(int(list_size / 2) - 1) # -1 because index starts from 0
indices.append(int(list_size / 2))
median = (arr... | 639a6d4efbc91457520ef1411ef7b935fb477b82 | 3,617,295 |
from typing import Callable
from typing import Tuple
from typing import List
def _sample_many(
logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]],
model_ndim: int,
draws: int,
tune: int,
chain: int,
chains: int,
start: list,
random_seed: list,
step,
discard_... | f57540009b58f68f6c8ec33073258ca2f47f747f | 3,617,296 |
import itertools
def plot_confusion_matrix(cm, classes, title="Матрица ошибок", cmap=plt.cm.winter):
"""
Визуализация матрицы ошибок с помощью Matplotlib
cm - матрица ошибок
cmap - стиль оформления
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title, fontsize=30)
plt... | c0c39d27d05232c10a8b6e8e99036e73285073a0 | 3,617,297 |
from typing import Union
import random
import string
def add_nonce_func(
string_array: Union[str, int, float, np.array]
) -> Union[str, int, float, np.array]:
"""
Add random prefix and suffix to an array of strings ``string_array``
This function takes an array of strings passed as ``string_array`` an... | ba72b29c878681c0b70be549a6f1effa83748cfa | 3,617,298 |
import copy
def rename_block_mesh(block_mesh_template_path, foam_files_templates):
"""rename the template to blockMeshDict, and leave in the templates folder for now.
Args:
block_mesh_template_path (str): full path of edited blockmesh template.
Returns:
blockMeshDict_for_run (str): rename... | 768a9b6bb051771548c7ee4443b3d9491170c1a0 | 3,617,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.