content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _normalize_newlines(text: str) -> str:
"""Normalizes the newlines in a string to use \n (instead of \r or \r\n).
:param text: the text to normalize the newlines in
:return: the text with the newlines normalized
"""
return "\n".join(text.splitlines()) | 6b53b42e8cec72a8e63ec0065776f47de2fba835 | 3,616,819 |
def getAxlib(libPath=None):
"""Return the handle to the axon library (CLibrary instance).
If libPath is specified, then it must give the location of the AxMultiClampMsg.dll
file that should be loaded. Otherwise, a predefined set of paths will be searched.
Note: if you want to specify the DLL file usin... | 365cd4a57036cc936b27030c2c07bec36c48a171 | 3,616,820 |
def create_stanford_article_level_model(rnn_type, embedding_matrix, sentence_size, hidden_size, dense_size, trainable=False, use_dropout=True, dropout=0.5):
"""
Create RNN model
:param rnn_type:
:param hidden_size:
:param dense_size:
:return:
"""
# Model
model = Sequential()
# E... | e611441a5c8c14ce23425bba03fb1078be13debc | 3,616,821 |
def read_words(f, count=100, encoding="utf-8"):
"""Reads the given number of words from the specified open file."""
result = []
while len(result) < count:
line = wrapped_readline(f, encoding=encoding).strip()
words = [w.strip() for w in line.split(" ")]
# remove empty words
w... | 2d6d2a5cd086e1ccdb4ba3035f660597e098e62b | 3,616,823 |
def create_tvshow_tiles_content(tvshows):
""" The HTML content for this section of the page
"""
content = ''
for tvshow in tvshows:
# Extract the youtube ID from the url
youtube_id_match = re.search(r'(?<=v=)[^&#]+', tvshow.trailer_youtube_url)
youtube_id_match = youtube_id_match... | 9bfe36740497f70e37ad525cb0fefe06180ea419 | 3,616,824 |
def pick_from_greatests(dictionary, wobble):
"""
Picks the left- or rightmost positions of the greatests list in a window
determined by the wobble size. Whether the left or the rightmost positions
are desired can be set by the user, and the list is ordered accordingly.
"""
previous = -100
is... | 52685877620ab7f58a27eb6997ec25f3b499e3a4 | 3,616,825 |
def replace_layer(model, layer_name, replace_fn):
"""Replace single layer in a (possibly nested) torch.nn.Module using `replace_fn`.
Given a module `model` and a layer specified by `layer_name` replace the layer using
`new_layer = replace_fn(old_layer)`. Here `layer_name` is a list of strings, each string
... | 2e0ee082d6ab8b48979aa49e303a0e12583812b7 | 3,616,827 |
def create_html_output(json_docs):
"""Create html output for the playbook by converting the docs to markdown and then converting to html."""
markdown_docs = create_markdown_output(json_docs)
return markdown.markdown(markdown_docs) | 0c59d85a06a9d8c842eaee16ec5b50dd5a7507b4 | 3,616,828 |
def has_name_pf(name_p, ignore_case=True):
"""
Predicate factory, returns true if the element name matches the pred parameter
* **name_p**: something that can be converted into a string compare predicate
* **ignore_case**: should the comparison be case sensitive (default: ignore case)
* **return**:... | 0392820f5ec7f0540f0eb4f0fbff1f9bf00bd28f | 3,616,829 |
def genInvSBox( SBox ):
"""
genInvSBox - generates inverse of an SBox.
Args:
SBox: The SBox to generate the inverse.
Returns:
The inverse SBox.
"""
InvSBox = [0]*0x100
for i in range(0x100):
InvSBox[ SBox[i] ] = i
return InvSBox | 8ddf7e338e914f6cb6c309dc25705601326160c0 | 3,616,830 |
def get_unassigned(values:dict, unassigned:dict):
"""
Select Unassigned Variable
It uses minimum remaining values MRV and degree as heuristics
returns a tuple of:
unassigned key and a list of the possible values
e.g. ('a1', [1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
values_sort = dict() # em... | 32ff78f7a6443bfbf4406c420ba87e254e88d5c3 | 3,616,831 |
def countvec():
"""
对文本进行特征值化
:return: None
"""
# 实例化CountVectorizer
vector = CountVectorizer()
# 调用fit_transform输入并转换数据
# res = vector.fit_transform(["life is short,i like python","life is too long, i dislike python"])
res = vector.fit_transform(["人生苦短,我喜欢python","人生漫长,不用python"])... | c0756a9a072296e6d78001deb55d51cc9de5bf15 | 3,616,832 |
def get_auth_token_ssh(account, signature, appid, ip=None):
"""
Authenticate a Rucio account temporarily via SSH key exchange.
The token lifetime is 1 hour.
:param account: Account identifier as a string.
:param signature: Response to challenge token signed with SSH private key as a base64 encoded... | 5ca3b104b0b84bfdbd0df16e349325835970667f | 3,616,833 |
def is_superset_of(value, superset):
"""Check if a variable is a superset."""
return set(value) <= set(superset) | 8b40089430dedef72566e93eb551b35001ec2e96 | 3,616,834 |
import requests
def _poll_for_status(client_id, device_code):
"""Polls API to see if user entered the device code
This is the second step of the Device Flow. Returns an access token, and
also writes the token to a file in the user's home directory.
"""
header = {"Content-Type": "application/json... | 698e21be730a767f604a8be07d73799d8658f028 | 3,616,835 |
from datetime import datetime
def datetime_to_year(dt: datetime) -> float:
"""
Convert a DateTime instance to decimal year
For example, 1/7/2010 would be approximately 2010.5
:param dt: The datetime instance to convert
:return: Equivalent decimal year
"""
# By Luke Davis from https://st... | 5f4ae29d57d13a344e70016ab59dbc0a619db4d8 | 3,616,836 |
def are_adjacent_empty(positions, seats):
"""Check if all seats from the positions are not OCCUPIED."""
return all(
seat != OCCUPIED
for seat in get_seats(positions, seats)
) | 9c14377a658ffd2d6ba04780fd2f407e1d338feb | 3,616,838 |
def one_component_ejecta_relation(time, redshift, mass_1, mass_2,
lambda_1, lambda_2, kappa, **kwargs):
"""
Assumes no velocity projection in the ejecta velocity ejecta relation
:param time: observer frame time in days
:param redshift: redshift
:param mass_1: mass ... | 8a4317b0fa7e33e269c4a17e74b711755a5d452b | 3,616,839 |
import json
def uhs500_msg_parsed() -> Message:
"""Expected :class:`~tslumd.messages.Message` object
matching data from :func:`uhs500_msg_bytes`
"""
data = json.loads(MESSAGE_JSON.read_text())
data['scontrol'] = b''
displays = []
for disp in data['displays']:
for key in ['rh_tally'... | 15a45da5809d29184456959adffbdbbef311c33b | 3,616,840 |
from typing import List
def brute_force_matchings(graph: Graph, partial_matchings: List[Matching]) -> List[Matching]:
"""Recursive algorithm for brute force maximum matching search"""
if len(graph.get_edges()) == 0:
return partial_matchings
updated_matchings = []
for edge in graph.get_edges():... | 3f2bb71a70f2883821b48d69b1128a8f795f9242 | 3,616,841 |
def status_check(request):
"""
JSON response for health checks.
"""
# because the argument is framework we will ignore
# pylint: disable=unused-argument
resp = {'status': 'up'}
return JsonResponse(resp) | ead0070f454b3233a9f3deb3092feae19de19c5f | 3,616,842 |
def ek_R56Q(cell):
"""
Returns the R56Q reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -96.0,
2: -95.0,
3: -90.5,
4: -94.5,
5: -94.5,
6: -101.0
}
return reversal_potentials[cell] | a61d33426e4c14147677c29b8e37381981f0d1db | 3,616,843 |
def _get_schema(cur: pyodbc.Cursor, table_name: str):
"""Get schema and table name - returned as tuple
"""
t_spl = table_name.split(".")
if len(t_spl) > 1:
return t_spl[0], ".".join(t_spl[1:])
else:
return _get_default_schema(cur), table_name | 84f25b43f1f1c0707725c2ec64540f1f1348e427 | 3,616,844 |
def poincare_tiling(p, q, nlayers, center):
"""
produce poincare regular tiling
p : number of edges per face
q : number of faces meeting at a vertex
nlayers : number of layers or rings of faces
"""
max_faces = count_faces(p, q, nlayers)
edges_out = []
verts_out = []
faces_out =... | cce0fb8f5f0d12e8fbdb524129e960ce1705f974 | 3,616,845 |
def magenta_on_white(string, *funcs, **additional):
"""Text color - magenta on background color - white. (see sgr_combiner())."""
return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_WHITE,)) | 53c230bc90442749c5d372f2a50ebf5154e6d90c | 3,616,846 |
import six
import re
def build(directory, name):
"""
Build an image using a Dockerfile at a specific path using the full name to
tag the resulting image.
Arguments:
directory (str): The directory containing the Dockerfile for the
distribution.
name (str): The full name of ... | f5699d7ca0ce4f8d5e7de7ded4e2f30d29a70dc5 | 3,616,847 |
def deriv_activation_func(func_type, z):
"""
Implements the different kind of derivated activation functions including:
line - linear function
sigm - sigmoidal
tanh - hyperbolic tangent
ptanh - smothly hyperbolic tangent
relu - Rectfied
step - Heavside (binary ste... | 1d18fe4df9ca7ef63f381581f466450355d20607 | 3,616,849 |
def createStringMacroseismicHeader(header):
"""
Function that creates NordicMacroseismic list with values being strings
:param str header: string from where the data is parsed from
:return: NordicMacroseismic object with list of values parsed from header
"""
nordic_macroseismic = [None]*22
... | 2d651e77ed0abc56116178afbab01cdb35088d18 | 3,616,850 |
def code_search(ea, val):
"""Search forward for the next occurance of val. Return None if no match."""
res = idc.FindBinary(ea, idc.SEARCH_DOWN, val)
if res == idaapi.BADADDR:
return None
else:
return res | 14b1ca9156bd081c289e78d3145ed7cb947f79c9 | 3,616,851 |
def buffer_input(data, buffer, input_data):
"""Repeats last search with 'input_data' as regexp."""
try:
cmd_grep_stop(buffer, input_data)
except:
return WEECHAT_RC_OK
if input_data in ('q', 'Q'):
weechat.buffer_close(buffer)
return weechat.WEECHAT_RC_OK
global search... | 51999ff6ed463b0033cc3e3ab19951199b4d7945 | 3,616,852 |
def read_input_files(input_file: str) -> list[Seat]:
"""
Extracts a list of valid passwords from the input file.
"""
with open(input_file) as input_fobj:
seats = [Seat.from_binary_partition(line.strip()) for line in input_fobj]
return seats | d56c78c330be9189e83dcb1cbb3baf690d806529 | 3,616,853 |
import re
import json
def mediapackage_channel_mediapackage_endpoint_ddb_items():
"""
Identify and format MediaPackage channel to MediaPackage endpoint connections for cache storage.
"""
items = []
package_key = re.compile("^(.+)Package$")
try:
# get mediapackage channels
media... | da94679df115fda6fc2dbb30e739b921f681afd4 | 3,616,854 |
def reinsert_star(seq, gapped_seq):
"""
Reinserts '*' at end of gapped alignment to make finding the end of
the aligned portion more accurate
"""
length = len(seq)
count = 0
for i in range(len(gapped_seq)):
if gapped_seq[i] == seq[count] and count == 0:
start = i
... | f4ef9428f023d655f43ca50582d3af61bddfe27e | 3,616,855 |
def _functional_groups_stable(geo, thy_save_fs, mod_thy_info):
""" look for functional group attachments that could cause
molecule instabilities
"""
# Initialize empty set of product graphs
prd_gras = ()
# Check for instability causing functional groups
gra = automol.geom.graph(geo)
... | 6f826ccf1f551f775b5bb61b8e5157e73724363a | 3,616,856 |
from typing import Callable
from typing import List
def get_table_reader() -> Callable[[Engine, Table], List[dict]]:
"""
When syncing from a relational database, currently MySQL or Postgres, the database has only a single concept of
state, that is the current state. We simply capture this state by readin... | d7d5c6349da5a779f1d8495b0851ef42fbf1fe00 | 3,616,857 |
def scene_to_raster(scene):
"""Convert scene to a integer array height x width containing color codes.
"""
pixels = simulator_bindings.render(serialize(scene))
return np.array(pixels).reshape((scene.height, scene.width)) | f4db88f58398228e58cca9dbf0662b3c0ecd89c8 | 3,616,858 |
def gtk_menu_position(event, *args):
"""
Create a menu at the given location for an event. This function is meant to
be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method.
The *event* object must be passed in as the first parameter, which can be
accomplished using :py:func:`functools.partial`.
... | 2670b4c2b3f5d7ad7fa74a836ec1b918a724c436 | 3,616,860 |
def mm2cm(v):
"""
Converts value from mm to cm
Parameters
----------
v: value
input value, mm
returns:
value in cm
"""
if np.isnan(v):
raise ValueError("mm2cm", "Not a number")
return v * 0.1 | 302377993307dbaa6011281b96a71d969c692579 | 3,616,861 |
import torch
def ssim(x, y):
"""Calculate ssim value of x (3D) in respect to y (3D).
:param x: preprocessed predicted tensor (3D)
:type x: torch.Tensor
:param y: preprocessed groundtruth tensor (3D)
:type y: torch.Tensor
"""
# pre-computation
C1 = (0.01 * 255) ** 2
C2 = (0.03 * 25... | e94d4565f694ecdc8f7e72f692861b9982e66b11 | 3,616,862 |
import math
def draw_star (im, yc, xc, radius, npoints, inner_radius=None,
v=max_image_value, fast=False, fill=False):
"""
Draw an npoints-pointed star of radius r centred at (yc, xc).
Arguments:
im image upon which the text is to be written (modified)
yc y-va... | 75193ebb73be3ab5f7c59d28fcacca9ceb5bf45f | 3,616,863 |
from typing import Any
import websockets
import json
async def songdb(timeout: int = config.TIMEOUT) -> Any:
"""
返回 ``song_id`` - 歌名(en|jp) 的字典表
"""
async with websockets.connect(config.ESTERTION_URI, timeout=timeout) as ws:
await ws.send('constants')
r = await ws.recv()
await ... | ecd751de2ad1940a7623b46bcf86d1edb16e62b0 | 3,616,864 |
def imagenet_resnet_v2_generator(block_fn, layers, num_classes, data_format=None):
"""Generator for ImageNet ResNet v2 models.
Args:
block_fn: The block to use within the model, either `building_block` or
`bottleneck_block`.
layers: A length-4 array denoting the number of blocks to include in each
... | 8d5f7ff0c19b6aa8ae88a1954759b26406c16603 | 3,616,865 |
import re
def get_api_url(request_object, production=False):
""" Get api URL and PORT
Usefull to handle https and similar
unfiltering what is changed from nginx and container network configuration
Warning: it works only if called inside a Flask endpoint
"""
api_url = request_object.url_root... | b8c9850e8379f1d49c717ecf11a2b135c2eeb88c | 3,616,866 |
from typing import List
from typing import Dict
def get_group_of_dependent_blocks(blocks: List[BuildingBlock]) -> Dict[int, int]:
"""
Building blocks can be categorized into groups. Blocks that follow each other in the graph
(that is, they are connected by one edge) belong to the same group.
:param: ... | 042b69f9b224c0451a4b81e8567151c837fe5301 | 3,616,867 |
def eval_data(dataset):
"""
Given a dataset as input returns the loss and accuracy.
"""
# If dataset.num_examples is not divisible by BATCH_SIZE
# the remainder will be discarded.
# Ex: If BATCH_SIZE is 64 and training set has 55000 examples
# steps_per_epoch = 55000 // 64 = 859
# num_ex... | cfcba534913936ba66bb0cd7002e7400383cd42b | 3,616,868 |
def list_blobs(bucket_name):
"""Lists all the blobs in the bucket."""
# bucket_name = "your-bucket-name"
storage_client = storage.Client()
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)
return [i.name for i in blobs]
# for... | fe6e4e9d9b5ff73e43c1079d3b0a1decfcf9fafe | 3,616,869 |
def valid_header(header: BlockHeader, difficulty: int) -> bool:
"""Check if block hash matches header data."""
h = hash.hash(header['timestamp'] +
header['previous_hash'] +
header['nonce'] +
header['merkle_root'])
return (header['this_hash'] == h and
... | 8b457ec85d25bd965f27c2e55bd5078597d24395 | 3,616,870 |
def poisson_gamma(data, sum_w, sum_w2, a=1, b=0):
"""
Log-likelihood based on the poisson-gamma mixture. This is a Poisson likelihood using a Gamma prior.
This implementation is based on the implementation of Austin Schneider (aschneider@icecube.wisc.edu)
-- Input variables --
data = data histogram
... | f4d71aca26e262b127baa62526f8a6d85a6a11ea | 3,616,871 |
def a_coreProperties():
"""Syntactic sugar to construct a CT_CorePropertiesBuilder instance"""
return CT_CorePropertiesBuilder() | 4088d48518988df15daa883c310bbfb3ad1ec59b | 3,616,872 |
import copy
def model_builder(features,
labels,
mode,
params,
config,
output_type=ModelBuilderOutputType.MODEL_FN_OPS):
"""Multi-machine batch gradient descent tree model.
Args:
features: `Tensor` or `dict` of `Tensor` ... | 144432534e21074d6f9f87a00962fa8e0845e2f1 | 3,616,873 |
def dmax_curve_z(tddose, shot_y, shot_z):
"""
Return dmax Z curve for a shot
Parameters
----------
tddose: 3ddose object
contains dose and boundaries, possible symmetrized
shot_y: float
Y shot position, mm
shot_z: float
Z shot position, mm
returns: tuple of a... | d557e59a896a88dac9a572e6f35793cae7207dae | 3,616,874 |
def _2samp_rotate(sim, x, y, p, degree=90, pow_type="samp"):
"""Generate an independence simulation, rotate it to produce another."""
angle = np.radians(degree)
data = np.hstack([x, y])
same_shape = [
"joint_normal",
"logarithmic",
"sin_four_pi",
"sin_sixteen_pi",
... | f0c4a7f5e4e72327359ca51962e554690b0e8e7a | 3,616,876 |
import re
def _sort_nd2_files(files):
"""
The script used on the Nikon scopes is not handling > 100 file names
correctly and is generating a pattern like:
ESN_2021_01_08_00_jsp116_00_P_009.nd2
ESN_2021_01_08_00_jsp116_00_P_010.nd2
ESN_2021_01_08_00_jsp116_00_P_0100.nd2
ESN_... | 17a034323412174beab3fd9cfb23e315a26d4d5a | 3,616,877 |
def trending_up(df: pd.Series, period: int) -> pd.Series:
"""returns boolean Series if the inputs Series is trending up over last n periods.
:param df: data
:param period: range
:return: result Series
"""
return pd.Series(df.diff(period) > 0, name="trending_up {}".format(period)) | 187dbee151d927828d1d17c02ebbb3bb079f6c0d | 3,616,878 |
def get_maxtarget(pairs):
"""
This method looks at a set of (before_label, after_label) tuples.
There are a few informative statistics from this set.
- proportion of changed labels: P(before_label != after_label)
- maximum proportional class gain: max_i(P(before_label != after_label AND after_l... | 6c1bbaa5630f455e2e10169fdcd84f9cb01eb4c6 | 3,616,879 |
def _get_formats(region=None):
"""Return the formats for the region."""
if region:
region = _clean_region(region)
if region not in _number_formats_per_region:
raise InvalidComponent()
return [_number_formats_per_region[region]]
return _number_formats_per_region.values() | f4962a46f1786bbc97a5991b5749e993efaac814 | 3,616,880 |
def jsonCatalog():
"""
The function that returns a JSON format output that contains
all database data. Including all categories and all items.
"""
output = {}
# Get all the categories from the database
categories = session.query(CatalogCategory).all()
for category in categories:
... | c7e22fa205bf648b5e6d830946317d6cf73afce1 | 3,616,881 |
import types
def argmax(values: np.ndarray) -> types.Action:
"""Argmax with random tie-breaking."""
check_numerics(values)
max_value = np.max(values)
return np.int32(np.random.choice(np.flatnonzero(values == max_value))) | 9cf697e375c1e4ba8d4e8605344bf03955cf272b | 3,616,882 |
def html_parser():
"""
Create an HTML5 parser.
"""
return HTMLParser(strict=True) | 0521cc74ae64d592d436a563cafb698fec1d8a69 | 3,616,883 |
def _crop_shape(shape):
"""Calculates a new, smaller shape after cropping.
Args:
shape: A shape.
Returns:
A shape.
"""
return [int(CROP_RATIO * shape[0]), int(CROP_RATIO * shape[1]), shape[2]] | 6e329aa2f37638994d772926b826ed4cc9702e80 | 3,616,885 |
def app_context():
"""Get app context for tests
:return:
"""
return app.app_context() | ebb9160362c73876631745c9b66ed5d03a84e313 | 3,616,886 |
import scipy
def fit_linear_least_squares(X, y, weights=None):
"""Fit linear model
Returns
-------
coefs : array
XXinv : array
Inverse of (X*transpose(X)), or None if system is not full rank
"""
num_coefs = np.size(X,1)
if weights is not None:
rtw = np.diag(np.sqrt(wei... | bd193b6e6b6a130782af2e9803a0d4f5636d7c4e | 3,616,887 |
def dmp_rem(f, g, u, K):
"""
Returns polynomial remainder in ``K[X]``.
**Examples**
>>> from sympy.polys.domains import ZZ, QQ
>>> from sympy.polys.densearith import dmp_rem
>>> f = ZZ.map([[1], [1, 0], []])
>>> g = ZZ.map([[2], [2]])
>>> dmp_rem(f, g, 1, ZZ)
[[1], [1, 0], []]
... | 8c03d5d2e5e110c0a323ba1997a4ad2ab1882231 | 3,616,888 |
def find_data(*args):
"""find_data(ea_t ea, int sflag) -> ea_t"""
return _idaapi.find_data(*args) | 7181f508d09e980c1d8d13b76e6a570eca1a66f1 | 3,616,890 |
import array
def a_starify(search_map: array):
"""Beings an a-star search through the input numpy array.
:param search_map: Input numpy array.
:return:
"""
end_point = (search_map.shape[1] - 1, search_map.shape[0] - 1)
start_node = Node(0, 0, None, 0, end_point[0], end_point[1])
heap = []... | d025f333402a574ef7916c83a30583dd9c750b4f | 3,616,891 |
from bs4 import BeautifulSoup
def parse_search_article_result(html):
"""
解析一页搜索结果中所有的微信文章条目,包括文章标题、摘要、时间、文章来源
:param html:
:return:list
"""
soup = BeautifulSoup(html, 'html.parser')
ul = soup.find('ul', attrs={'class': 'news-list'})
res = list()
for li in ul.find_all('li'):
... | ce293b1e78b174a5343417e40cf5285f9cd46464 | 3,616,892 |
def generate_ground_image(height,
width,
focal,
principal_point,
camera_rotation_matrix,
camera_translation_vector,
ground_color=(0.43, 0.43, 0.8)):
"""Generate a... | 31ff3b82132e7bf56b0a1347c78b8ea9223833bc | 3,616,893 |
import codecs
def get_config(p):
"""Reads a config file.
:return: dict of ('section.option', value) pairs.
"""
cfg = {}
parser = ConfigParser()
parser.readfp(codecs.open(p, encoding='utf8'))
for section in parser.sections():
for option in parser.options(section):
typ... | 983ff3363e0b0f6d0e2d7f9f516d484849718d56 | 3,616,894 |
def process_key(key):
"""
返回32 bytes 的key
"""
if not isinstance(key, bytes):
key = bytes(key, encoding='utf-8')
if len(key) >= 32:
return key[:32]
return pad(key, 32) | 39fcab8fe8bb18014307d86432b3bc22c40107bf | 3,616,895 |
def dobro(valor=0, formatc=False):
"""
-> Dá o dobro de um valor.
Parâmetros opcionais
:param valor: Valor que será dobrado.
:param formatc: Booleano que indica se a formatação no valor será feita
:return: Valor dobrado com a formatação ou não.
"""
res = valor * 2
return res if not f... | dcb79b83a8e347d2fa77d1ee65756f9eedf3c301 | 3,616,896 |
def _suppression_polynomial(halo_mass, z, log_half_mode_mass, c_scale, c_power):
"""
:param halo_mass: halo mass
:param z: halo redshift
:param log_half_mode_mass: log10 of half-mode mass
:param c_scale: the scale where the relation turns over
:param c_power: the steepness of the turnover
... | e0d72ae6c092ff01864cfb74d18143b070f075c9 | 3,616,897 |
import torch
def KLDiv_loss(x, y):
"""Wrapper for PyTorch's KLDivLoss function"""
x_log = x.log()
return torch.nn.functional.kl_div(x_log, y) | e288c3e60fab90a30693b6d5856bd2964f421599 | 3,616,899 |
def limit_vals(input_value, low_limit, high_limit):
"""
Apply limits to an input value.
Parameters
----------
input_value : float
Input value.
low_limit : float
Low limit. If value falls below this limit it will be set to this value.
high_limit : float
High limit. If... | 4520da27c81338631ea0d35651c7e3170de0524c | 3,616,900 |
def reformat_remove_leading_zeros(x, pos):
"""Format 1 as 1, 0 as 0, and all values whose absolute values is between
0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
formatted as -.4)."""
val_str = '{:g}'.format(x)
if 0 < np.abs(x) < 1:
return val_str.replace("0", "... | 29788f14482eba5ba29f2dbb93db25314f3dbffa | 3,616,901 |
from bs4 import BeautifulSoup
def getFormData(page):
"""
Finds form data required to post request for
next page. Returns tuple with data
"""
soup = BeautifulSoup(page, 'html.parser')
viewstate = soup.find('input', {'id': '__VIEWSTATE' })['value']
generator = soup.find('input', {... | 0f4ceb3a82d2a2dcad4125445e9803b358e0ada1 | 3,616,902 |
import torch
def get_mask(
ref,
sub,
pyg=False
):
"""
Get the mask for a reference list based on a subset list.
Args:
ref: reference list
sub: subset list
pyg: boolean; whether to return torch tensor for PyG
Return:
mask: list or torch.BoolTensor
"""... | 07e4b092b5becaaec8bc070990259701bc3a00b7 | 3,616,903 |
def round_m(x):
"""Round meters to an accuracy that avoids machine error."""
return np.around(x, decimals=6) | 323447a17715f1bbf525f371e7f5770311f4d592 | 3,616,904 |
def get_merged_overlapping_coords(start_end):
"""merges overlapping spans, assumes sorted by start"""
result = [start_end[0]]
prev_end = result[0][-1]
for i in range(1, len(start_end)):
curr_start, curr_end = start_end[i]
# if we're beyond previous, add and continue
if curr_start... | 22220778a66e069d98d1129b32f024e61fde1859 | 3,616,905 |
def create_prime_node():
"""
Return a prime node with no children
OUTPUT:
A node object with node_type set as NodeType.PRIME
EXAMPLES::
sage: from sage.graphs.graph_decompositions.modular_decomposition import create_prime_node
sage: node = create_prime_node()
sage: node
... | 43879b9b68418565301cedc121d33c40e6ad86b3 | 3,616,906 |
def u_from_psi(head, psi):
"""Calculate u_calc from non dimensional psi.
Parameters
----------
head : pint.Quantity, float
Polytropic head.
psi : pint.Quantity, float
Head coefficient.
Returns
-------
u_calc : pint.Quantity, float
Impeller tip speed.
"""
... | 2f4f1b772decd008e0e52b8fd9e8975feb40b450 | 3,616,907 |
def collapse_objlist(object_list, keyword, suffix='', doarray = False):
""" Given a LIST of identical objects, collapse the objects to form a
list of only a single keyword.
::
aplist = nsdata.getirafap('ap1')
cenlist = nsdata.collapse_objlist(aplist, 'keyword')
If yo... | 32afbf75b7fe7d06cb89a1ebb0a2f34666e8d732 | 3,616,908 |
def add_gmail(t=None, u=None, p=None):
"""
Adds server GMail to instance
Adds GMail settings to vim /var/lib/geonode/rogue_geonode/geoshape/local_settings.py
"""
address = _request_input("User", u, True)+'@gmail.com'
host = 'smtp.gmail.com'
return _run_task(_add_email, args=None, kwargs={... | 64e7778b3010981ca31e079d728a1368abffd0c3 | 3,616,910 |
def unpack_mac(sixbytes):
"""Converts a mac address given in a six byte string in network
byte order to a string in colon delimited notation.
>>> unpack_mac(b"012345")
'30:31:32:33:34:35'
>>> unpack_mac(b"bad")
Traceback (most recent call last):
...
ValueError: given buffer is not exactly six bytes long
@typ... | d9504ac1f99229cff1a870ff500808cd6d7174d2 | 3,616,911 |
def create_obs_stacker(environment, history_size=4):
"""Creates an observation stacker.
Args:
environment: environment object.
history_size: int, number of steps to stack.
Returns:
An observation stacker object.
"""
return ObservationStacker(history_size,
environment.vectorized_observation_sha... | 0955e75841247fd2bd8a27f4b695fbfffbd5dbd7 | 3,616,912 |
def s3_name(request):
"""[summary]
Args:
request ([type]): [description]
Returns:
[type]: [description]
"""
bucket_name = "test.bucket"
mock = mock_s3()
mock.start()
conn = boto3.resource("s3", region_name="us-east-1")
conn.create_bucket(Bucket=bucket_name)
requ... | 3e3f4c5a2a9249e8376eb4743632ba9a00f4aad1 | 3,616,913 |
def git_repo(pip_url_kwargs):
"""Create an git repository for tests. Return repo."""
git_repo = create_repo_from_pip_url(**pip_url_kwargs)
git_repo.obtain()
return git_repo | 21bf065c5b226453897c67b93693274201ea51cb | 3,616,914 |
def test_markdown_code_block():
"""We test that
- A code blocks are supported. Sort of. BUT THE INDENTATION IS CURRENTLY LOST!
- Indented markdown test from editors is supported. The Panel Markdown does not support this.
"""
code_block = """
This is not indented
```python
print("Hello Awesome Pane... | 84f47665265e0c6e5b8137361dd748ca14ac824c | 3,616,916 |
def euclidean_distance(mov_data, joint1, joint2):
"""Calculate the euclidean distance between the 2 given joints for all the frames of the grasping movement.
Args:
mov_data (pd.DataFrame): A pd.DataFrame containing the skeletal data of the grasping movement and of 9 frames before the beginning of the m... | 9f2eedcf3346d3a1cd3126a1e8ddc3e33b8c823d | 3,616,917 |
def ta_iter_SWS(*args):
"""
Function to be optimized for free protons, calls Bohrium version if required
Parameters
----------
mask
Mask indicating which cells to include / exclude from calculation
x
Free protons
k1
k2
k1p
k2p
k3p
st
ks
kf
ft... | 3673f94ae163fbef2ec9809c454a7b3be0edd841 | 3,616,918 |
def get_integer_attribute(attribute_list, name, default_value=None):
"""Returns the integer value of an attribute, if any, or default_value.
Arguments:
attribute_list: A list of attributes to search.
name: The name of the desired attribute.
default_value: A value to return if name is not found in... | ef364f78dbe8ce5cef70651ddab8057a45540e0f | 3,616,919 |
import logging
from pathlib import Path
def init_logger(log_file=None, log_file_level=logging.NOTSET):
"""
Example:
init_logger(log_file)
logger.info("abc'")
"""
if isinstance(log_file, Path):
log_file = str(log_file)
log_format = logging.Formatter(fmt='%(asctime)s - %(leve... | 65df2b9377062aa562b88eadd334447b14c100d3 | 3,616,920 |
def add_news():
"""新闻编辑详情页"""
if not g.user.is_admin:
return redirect('/')
if request.method == 'GET':
# 查询分类的数据
categories = []
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
categories_li ... | f079b9cbb321b2971a6fa5b1ae98dfb5cdbc4379 | 3,616,921 |
def get_address(tag_name, region, client):
"""
Collects the addresses of the aws instances being used for the estimation
:param tag_name: aws 'Name' tag of the instances
:param region: aws region
:param client: aws client
:return: list with aws instance addresses
"""
ec2 = boto3.Session(... | 565acb98b0cd79a566ed231a3b1cde362cfefa82 | 3,616,923 |
def SearchableField(**kw):
# type: (**Any) -> Dict[str, Any]
"""Configure a searchable text field for an Azure Search Index
:param name: Required. The name of the field, which must be unique within the fields collection
of the index or parent field.
:type name: str
:param type: Required. The d... | 5cdfd9aabd6d92f38ee681448546d7dd4976bf3b | 3,616,925 |
def geometry_factor_trace(trace, gap, thickness):
"""Return the kinetic inductance geometry factor for the central conducting trace of a CPW.
If the kinetic inductance of the central trace is L_k, its kinetic inductance contribution per unit length is
L = g_c L_k,
where g_c is the geometry factor ret... | ec4aad344c152d526f0009d26e90181512e6d7d2 | 3,616,926 |
def list_dir(conn=None):
"""
:param conn:
:return: <list>
"""
available = RBF.filter({PART_FIELD: False}).pluck(PRIMARY_FIELD).run(conn)
return [x[PRIMARY_FIELD] for x in available] | 0be9d248fbefe6e22a64863841a601b40daeb5dd | 3,616,927 |
def get_location_in_distance(actor, distance):
"""
Obtain a location in a given distance from the current actor's location.
Note: Search is stopped on first intersection.
@return obtained location and the traveled distance
"""
waypoint = CarlaDataProvider.get_map().get_waypoint(actor.get_locati... | 8dd439b681d94ed74bbfb89225d7710708ad436a | 3,616,928 |
def read_arrays_and_return():
"""
Reads the prepared numpy arrays
# Returns: the read np arrays
"""
X_train = np.load('arrays/X_train_w2v.npy')
y_train = np.load('arrays/y_train_w2v.npy')
X_test = np.load('arrays/X_test_w2v.npy')
y_test = np.load('arrays/y_test_w2v.npy')
retu... | 4aa5f036d3c0002f14a07e09d5c0062f07a35348 | 3,616,929 |
def HtmlRenderer(tooltip):
"""
A renderer that implements all tooltip features
in html.
"""
ret = []
USE_STYLE = True
lineTpl = '<div style="%s">%s</div>'
sideTpl = '<span style="%s">%s</span>'
for idx, line in enumerate(tooltip):
lineHtml = []
lineStyle = []
if idx == 0:
lineStyle.append("font-size... | fc4cbd326138085f39ee339973279e73be5f2af8 | 3,616,930 |
def linear_v2n(inputs, output_size, bias, w_x_inp, params, concat=False,
dtype=None, scope=None, d2=False):
"""
Linear layer
:param inputs: A Tensor or a list of Tensors with shape [batch, input_size]
:param output_size: An integer specify the output size
:param bias: a boolean value ... | c58092c21bdceeb901ce37b6a36586be2ae68025 | 3,616,931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.