content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import signal
def filt(data, cutoff, fs=1., order=1, rp=10., rs=10., kind='butter', btype='low', ftype='filtfilt', axis=0, analog=False):
"""
Apply a digital filter.
:param data:
:param cutoff:
:param fs:
:param order:
:param rp:
:param rs:
:param kind:
:param btype:
:param... | e37e03079700446c0eedbfb0b09dd8d045c87155 | 3,615,000 |
def remove_exceptions(words):
""" Removes exceptions from the resulting words """
return [word for word in words if root(word) not in EXCEPTIONS] | 1bdcc8bfb74f1cf3d31c80203da07580b66c40dd | 3,615,001 |
def convert_ring_to_sub_molecule(ring):
"""
This function takes a ring structure (can either be monoring or polyring) to create a new
submolecule with newly deep copied atoms
Outputted submolecules may have incomplete valence and may cause errors with some Molecule.methods(), such
as update_atomty... | 2e6c7c1ef637dd2e60988e4a7bf6b4f56ad41563 | 3,615,002 |
def generate_first_goal(roi_boundaries, vehicle_pos, parking_pos):
"""
generate goal for forward task
"""
x = roi_boundaries[4].x + 4
y = (roi_boundaries[6].y + roi_boundaries[5].y) / 2 \
+ (roi_boundaries[6].y - roi_boundaries[5].y) / 4 - 1.1
theta = 2... | 45308e1662f7b6512ab8364d65721fc7820687eb | 3,615,003 |
from scipy.integrate import solve_ivp
def solver_ode(X: np.ndarray, model: dict, flag_contact: np.array,T:float):
"""
param:
X: current q, qdot
model: add tau, ST
return:
Xdot: next qdot, qddot
"""
status = -1
# Calculate state vector by ODE
t0 = 0
tf = T
... | 88822a96cd838ea95a5a44a28a416b47c7c6b645 | 3,615,004 |
def compute_acc(Y, log_dist_a, n_se=2, return_er=False):
"""compute the accuracy of the prediction, over time
- optionally return the standard error
- assume n_action == y_dim + 1
Parameters
----------
Y : 3d tensor
[n_examples, T_total, y_dim]
log_dist_a : 3d tensor
[n_exam... | d042c2b6c8e540035f61cc06e7b751c664a44bda | 3,615,005 |
import tqdm
import sys
def uni_emojis() -> dict:
"""
Load all unicode emojis in 72x72 (folder from twemoji).
Since this is pretty fast we do it in the main thread
"""
emo_imgs = {}
twemoji_path = join("Image", "72x72")
emofiles = listdir(twemoji_path)
# for every emoji file in twemoji
for emofile in tqdm(emo... | 4fa5d5977afc841688a4a95cccdd205c9022aae9 | 3,615,006 |
def get_closest_point(points, point):
""" Get the closest point in an array of points to the given point. """
if len(points) == 1:
return 0, points[0]
min_dist = None
min_pt = None
min_i = None
for i, pt in enumerate(points):
v = [point[j] - pt[j] for j in range(0, 3)]
di... | 64f9c0bf949df7e18defa129105ca742bb5b6b2e | 3,615,007 |
from sys import path
def login():
"""
Login Page
"""
session.pop("user_email", None)
print("IN LOGIN")
if request.method == "POST":
u_name = request.form.get('Name')
u_email = request.form.get('Email Id')
u_num = request.form.get('Mobile No')
u_pwd = request.fo... | e14253503e48547fb4426753fd9667b405bf4c7d | 3,615,008 |
def get_facemesh_coords(landmark_list, img):
"""Extract FaceMesh landmark coordinates into 468x3 NumPy array.
"""
h, w = img.shape[:2] # grab width and height from image
xyz = [(lm.x, lm.y, lm.z) for lm in landmark_list.landmark]
return np.multiply(xyz, [w, h, w]).astype(int) | 2c7f21fe65e852659aecba966b9623938e1fd33d | 3,615,009 |
def decode_resource(name):
"""Load and decode sublime text resource.
Arguments:
name - Name of the resource file to load.
returns:
This function always returns a valid dict object of the decoded
resource. The returned object is empty if something goes wrong.
"""
try:
... | 98c2d590e977981175fd38539ce0b65097d07fba | 3,615,010 |
def get_dtw(action_list, env_output_list, environment):
"""Dynamic Time Warping (DTW).
Muller, Meinard. "Dynamic time warping."
Information retrieval for music and motion (2007): 69-84.
Dynamic Programming implementation, O(NM) time and memory complexity.
Args:
action_list: List of actions.
env_out... | 401def9c268195eda2b7a09cea30a220c43890aa | 3,615,011 |
def get_version(v):
"""
Generate a PEP386 compliant version
Stolen from django.utils.version.get_version
:param v tuple: A five part tuple indicating the version
:returns str: Compliant version
"""
assert isinstance(v, tuple)
assert len(v) == 5
assert v[3] in ('alpha', 'beta', 'rc... | 946c9ea382ac7da0da1c74373cf981df174737c1 | 3,615,012 |
def cpdf_shape(e, p, x):
"""The conditional probability distribution function of the shape parameters
e and p (ellipticity and prolateness) given the curvature x, as defined by
Bardeen, Bond, Kaiser & Szalay (1986) in equation (7.6), together with
(A15), (C4) and (C3)."""
# BBKS eqn. (C3):
chi =... | c2703d2438fac1ff2ec166ac85f2c9d5b293e7dc | 3,615,013 |
def get_nuc2prot():
"""
Returns a dict of nucleotide accessions numbers as keys and
protein acession numbers as values.
"""
nuc2prot_acc = {}
with open("./data/download/nucleotide2protein", "r") as handle:
line = handle.readline()
while line:
prot, nuc = line.split("... | 8f6e0ab5ad76cfaa63d8c0bf12f84e18b759e750 | 3,615,014 |
def MeasureTime(function):
"""Measure the execution time as a decorator.
Returns:
: The return of the wrapped function
Example::
from ml_dev_utils.Timer import MeasureTime
@MeasureTime
def my_function():
print("my awesome code")
The measured duration time... | 3e1f85285518a15c98ad7ffa20c0ed73a446c333 | 3,615,015 |
from typing import Iterable
from typing import Tuple
from typing import List
import os
import pathlib
def _repo_names_to_urls(
repo_names: Iterable[str], org_name: str, api: plug.PlatformAPI
) -> Tuple[List[str], List[str]]:
"""Use the repo_names to extract urls to the repos. Look for git
repos with the c... | 6f16308c0f72a2fa78af8638cbb2b460f9e7243b | 3,615,016 |
def tadsize_chart(genome_name):
"""
Determine the distance threshold to build coverage tracks.
Args:
genome_name (string): name of the reference genome;
ex: mammals, drosophila, c_elegans, s_pombe, c_crescentus
Returns:
dist_thresh (int): integer specifying dist... | 844744424845a1d240fa93023b9786a7ed2cc12c | 3,615,017 |
from typing import List
def vertices_of_mesh(bsp, mesh_index: int) -> List[VertexReservedX]:
"""gets the VertexReservedX linked to bsp.MESHES[mesh_index]"""
# https://raw.githubusercontent.com/Wanty5883/Titanfall2/master/tools/TitanfallMapExporter.py (McSimp)
mesh = bsp.MESHES[mesh_index]
material_sor... | 279defde6999f29ca085d2ec81602c21de69bf80 | 3,615,018 |
def convert_results_to_table(results, aggregation="average"):
"""
Convert results to table
Args:
results (dict): results dictionary
aggregation (str): aggregation method, either average or sum
"""
headers = []
columns = []
for target_task, source_tasks in results.items():
... | 51d38a52cb5428568c89e518df86624c5f438cf6 | 3,615,019 |
import gc
def object_at(desc):
"""object_at(id) -> object
id is an int returning from id() or a hex string of id()
Fetches all live objects, finds the one with given id, and returns
it. Warning: THIS IS FOR DEBUGGING ONLY. IT IS SLOW."""
if isinstance(desc, int):
target_id = desc
el... | deadb1c83254c12b22091532b9a6eb87f7e37542 | 3,615,020 |
def collapse_cr_map(dq_map):
"""Transform a 4D array containing cosmic ray hit locations
(1 for CR hit, 0 for no hit), into a 3D (integration, y, x)
map that lists for each pixel the group number of the first
CR hit. If that pixel has no CR hits in the integration, then
it will have a value of NaN.
... | d041608ad2b3813f8f3a4bb97c51966730ccd23e | 3,615,021 |
def pretty_league(league):
"""Formats a detailed league view in a PrettyTable"""
fields = ["Previous rank", "Current rank", "Arrow up/down", "Team name", "Manager name",
"Gameweek score", "Total score", "Team Id"]
table = PrettyTable(field_names=fields)
table.title = league.name
for t ... | d500b5b8929a5f7b5dbebef6558cfd2b57ea0c79 | 3,615,022 |
def pix2np(pix):
"""
Converts a pixmap buffer into a numpy array
"""
# pix.samples = sequence of bytes of the image pixels like RGBA
#pix.h = height in pixels
#pix.w = width in pixels
# pix.n = number of components per pixel (depends on the colorspace and alpha)
im = np.frombuffer(pix.sa... | 827cc54cbf66bed4ad980d8403c8bce96a884e52 | 3,615,023 |
def get_org_menu_extras(org):
"""
Check if there are any Config Attributes for extra org related menus in different pages
:param org: Organization Object
:return: Object with additional org menus to show. e.g. archive_buttons:
{
"url": "/apps/shipping/p--0000-0015/sxd/device/",
... | 5de3e64538633381f8eff395ab1e57acb6d8c039 | 3,615,024 |
from typing import Dict
def deep_dict_merge(source: Dict, dest: Dict):
"""Merge dictionaries recursively (i.e. deep merge)."""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = dest.setdefault(key, {})
deep_dict_merge(valu... | 98f3f7bb819e1245155280e4d31f5b07f7944cc4 | 3,615,025 |
import re
def split_with_semicolon(input_lines):
"""
文末までで1行になるように行を連結して作り直す
連結するときは単語間に1つのスペースを入れる
コメント文を含む場合は連結しない
ラベルが先頭に出現する場合は連結しない
Args:
input_lines(list): 入力ファイル
Returns:
list: 整形された文字列
"""
splited_lines = []
output_lines = []
for line in input_lines:... | 5a02b6eda109132b16bcb2d677b59b35bb3920d4 | 3,615,026 |
def get_challenge():
"""Calc game Q&A generation.
generate two random numbers
and calculate result of random operation
Returns:
dictionary:
key QUESTION (string) : operation description;
key ANSWER (string) : result of operation
"""
num1 = randint(_min(), _max()... | d21cc8672fd4bc3b4eae3e69d0d3a83978ed4d64 | 3,615,027 |
def _los(da, eos, sos):
"""
LOS = Length of season (in DOY)
"""
los = eos - sos
# handle negative values
los = xr.where(
los >= 0,
los,
da.time.dt.dayofyear.values[-1] +
(eos.where(los < 0) - sos.where(los < 0)),
)
return los | fe3da95bb3328643925a7d52656e201f055809fe | 3,615,028 |
def test_fallback_Jacobian_qnode(monkeypatch):
"""Test the decorator fallsback to Jacobian QNode if it
can't determine the device model"""
dev = qml.device('default.gaussian', wires=1)
# use monkeypatch to avoid setting class attributes
with monkeypatch.context() as m:
m.setitem(dev._capabi... | 3aa0dc3b29b01b23e05dc096e708f2992b703496 | 3,615,029 |
import textwrap
def construct_pdp_query(
metarels,
dwpc=None,
path_style="list",
return_property="name",
property="name",
join_hint="midpoint",
index_hint=False,
unique_nodes=True,
aggregate_columns=False,
):
"""
Create a Cypher query for computing the path degree product f... | 79a24cc17139273356959f6b4c2b9867c9943e5a | 3,615,030 |
from typing import List
def get_sparclur_renderers():
"""Helper function that returns a list of all SPARCLUR Renderers"""
present_renderers: List[Renderer] = \
[renderer for renderer in _sparclur_parsers.values() if issubclass(renderer, Renderer)]
return present_renderers | 80883bfda55f20c5ec2e38ed1a3dfbb28a5cd69f | 3,615,031 |
from typing import Tuple
def load_component_from_url(
cUrl: str, tProperties: "Tuple[PropertyValue]"
) -> "XComponent":
"""
Open or Create a document from it's URL.
Args:
cUrl (str): specifies the URL of the document to load
New documents are created from URL's such as:
... | 3e62ac958d1b9b98a751d153d672843faf388bfe | 3,615,032 |
def get_fields(search_input):
"""
Forms the field properties for a search input based on the input type and properties stored in the database.
For some types it returns a list with only one field for which the label is empty. Because it takes the label of
its fieldsets while rendering. For others, it re... | ec79e36eea1f4c185873fca1cd9c3d999d2d5e8e | 3,615,033 |
import os
import pickle
def read_and_save_tfrec_path(config, rootdir, filename_tfrec_pickle=None, dataset='0'):
"""
Read all paths of tfrecords and save into the pickle files
:param rootdir: type str: rootdir of saving tfrecords dataset
:param filename_tfrec_pickle: type str: Filename of pickle which ... | 6314aef94095d76bec032e5687c3065b028284ca | 3,615,034 |
def sub_menu(context, root):
"""Returns the sub menu items, the children of the root page. Only live
pages that have the show_in_menus setting on are returned."""
menu_pages = root.get_children().live().in_menu()
return {'request': context['request'], 'root': root,
'menu_pages': menu_pages} | e8ebfacd36263bad8cfb4d0acd2aba5e02560a7f | 3,615,035 |
import os
def forge_database_args(options: ImmutableMultiDict) -> t.List[str]:
"""Forges command for database selection based on submitted options
Input:
- options: user submitted parameters via HTML form
Output:
- base: appropriate (based on submitted options) argument list
"""
... | 0874c71277db1f65f8b9815acdacdface0dcdbf8 | 3,615,036 |
def alembic_config(postgres):
"""Создает объект с конфигурацией для alembic, настроенный на временную БД."""
cmd_options = SimpleNamespace(
config="alembic.ini", name="migrations", pg_url=postgres, raiseerr=False, x=None
)
return make_alembic_config(cmd_options) | be8e438caae3846a07baf09f07636e6a2f7f3dda | 3,615,037 |
def get_setting(name):
"""
Возвращает значение для настройки, или дефолт, если он задан, или None.
Если настройка обязательная, но она не задана - выбрасывает исключение.
"""
if hasattr(settings, name):
return getattr(settings, name)
if name in REQUIRED_SETTINGS:
_raise_required... | 6fd6bfe7de233af34d6fbe03bbc57a6bebebdbcc | 3,615,038 |
import mmap
def is_word_in_file(fname, word):
""" Search word in given file. This function skips empty files.
"""
f = open(fname)
try:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find(word) != -1:
return True
return False
except ValueError:
... | c16b94bb450807fefdab35470535c0752a9ecbbd | 3,615,039 |
def Difference(left, right): # pylint: disable=invalid-name
"""
@type: left: Iterable[Any]
@rtype: set[Any]
"""
return to_set(left).difference(to_set(right)) | d891e141f9dbb498dd0ea375de226060f5230f15 | 3,615,040 |
import opcode
def getP2PKHOpCode(pkScript):
"""
getP2PKHOpCode returns opNonstake for non-stake transactions, or
the stake op code tag for stake transactions.
Args:
pkScript (ByteArray): The pubkey script.
Returns:
int: The opcode tag for the script types parsed from the script.
... | 4468bc3dcc9828005aae322d28466093b1e127e9 | 3,615,041 |
def emat(st1, yt, t, a=None):
"""
returns exponential moving average for a t-period EMA and incremental value
where st1 is the previous average, yt is the incr value, and t is the size of the avg
a can optionally be overridden with a specific coefficient, else 2/(t-1) is used
"""
# St = a... | 484403ca5ba13bd960bcda6220846eef9ac09114 | 3,615,042 |
from datetime import datetime
def generate_dates_in_year_df(year, spark):
"""Generate all dates and all hours between in the given year"""
date = datetime.datetime.strptime(f"01/01/{year}", "%d/%m/%Y")
end = datetime.datetime.strptime(f"01/01/{year+1}", "%d/%m/%Y")
dates = list()
while date != end... | 50c489b4f169568c88cef4b7783caa88e9397863 | 3,615,043 |
import os
def get_swiftclient():
""" For this script, the authentication implementation is just the quickest
means possible to a demonstration.
"""
swift_conn = swiftclient.client.Connection(
authurl=os.environ.get("OS_AUTH_URL"),
user=os.environ.get("OS_USERNAME"),
key=os.envi... | fd1ac78c272acae56a022de6f00e779d2825f8f0 | 3,615,044 |
def plot_kmeans(result ,names, colors, country, season, mapbox_access_token):
"""
Creates and interactive html output of the clusters, if the number of points is more 100K randomly sample 50K of them
result: Dataframe, constaining k-means clustering results under the column 'label'
names: List of clust... | c948a98b9a4a12bb1b673ab0394f349fdf20c82f | 3,615,045 |
import time
def _fitFunc(pfit, pfitKeys, x, y, err=None, func=None,
pfix=None, verbose=False, follow=None):
"""
interface to leastsq from scipy:
- x,y,err are the data to fit: f(x) = y +- err
- pfit is a list of the paramters
- pfitsKeys are the keys to build the dict
pfit and pfi... | 5b13bcd74958818d57d4e18a155fffa4b43a4262 | 3,615,046 |
import os
def relpath(path, cwd=None):
""" Find relative path from current directory to path.
Example usage:
>>> from Ska.File import relpath
>>> relpath('/a/b/hello/there', cwd='/a/b/c/d')
'../../hello/there'
>>> relpath('/a/b/c/d/e/hello/there', cwd='/a/b/c/d')
'e/hello/t... | a743e02cb51ee352d7bbef047af13152c5834c14 | 3,615,047 |
def do_set_license_link(parser, token):
"""
Stores the license link to a context variable.
Usage::
{% license_link as [varname] %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError('%s tag requires two arguments' % bits[0])
if ... | 8c424990daeab639475cea0cb88d692803f14c66 | 3,615,048 |
def bf_get_snapshot_inferred_node_roles():
# type: () -> NodeRolesData
"""Gets suggested definitions and hypothetical assignments of node roles for the active network and snapshot."""
return bf_session.get_node_roles(inferred=True) | d0be36c9ce23190487669f384f4e7d1b7b44c85d | 3,615,049 |
import textwrap
def ExtractHelpStrings(docstring):
"""Extracts short help and long help from a docstring.
If the docstring contains a blank line (i.e., a line consisting of zero or
more spaces), everything before the first blank line is taken as the short
help string and everything after it is taken as the l... | c85f0008f059128c13f823a86e49eff901df3076 | 3,615,050 |
def flat_page(path):
"""flat pages rendering"""
page = g.pages.flatpages.get_or_404(path)
# Configure the img link plugin
g.flat_page = page
return render_template('article.html', page=page) | 654badee72cbe1c0f62d8859358afa22746d3432 | 3,615,051 |
def init_smoothing_wf(fwhm=None, memcalc=MemoryCalculator(), name=None, suffix=None):
"""
Smooths a volume within a mask while correcting for the mask edge
"""
if name is None:
if fwhm is not None:
name = f"smoothing_{int(float(fwhm) * 1e3):d}_wf"
else:
name = "sm... | 10cd279fe401cd23286d5f98efa49e6bf44ef3e2 | 3,615,052 |
import array
def check_similarity_in_list(token_1: str, token_list: array, threshold: int) -> bool:
"""
:param token_1
:param token_list
:param threshold
:return true, if token_1 and at least one token in token_list are equal due to levenshtein distance and a given threshold, otherwise false
"... | e7b88a555ed4c220b1354e711892740ca5a85038 | 3,615,053 |
def sin(val):
""" Qiskit wrapper of sine function
"""
if isinstance(val, Qobj):
return val.sinm()
else:
return np.sin(val) | daea123bc919f6b5686b87eff3f1b2e94766fb69 | 3,615,054 |
def toy_data_multitask(n_samples, input_dim, output_dim, random_state=None):
"""Generate data according to Evgeniou, C. A. Micchelli, and M. Pontil.
'Learning multiple tasks with kernel methods.' 2005.
Parameters
----------
"""
rs = check_random_state(random_state)
X = rs.rand(n_samples, ... | 7ba1e2c1644b57d83844757807b8bfd55f503027 | 3,615,055 |
def select_all(event):
"""Select all text event in textbox
An event that is bound to the select-all key press.
Selects all text within a text widget.
"""
event.widget.tag_add(SEL, "1.0", END)
event.widget.mark_set(INSERT, "1.0")
event.widget.see(INSERT)
return 'break' | 25cbd469df40c9e25bde52cb49fbc054c7cc978e | 3,615,056 |
def get_service_type(f):
"""Retrieves service type from function."""
return getattr(f, 'service_type', None) | fb4d98a4b4db0d10ab97d94d98ccfe21cea05fe9 | 3,615,057 |
def tempcsv():
"""Create a temporary CSV file"""
return tempfilename(suffix='.csv') | 3fe27678892dccecc852363338db74cac97ac5ac | 3,615,058 |
def func_d2lV(isvegc, edge, saturate):
"""
input:
isvegc : [ncol x nrow] array of vegetation field
output :
d2lV : [ncol x nrow] array, distance to nearest veg cell to the left
= 0 for veg cells
= 1 for bare cells with a veg cell immediately left
"""
ncol = isvegc... | 89820134f31ee577a2f923fca658d65e8cac92bc | 3,615,059 |
def generate_enum(cls_name, values, imports='') -> str:
"""
Helper function to create C++ enum headers
:param cls_name: the name of the enum
:param values: values to include
:param imports: additional files to import
"""
code = templates.FOUNDATION_ENUM.format(
name=cls_name,
... | adee41955f7ca800944c57ae470a5638a3df1e2a | 3,615,060 |
def u(string):
"""
This is a unicode() wrapper since u'string' is a Python3 compiler error.
"""
if is_python3():
return string
return unicode(string, encoding='utf-8', errors='strict') | bc37126387c04d67504de0ec981d805ea5e19c15 | 3,615,061 |
def env(ctx, name, home='~'):
"""Run with an anaconda environment"""
return ctx.prefix('source %s/%s/bin/activate %s' % (home, ANACONDA, name)) | 984075f721f62d973145705b8774ef33c6e75c0e | 3,615,062 |
def output_file(file_name):
""" adds output file extension, if missing
"""
return _add_extension(file_name, Extension.OUTPUT_LOG) | 946dcfee5a706b6cf0dc3713f75013bdc07f274f | 3,615,063 |
def load_pnasnetlarge(scopes, return_fn=_assign):
"""Converted from the [TF Slim][2]."""
filename = 'pnasnet_large.npz'
weights_path = get_file(
filename, __model_url__ + 'nasnet/' + filename,
cache_subdir='models',
file_hash='a1afc7679b950b643865aa7ea716c901')
values = parse_wei... | 9908f72795523ef4990e3f6e55ab45f3d0627772 | 3,615,064 |
def coord_max(t):
"""Multidimensional argmax
Returns coordinates of largest element in tensors of any shape
Args:
t: Tensor to find location of max element within
Returns:
0 or 1-D Tensor of length t.ndims containing coordinates
"""
# Run 1-D argmax on flattened array
idx ... | 5e006bae358c4ef97986abf08b9d45effbcd81d0 | 3,615,065 |
def block_dot(A, B, diagonal=False):
"""
Element wise dot product on block matricies
+------+------+ +------+------+ +-------+-------+
| | | | | | |A11.B11|B12.B12|
| A11 | A12 | | B11 | B12 | | | |
+------+------+ o +------+------| = +-------... | 453b4f5a300d750a9302f3309ab7f73c8d4b51c7 | 3,615,066 |
def SSIM(pred, ref):
"""
Compute SSIM between predicted and reference tensors in Tensorflow
Params:
- pred : TensorFlow tensor
Predicted tensor
- ref : TensorFlow tensor
Reference tensor
Outputs:
- ssim : float
SSIM value
... | fb5546ad16dab75c1bcbc63c9dabd47a100d7924 | 3,615,067 |
def CreatePackagableRoot(target, output_dir, ldpaths, root='/'):
"""Setup a tree from the packages for the specified target
This populates a path with all the files from toolchain packages so that
a tarball can easily be generated from the result.
Args:
target: The target to create a packagable root from
... | a86316d6928baf7cc7b66f7771d8538baea4007a | 3,615,068 |
def tablename(dxfname):
""" Translate DXF-table-name to attribute-name. ('LAYER' -> 'layers') """
name = dxfname.lower()
return TABLENAMES.get(name, name+'s') | 20ede17ece01f164a54d1052cfd43dc90fe0155e | 3,615,069 |
def extra_aaindex(filename):
"""Return AAIndex obj list.
"""
index_list = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']
aaindex = []
with open(filename, 'r') as f:
temp_h = ""
lines = f.readlines()
for i... | 346898a4094612161245464dde31b46b83af197c | 3,615,070 |
def make_block(arch_args, in_chs):
"""
Creates a block instance
"""
block_type_code = arch_args['block_type']
out_chs = arch_args.get('out_chs')
if out_chs is None:
out_chs = in_chs
arch_args['name'] = clean_name(arch_args['name'])
block_type_def = NetBuilderConfig.get_block_ty... | d587990fab9984719bd34199d113743ee201bdac | 3,615,071 |
def aks_list_table_format(results):
""""Format a list of managed clusters as summary results for display with "-o table"."""
return [_aks_table_format(r) for r in results] | b105b18f8b6d613a7d216bbcba9a31d1ee94bb32 | 3,615,072 |
import requests
from bs4 import BeautifulSoup
import tqdm
def bank_rank_banker() -> pd.DataFrame:
"""
全球银行排名前 25 家
https://www.thebankerdatabase.com/index.cfm/search/ranking
:return: 全球银行排名前 25 家
:rtype: pandas.DataFrame
"""
url = "https://www.thebankerdatabase.com/index.cfm/search/index.c... | f63c5e35e9f2b91af3d50d5c2eb23c0bad4f1dde | 3,615,073 |
from functools import reduce
def matmul(mat_list):
"""
Compute matrix multiplication of the matrices in mat_list
Arguments:
mat_list: list of numpy arrays, the target matrices
Return:
prod: numpy array, the result
"""
if len(mat_list) <= 1:
prod = mat_list[0]
els... | 0defdd6d073f9a254e178cac6489e96818cbe4f7 | 3,615,074 |
def expand_branch(branch):
"""Handles all branch todos (if any), in other words makes it ready.
Implementation of non-recursive DFS."""
if branch.ready:
return
trunk = branch.trunk
stack = list()
def stack_push(branch):
assert not hasattr(branch, 'todo_it'), ("A branch has 't... | 7a9dd3951f67f9ec804a9f0047f500a6d1dce293 | 3,615,075 |
def ByteStreamCopyToUTF16Stream(byte_stream, byte_stream_size=None):
"""Reads an UTF-16 formatted stream from a byte stream.
The UTF-16 formatted stream should be terminated by an end-of-string
character (\x00\x00). Otherwise the function reads up to the byte stream size.
Args:
byte_stream: The byte strea... | f994f5c88400b174eb7c435f69f7f0a0220fc371 | 3,615,076 |
def compute_error(model_data, reference_data):
"""Returns the summ of the squared differences between model and reference data."""
error = ((model_data - reference_data) ** 2).sum()
return error | 66e80326b85eed67008b517dfeff99cc8352bffd | 3,615,077 |
def blog_comment():
""" 博客文章评论 """
the_result = do_blog_comment(db, Post, Comment, request.form, request.headers['X-Real-IP'])
return the_result | 802aa611be206f483dddd0762e7e20a1f6089881 | 3,615,078 |
import importlib
def api(package_name, client, name):
"""Return an API instance."""
module_name = snake_case(name)
package = importlib.import_module(f"{package_name}.api.{module_name}_api")
return {
"api": getattr(package, name + "Api")(client),
"calls": [],
} | e1d149ab987e9923a42866c5f0f3ae946887e7ab | 3,615,079 |
import json
def checa_registro_json(registro, caminho_json):
"""
Checa se um <registro> já está no arquivo <caminho_json>.
Parâmetros
----------
registro : dict
Dicionário contendo o registro a ser checado.
Espera-se o formato:
{
... | b888781ed0e4fbc87f888afeec643e51b305157c | 3,615,080 |
def temporal_cyclic_transform(datetime_series, periodicity=None):
"""
TODO: VERY UNFINISHED
Replaces all time resolutions above the resolution specified with a fixed value.
This creates a cycle within a datetime series.
Parameters
----------
datetime_series: a pandas series of datetime objec... | 87828002c16b054de98a0981afd077bf724c752f | 3,615,081 |
import json
import sys
def read_json_file(json_path):
""" Read inventory as json file """
tf_inv = {}
try:
with open(json_path) as json_handler:
try:
tf_inv = json.load(json_handler)
except json.decoder.JSONDecodeError:
print(
... | 6758e50c441c10ed3e0c7e68b1ed87abbbeff6b1 | 3,615,082 |
def from_baseclaim(baseclaim: Baseclaim) -> VictorSolution:
"""Converts a Baseclaim into a VictorSolution.
Args:
baseclaim (Baseclaim): a Baseclaim.
Returns:
solution (VictorSolution): a VictorSolution.
"""
square_above_second = Square(row=baseclaim.second.row - 1, col=baseclaim.se... | c44b5770cb53cdb914c89130260bf1d6973b5cb9 | 3,615,083 |
def amsthm_latex(elem: Element, doc: Doc) -> pf.RawBlock | None:
"""Transform amsthm defintion to LaTeX package specifications."""
# check if it is a Div, and the class is an amsthm environment
options: DocOptions = doc._amsthm
if isinstance(elem, pf.Div):
environments: set[str] = options.theore... | 3b524464b41532810212ac1a5c3ec214baa2cff5 | 3,615,084 |
def async_run_in_kivy(func=None, clock=None):
"""Decorator that runs the given function in a Kivy context in an
asynchronous manner, waiting (asynchronously) until it's done.
It is primarily useful when kivy and trio are running in different threads.
See :mod:`kivy_trio.context` and the note below for ... | 635deedba8e62e341f501df9c66938da36641b3d | 3,615,085 |
def he_normal():
""" Returns a weight initializer with a Gaussian distribution whose mean is
zero and standard deviation is :math:`\\sqrt{\\frac{2}{n_i}}`, where
:math:`n_i` is the number inputs to a layer.
See "Delving deep into rectifiers: Surpassing human-level performance on
ImageNet classifica... | 6238592022eba777b3ce4118154bfab961d275b5 | 3,615,086 |
import copy
import random
import time
def upper_bound(sequences, max_run_time_random_seconds = 1):
""" Finds an upper bound based on some fast approximation algorithms."""
def alphabet_leftmost(sequences):
""" Approximation algorithm by looping through a random permutation on the alphabet """
... | 13268c26b00e6edfc9a581078f5105755e98834a | 3,615,087 |
import re
def get_block_source(template_source, block_name):
"""
Given a template's source code, and the name of a defined block tag,
returns the source inside the block tag.
"""
# Find the open block for the given name
match = re.search(NAMED_BLOCK_RE % (block_name,), template_source)
if ... | 83a4245dca634c6fa39b584cc9bfcabff8aa5866 | 3,615,088 |
import json
def get_mysql_connection(replica_set_name,
writeable=False,
user_role=None,
replica_set_role=None):
""" Get MySQL connection information. This code also exists in
the wiki and is copied numberous places across the pinterest... | 79909884edc6ba7c559ee84380d7f1692ad46517 | 3,615,089 |
import json
def dj(_dict):
"""Converts dicts to JSON and safely handles non-serializable items"""
return json.dumps(
_dict,
default=lambda o: 'ERROR: Item not JSON serializable',
sort_keys=True,
indent=3) | 042fdc731a084e1d74175a1ac22bc5b4204050c6 | 3,615,090 |
from sys import version
def inventree_commit_date(*args, **kwargs):
""" Return InvenTree git commit date string """
return version.inventreeCommitDate() | 6667e25b7d8552fa7f2e599dd4056b06eb8b8cf0 | 3,615,091 |
async def google_signin(
request: Request,
provider: StarletteOAuth2App = Depends(GoogleProviderMarker)
) -> RedirectResponse:
""" Redirect to the login through Google OAuth. """
return await provider.authorize_redirect( # type: ignore[no-any-return]
request=request,
redirect_ur... | f0c5809fa67ec55b4bc3b260c780ec337eecfa2d | 3,615,092 |
def fillna_bfill(array):
"""Backward fills an array.
Args:
array: A 2d numpy array with dimensions (location, time)
Returns:
A numpy array.
"""
_assume_2d(array)
flipped = np.flip(array)
filled = fillna_ffill(flipped)
return np.flip(filled) | 6bdca95590a3ad1d0feb32480b193fbe5dede4dc | 3,615,093 |
def generate_cholesky_factor(n=100, k=20):
"""
Generate a toy banded Cholesky factor
"""
L_band = np.random.uniform(low=0.1, high=1.0, size=(k, n))
L_band[0, :] = np.abs(L_band[0, :])
L_dense = construct_banded_matrix_from_band(k - 1, 0, L_band)
return L_dense | 7924449aeda724e8b3f2742409500a5500a04c3c | 3,615,094 |
def get_task_status(request):
""" AJAX: Gets the status of a pending background task by hash """
task_hash = request.GET.get("task_hash", "")
if not task_hash:
return {'response': 'bad', 'message': 'Invalid request'}
# Check if completed
if CompletedTask.objects.filter(task_hash=task_hash).... | 729552dc7e646c6a046be053d9fa6cff2d11dd05 | 3,615,095 |
def convert_to_fortran_bool(boolean):
"""
Converts a Boolean as string to the format defined in the input
:param boolean: either a boolean or a string ('True', 'False', 'F', 'T')
:return: a string (either 't' or 'f')
"""
if isinstance(boolean, bool):
if boolean:
new_string... | 9c129fff7e09f5619489206ecd95c9c72fd17627 | 3,615,096 |
def iter_dumps(iterable, width=2):
"""Converts numbers from iterable in the range from -1 to 1 into signed integers 'width' wide. And dumps them into a string or a bytearray."""
if width == 1:
return bytearray(map(lambda x: int(x * 127) & 255, iterable))
elif width == 2:
return bytearray(_se... | e5662483e938aebca9a750d1de4af944d49282f0 | 3,615,097 |
def scatterplot(
a,
b=None,
along="x",
area=None,
aspect=None,
color=None,
filename=None,
height=None,
hyperlink=None,
label=None,
margin=50,
marker="o",
mlstyle=None,
mstyle=None,
opacity=1.0,
... | 0b06e7ad2aa3a2aef045b366e57a82dd420e6d36 | 3,615,098 |
def is_decorated(field_spec):
"""
is this spec a decorated one
:param field_spec: to check
:return: true or false
"""
if 'config' not in field_spec:
return False
config = field_spec.get('config')
return 'prefix' in config or 'suffix' in config or 'quote' in config | b44d13fbcadc67ac191d07b1c304f2ec5ce1f081 | 3,615,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.