content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def lighten(data, amt=0.10, is255=False):
"""Lighten a vector of colors by fraction `amt` of remaining possible intensity.
New colors are calculated as::
>>> new_colors = data + amt*(1.0 - data)
>>> new_colors[:, -1] = 1 # keep all alpha at 1.0
Parameters
----------
data : matplot... | 195faa21ba30989f900b9b7f2b655a97074d8833 | 13,731 |
def _determine_function_name_type(node):
"""Determine the name type whose regex the a function's name should match.
:param node: A function node.
:returns: One of ('function', 'method', 'attr')
"""
if not node.is_method():
return 'function'
if node.decorators:
decorators = node.... | d80cfd4aabdd79023d636c7425b04e747420ad36 | 13,732 |
from typing import Tuple
import datasets
from typing import List
from typing import Dict
from re import T
def create_dataset(
template_path:
str = 'com_github_corypaik_coda/projects/coda/data/coda/templates.yaml',
objects_path:
str = 'com_github_corypaik_coda/projects/coda/data/coda/objects.jsonl',
... | 915bb616e165b55234f140f2ea1577644876ddb7 | 13,734 |
def escape_blog_content(data):
"""Экранирует описание блога."""
if not isinstance(data, binary):
raise ValueError('data should be bytes')
f1 = 0
f2 = 0
# Ищем начало блока
div_begin = b'<div class="blog-description">'
f1 = data.find(b'<div class="blog-content text">')
if f1 >= 0... | 285825b253de8ef9b67d7d3f1bdaa7a28f2e918c | 13,735 |
import csv
def read_csv(file_path, delimiter=",", encoding="utf-8"):
"""
Reads a CSV file
Parameters
----------
file_path : str
delimiter : str
encoding : str
Returns
-------
collection
"""
with open(file_path, encoding=encoding) as file:
data_in = list(csv.... | a4f1da219b0e5d752ff606614e93abbfc3d30597 | 13,736 |
from typing import Tuple
from pathlib import Path
def get_cmd_items(pair: Tuple[str, Path]):
"""Return a list of Albert items - one per example."""
with open(pair[-1], "r") as f:
lines = [li.strip() for li in f.readlines()]
items = []
for i, li in enumerate(lines):
if not li.startswi... | 92d34ce5af3a3dbe162adf0766382120d0458c46 | 13,737 |
import importlib
def import_activity_class(activity_name, reload=True):
"""
Given an activity subclass name as activity_name,
attempt to lazy load the class when needed
"""
try:
module_name = "activity." + activity_name
importlib.import_module(module_name)
return True
e... | b4cea3fad1f08a5758972847d3e03a41f89f223c | 13,738 |
def rgb2hsv(rgb):
"""
Reverse to :any:`hsv2rgb`
"""
eps = 1e-6
rgb = np.asarray(rgb).astype(float)
maxc = rgb.max(axis=-1)
minc = rgb.min(axis=-1)
v = maxc
s = (maxc - minc) / (maxc + eps)
s[maxc <= eps] = 0.0
rc = (maxc - rgb[:, :, 0]) / (maxc - minc + eps)
gc = (maxc - ... | febb268b1b691897c28447ff00a29785742dfc0c | 13,739 |
def fig_colorbar(fig, collections, *args, **kwargs):
"""Add colorbar to the right on a figure."""
fig.subplots_adjust(right=0.8)
cax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
cbar = fig.colorbar(collections, cax, *args, **kwargs)
plt.pause(0.1)
return cbar | a3156d24e28407938661c003d30b80a4d57638e6 | 13,740 |
def _merge_css_item(item):
"""Transform argument into a single list of string values."""
# Recurse lists and tuples to combine into single list
if isinstance(item, (list, tuple)):
return _merge_css_list(*item)
# Cast to string, be sure to cast falsy values to ''
item = "{}".format(item) if i... | c6f0c8769761640d5b0d98168cee1308f3209072 | 13,741 |
def extract_arguments(start, string):
""" Return the list of arguments in the upcoming function parameter closure.
Example:
string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
arguments (output):
'[{'start': 1, 'end': 7},
{'start': 8, 'end': 16},
... | 8e6e3fecc0643aa3f55108916a7c6892a96f13aa | 13,742 |
def iter_archive(path, method):
"""Iterate over an archive.
Args:
path: `str`, archive path
method: `tfds.download.ExtractMethod`, extraction method
Returns:
An iterator of `(path_in_archive, f_obj)`
"""
return _EXTRACT_METHODS[method](path) | dda105efc20583f54aed26a55112cfc56380ad68 | 13,744 |
def unfoldPath(cwd, path):
"""
Unfold path applying os.path.expandvars and os.path.expanduser.
Join 'path' with 'cwd' in the beginning If 'path' is not absolute path.
Returns normalized absolute path.
"""
if not path:
return path
path = _expandvars(path)
path = _expanduser(path... | ae11a69e6b2a3b0be4b3f266960d6004e99bd261 | 13,745 |
def get_predictions(logits):
"""
Convert logits into softmax predictions
"""
probs = F.softmax(logits, dim=1)
confidence, pred = probs.max(dim=1, keepdim=True)
return confidence, pred, probs | c83a47140534e27bb14991d4c8b2192a2a02cd46 | 13,748 |
def lookup_capacity(lookup_table, environment, cell_type, frequency, bandwidth,
generation, site_density):
"""
Use lookup table to find capacity by clutter environment geotype,
frequency, bandwidth, technology generation and site density.
"""
if (environment, cell_type, frequency, bandwidth, ge... | c98b25611cf72cc202fea060063f3020732a5282 | 13,749 |
def contig_slow(fn, num):
"""brute force, quadratic"""
data = parse(fn)
for i in range(len(data)-2):
for j in range(i + 2, len(data)-1):
s = sum(data[i:j])
if s == num:
return min(data[i:j]) + max(data[i:j]) | 69c086c605afc17a63def6e3958e340ddb7a32c3 | 13,750 |
def create_consts(*args) -> superclasses.PyteAugmentedArgList:
"""
Creates a new list of names.
:param args: The args to use.
"""
return _create_validated(*args, name="consts") | b10ab2d0e30e5cfb54c284d4557a98c0b3eb69c6 | 13,751 |
def opts2constr_feat_gen(opts):
"""Creates ConstFeatPlanes functor by calling its constructor with
parameters from opts.
Args:
opts (obj): Namespace object returned by parser with settings.
Returns:
const_feat_planes (obj): Instantiated ConstFeatPlanes functor.
"""
return Cons... | 5f664aae10f0584aca14ff58d2a984c29fd0dc2d | 13,752 |
def cmd_convert_items_to_cheetah_list(list):
"""
Cheetah templates can't iterate over a list of classes, so
converts all data into a Cheetah-friendly list of tuples
(NAME, DESCRIPTION, ENUM, HAS_BIT_OFFSET, BIT_OFFSET, BITS, TYPE, MIN, MAX, DEFAULT)
"""
temp = []
for i in list:
... | ff6933dce38d6ddcd74df72ce321d8f16dfd5074 | 13,754 |
def pose223(pose:gtsam.Pose2) -> gtsam.Pose3:
"""convert a gtsam.Pose2 to a gtsam.Pose3
Args:
pose (gtsam.Pose2): the input 2D pose
Returns:
gtsam.Pose3: the 3D pose with zeros for the unkown values
"""
return gtsam.Pose3(
gtsam.Rot3.Yaw(pose.theta()), gtsam.Point3(pose.x(... | 0a6d738d9cbe035be55a884a1523c985d547f25f | 13,755 |
import random
def pivot_calibration_with_ransac(tracking_matrices,
number_iterations,
error_threshold,
concensus_threshold,
early_exit=False
):
... | 0ce7c7bd8afbc88093793601da2b0333b40766cb | 13,756 |
def find_companies_name_dict():
"""
Finds companies names and addresses
:return: a dict with resource name eg.area of companies and url of available data
"""
base = "https://data.gov.ro/api/3/action/"
query = "Date-de-identificare-platitori"
address = url_build.build_url_package_query(base,... | 74526747f45a4c5491e4778759baca53a638c97f | 13,757 |
import typing
def error_to_response(request: web.Request,
error: typing.Union[Error, ErrorList]):
"""
Convert an :class:`Error` or :class:`ErrorList` to JSON API response.
:arg ~aiohttp.web.Request request:
The web request instance.
:arg typing.Union[Error, ErrorList] er... | 792c3fccd8d7fee708d850169fd943010e92ab05 | 13,758 |
def read(handle):
"""read(handle)"""
record = Record()
__read_version(record, handle)
__read_database_and_motifs(record, handle)
__read_section_i(record, handle)
__read_section_ii(record, handle)
__read_section_iii(record, handle)
return record | 90921ec1779c313505a838863509838bd858d0b7 | 13,759 |
import json
def validate_telegam():
"""Validate telegram token and chat ID
"""
configs = InitialConfig()
confs = ["chat_id", "bot_token"]
conf_dict = {}
if request.method == "GET":
for conf in confs:
conf_dict[conf] = getattr(configs, conf)
conf_json = json.dump... | f597d75672639dc2a39eb100f7221c508f62cf06 | 13,760 |
def hour(e):
"""
:rtype: Column
"""
return col(Hour(ensure_column(e))) | 492d9e21f2f7c3fd6107dd4000c8273efaa0357c | 13,761 |
def infer_gaussian(data):
"""
Return (amplitude, x_0, y_0, width), where width - rough estimate of
gaussian width
"""
amplitude = data.max()
x_0, y_0 = np.unravel_index(np.argmax(data), np.shape(data))
row = data[x_0, :]
column = data[:, y_0]
x_0 = float(x_0)
y_0 = float(y_0)
... | 784e88e5cd58def8467cbe0a851b37cc1fefe9dd | 13,762 |
import math
def extract_freq(bins=5, **kwargs):
"""
Extract frequency bin features.
Args:
bins (int): The number of frequency bins (besides OOV)
Returns:
(function): A feature extraction function that returns the log of the \
count of query tokens within each frequency bi... | b07f2f1810a26c2d04366d5516aac0ca79b547bb | 13,763 |
import typing
def create_private_key_params(key_type: str) -> typing.Type[PrivateKeyParams]:
"""Returns the class corresponding to private key parameters objects of the
given key type name.
Args:
key_type
The name of the OpenSSH key type.
Returns:
The subclass of :any:`Pr... | 6702f93f8cd8dc3fd104db5d63efd7db4bbaa38e | 13,764 |
import json
import requests
def get_response(msg):
"""
访问图灵机器人openApi
:param msg 用户输入的文本消息
:return string or None
"""
apiurl = "http://openapi.tuling123.com/openapi/api/v2"
# 构造请求参数实体
params = {"reqType": 0,
"perception": {
"inputText": {
... | 9a542b56a3ed3db8b8a9306ea3d425054a4ca64b | 13,765 |
import torch
def lm_sample_with_constraints(lm_model,
max_decode_steps,
use_cuda,
device,
batch_size=1,
alpha_0=1,
alpha=1,
... | cbccd2c0a2b91fa3e5ff5efb8b394fe7418f5b8b | 13,766 |
import torch
import tqdm
def validate_official(args, data_loader, model, global_stats=None):
"""Run one full official validation. Uses exact spans and same
exact match/F1 score computation as in the SQuAD script.
Extra arguments:
offsets: The character start/end indices for the tokens in each cont... | 09385e491c25ac238aebabe7d887f73b4c0bd091 | 13,767 |
def tuple_list_to_lua(tuple_list):
"""Given a list of tuples, return a lua table of tables"""
def table(it):
return "{" + ",".join(map(str, it)) + "}"
return table(table(t) for t in tuple_list) | 71ec1a29f5e23b8bf82867617fe157fbba4a2332 | 13,768 |
def reset_user_messages(request: Request):
"""
For given user reset his notifications.
"""
profile: Profile = get_object_or_404(Profile, user=request.user)
profile.messages = 0
profile.save()
return Response(status=status.HTTP_200_OK) | 628347dea707b0bd2ecc63cc004a3f62cb85e967 | 13,769 |
import functools
def define_scope(function, scope=None, *args, **kwargs):
"""
A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph only once.
Th... | 988f2f711dc227bfe8df5c7074d354c37d079fdb | 13,770 |
from typing import Union
from typing import List
from typing import Dict
import yaml
from typing import OrderedDict
def load_yaml(fname: str) -> Union[List, Dict]:
"""Load a YAML file."""
try:
with open(fname, encoding='utf-8') as conf_file:
# If configuration file is empty YAML returns No... | 5fd0b9d2dea7d07b7bb98f6a9ae3ce98be3962e0 | 13,771 |
def fancy_vector(v):
"""
Returns a given 3-vector or array in a cute way on the shell, if you
use 'print' on the return value.
"""
return "\n / %5.2F \\\n" % (v[0]) + \
" | %5.2F |\n" % (v[1]) + \
" \\ %5.2F /\n" % (v[2]) | 2340f22aa87da00abad30b9946c374f34b38496d | 13,772 |
def findpath_split(seq, ss1, ss2, md, th = 5, w = None):
""" Calculate findpath barriers for smaller components.
Args:
seq: RNA sequence.
ss1: Structure 1.
ss2: Structure 2.
md: ViennaRNA model details.
th: Threshold of how many basepairs must change for an independent f... | 2d52102df31dd014ac60e28c7258bff833353b6a | 13,773 |
def get_root_relative_url(url_path):
"""Remove the root page slug from the URL path"""
return _clean_rel_url('/'.join(url_path.split('/')[2:])) | 7aca9c0ec8856615fe1777117f44a259d7b597c7 | 13,774 |
def exclusion_windows_matching(match_peaks):
"""
Discard the occurrences of matching and non-matchign ions when they are found in the window
(+-losses_window_removal) around M-xx or free bases ions
"""
output_dic = match_peaks
for key in match_peaks:
if match_peaks[key]:
fo... | 9c2b5bcdb283b197102d50fdd2aaa8eb49e2fc3b | 13,776 |
def any_of(elements):
"""
Check to see if the argument is contained in a list of possible elements.
:param elements: The elements to check the argument against in the predicate.
:return: A predicate to check if the argument is a constituent element.
"""
def predicate(argument):
return a... | adacf8fd632d25452d22dab0a8a439021083ec83 | 13,777 |
def find_year(films_lst: list, year: int):
""" Filter list of films by given year """
filtered_films_lst = [line for line in films_lst if line[1] == str(year)]
return filtered_films_lst | f4c11e09e76831afcf49154234dd57044536bce1 | 13,778 |
def func_BarPS(HA_Open, HA_Close, HA_PS_Lookback, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False):
"""
0. This function is for calculating price trend number of HA bar, by looking back HA_PS_Lookback HA bars,
according to the previous bars' distribution, find the range (i.e. -4,-3,-2,-1,0,1,2,3,4) o... | 8a57de8ee4e832afd6327afc808668d227bc2592 | 13,779 |
from typing import List
def filter_whitespace(stream: List[Part]) -> List[Part]:
"""Remove whitespace tokens"""
return flu(stream).filter(lambda x: x.token != Token.WHITESPACE).collect() | aa3b8d109b0d85db7c3aa286858426276afb80ba | 13,780 |
def merge_partial_dicts(interfaces_dict, partials_dict):
"""Merges partial interface into non-partial interface.
Args:
interfaces_dict: A dict of the non-partial interfaces.
partial_dict: A dict of partial interfaces.
Returns:
A merged dictionary of |interface_dict| with |partial_dict|.
... | 7efc47325e1af5c06b19c1bba02ec8b53d9473e0 | 13,781 |
def gen_code_def_part(metadata):
"""生成代码中定义类的部分。
"""
class_def_dict = validate(metadata)
class_def_list = list(class_def_dict.values())
code = templates.t_def_all_class.render(class_def_list=class_def_list)
return code | df01fb69984a0ba471a6e5ac24bbecb0a622dd1b | 13,782 |
def clang_plusplus_frontend(input_file, args):
"""Generate LLVM IR from C++ language source(s)."""
compile_command = default_clang_compile_command(args)
compile_command[0] = llvm_exact_bin('clang++')
return compile_to_bc(input_file, compile_command, args) | 1b2701f3e0fac240843b302dd2056bac857ecb74 | 13,783 |
from django.db.models import Model
def create_forward_many_to_many_manager(superclass, rel, reverse):
"""
Create a manager for the either side of a many-to-many relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-t... | c9c45ae0eca4a913affab0ed832a0568e46d9a4c | 13,784 |
def grp_render_dashboard_module(context, module, index=None, subindex=None):
"""
Template tag that renders a given dashboard module, it takes a
``DashboardModule`` instance as first parameter and an integer ``index`` as
second parameter, that is the index of the module in the dashboard.
"""
... | 515bf427c4c39dc28479f6fe7121dc1cb542745e | 13,785 |
def serialize_routing(value, explicit_type=None):
"""Custom logic to find matching serialize implementation and
returns it's unique registration string key
:param value: instance to serialize
:param explicit_type: explicit serialization type for value
:return: str key to find proper serialize im... | 792cb24fc68060fe7e24f064f411752c5d787c3d | 13,786 |
def get_projection_matricies(az, el, distance_ratio, roll = 0, focal_length=35, img_w=137, img_h=137):
"""
Calculate 4x3 3D to 2D projection matrix given viewpoint parameters.
Code from "https://github.com/Xharlie/DISN"
"""
F_MM = focal_length # Focal length
SENSOR_SIZE_MM = 32.
PIXEL_ASPE... | a8ef5852510982851487e349336e41e61f7b582e | 13,787 |
def pix_to_coord(edges, pix, interp="lin"):
"""Convert pixel coordinates to grid coordinates using the chosen
interpolation scheme."""
scale = interpolation_scale(interp)
interp_fn = interp1d(
np.arange(len(edges), dtype=float), scale(edges), fill_value="extrapolate"
)
return scale.inv... | db9fcc47a273e9b39f6d5b6a39b59146866e5dd4 | 13,788 |
def create_action_urls(actions, model=None, **url_args):
"""
Creates a list of URLs for the given actions.
"""
urls = {}
if len(actions) > 0:
# Resolve the url_args values as attributes from the model
values = {}
for arg in url_args:
values[arg] = getattr(model, u... | f26477e0d046bfe6f73f25b2b086fad3b05a2646 | 13,789 |
def check_vfvx(x0, fx, fx_args, dfx, dfx_args=None, delta=1e-5):
"""
Check derivatives of a (vectorized) vector or scalar function of a vector
variable.
"""
if x0.ndim != 2:
raise ValueError('The variable must have two dimensions!')
if dfx_args is None:
dfx_args = fx_args
d... | a8cffcbf118394a1ea5d65835bade516035fe9fe | 13,790 |
def add_hovertool(p1, cr_traj, traj_src, sat_src, traj_df):
"""Adds a hovertool to the top panel of the data visualization tool plot."""
# Create the JS callback for vertical line on radar plots.
callback_htool = CustomJS(args={'traj_src':traj_src,'sat_src':sat_src}, code="""
const indices = cb_d... | f45245df7cd81ee8f0fc486d460be0c4338fd921 | 13,791 |
def backpage_url_to_sitekey(url):
"""http://longisland.backpage.com/FemaleEscorts/s-mny-oo-chics-but-oo-nn-lik-oo-me-19/40317377"""
(scheme, netloc, path, params, query, fragment) = urlparse(url)
sitekey = netloc.split('.')[0]
return sitekey | 6efa6d0bf73ab297144a7c6a35dbba920f77789e | 13,792 |
import torch
def batch_eye_like(X: torch.Tensor):
"""Return batch of identity matrices like given batch of matrices `X`."""
return torch.eye(*X.shape[1:], out=torch.empty_like(X))[None, :, :].repeat(X.size(0), 1, 1) | 266ee5639ce303b81e2cb82892e64f37a09695ff | 13,793 |
def cal_occurence(correspoding_text_number_list):
"""
calcualte each occurence of a number in a list
"""
di = dict()
for i in correspoding_text_number_list:
i = str(i)
s = di.get(i, 0)
if s == 0:
di[i] = 1
else:
di[i] = di[i] + 1
return di | aafabc6abdf4bf1df1b8d9e23a4af375df3ac75b | 13,794 |
def subtract(v: Vector, w: Vector) -> Vector:
"""simple vector subtraction"""
assert len(v) == len(w), 'Vectors need to have the same length'
return [vi - wi for vi, wi in zip(v, w)] | c6f8a9b19e07206a4d2637557c721bd97ad56363 | 13,795 |
from re import I
def f1():
"""
Filtering 1D.
"""
# Get center of the filter
c = int((size - 1) / 2)
# Pad the flatten (1D array) image with wrapping
If = np.pad(I.flatten(), (c), 'wrap')
# Initialize the resulting image
Ir = np.zeros(If.shape)
# Apply 1D convulation in the image
for x in range(c... | cc50f089148cdbaffbbdc7d6d734a066a6b08722 | 13,796 |
from typing import Optional
def _unify_data_and_user_kwargs(
data: 'LayerData',
kwargs: Optional[dict] = None,
layer_type: Optional[str] = None,
fallback_name: str = None,
) -> 'FullLayerData':
"""Merge data returned from plugins with options specified by user.
If ``data == (_data, _meta, _ty... | c0d472ef60bf69d67ef50d435715bfabe11c229e | 13,797 |
def get_sentence_embeddings(data):
"""
data -> list: list of text
"""
features = temb.batch_tokenize(data, tokenizer)
dataset = temb.prepare_dataset(features)
embeddings = temb.compute_embeddings(dataset, model)
return embeddings | cb1badd5cf9a244d7af8b40d219a467d0dff811e | 13,798 |
def sample_user(phone="+989123456789", full_name="testname"):
""" Create a sample user """
return get_user_model().objects.create_user(phone=phone,
full_name=full_name) | 418b12b4249c4beda4fed36664f2c9eb14f8adc4 | 13,799 |
import ctypes
def getVanHoveDistances(positions, displacements, L):
"""
Compte van Hove distances between particles of a system of size `L', with
`positions' and `displacements'.
Parameters
----------
positions : (*, 2) float array-like
Positions of the particles.
displacements : ... | a66150cfe238b151f098733d4570c438f1c93906 | 13,801 |
from typing import Any
from typing import Union
from typing import List
def plot_local_coordinate_system_matplotlib(
lcs,
axes: plt.Axes.axes = None,
color: Any = None,
label: str = None,
time: Union[pd.DatetimeIndex, pd.TimedeltaIndex, List[pd.Timestamp]] = None,
time_ref: pd.Timestamp = None... | 2df77f0e3343f6ac541ff37991208fb894b44660 | 13,802 |
def saved_searches_list(request):
"""
Renders the saved_searches_list html
"""
args = get_saved_searches_list(request.user)
return render('saved_searches_list.html', args, request) | a2f92c06733113f05501cb242d2ee2bad91917be | 13,803 |
def get_active_loan_by_item_pid(item_pid):
"""Return any active loans for the given item."""
return search_by_pid(
item_pid=item_pid,
filter_states=current_app.config.get(
"CIRCULATION_STATES_LOAN_ACTIVE", []
),
) | 6922336876fddd72ce7655bf2cfee298fdc4a766 | 13,805 |
from typing import Set
from re import X
def _get_szymkiewicz_simpson_coefficient(a: Set[X], b: Set[X]) -> float:
"""Calculate the Szymkiewicz–Simpson coefficient.
.. seealso:: https://en.wikipedia.org/wiki/Overlap_coefficient
"""
if a and b:
return len(a.intersection(b)) / min(len(a), len(b))... | 42d39edf9fa2465605717e0892bcbca05df7799b | 13,806 |
def data_splitter(
input: pd.DataFrame,
) -> Output(train=pd.DataFrame, test=pd.DataFrame,):
"""Splits the input dataset into train and test slices."""
train, test = train_test_split(input, test_size=0.1, random_state=13)
return train, test | ddcc28b4430a8901fcde540cf321d4ea43f123d7 | 13,807 |
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__',
'numpy', 'numpy._globals')):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __bu... | c97fd1942dae583ff236ed73d33b53b685cafd32 | 13,808 |
def get_words_for_board(words, board_size, packing_constant=1.1):
"""Pick a cutoff which is just beyond limit of the board size."""
# Order the words by length. It's easier to pack shorter words, so prioritize them.
# This is SUPER hacky, should have a Word class that handles these representational differe... | e5f74806fa15c1f1fbe78e0ac218d6d808611dfe | 13,809 |
def booleans(key, val):
"""returns ucsc formatted boolean"""
if val in (1, True, "on", "On", "ON"):
val = "on"
else:
val = "off"
return val | f210a2ce6b998e65d2e5934f1318efea0f96c709 | 13,810 |
def merge_param_classes(*cls_list,
merge_positional_params: bool = True) -> type(Params):
"""
Merge multiple Params classes into a single merged params class and return the merged class.
Note that this will not flatten the nested classes.
:param cls_list: A list of Params subcla... | c42907652f971d7cd6d208017b8faaacacddb5b2 | 13,811 |
import random
import collections
def make_pin_list(eff_cnt):
"""Generates a pin list with an effect pin count given by eff_cnt."""
cards = [1] * eff_cnt
cards.extend([0] * (131 - len(cards)))
random.shuffle(cards)
deck = collections.deque(cards)
pin_list = []
for letters, _ in KEY_WHEEL_DA... | 2c15a09928231993f09a373354ee29723463280d | 13,812 |
import select
def drop(cols, stmt):
"""
Function: Drops columns from the statement.
Input: List of columns to drop.
Output: Statement with columns that are not dropped.
"""
col_dict = column_dict(stmt)
col_names = [c for c in col_dict.keys()]
colintention = [c.evaluate(stmt).name if i... | 73ecf35077824281a5ebc4e26776b963e0cb378e | 13,813 |
def ConvertVolumeSizeString(volume_size_gb):
"""Converts the volume size defined in the schema to an int."""
volume_sizes = {
"500 GB (128 GB PD SSD x 4)": 500,
"1000 GB (256 GB PD SSD x 4)": 1000,
}
return volume_sizes[volume_size_gb] | b1f90e5ded4d543d88c4f129ea6ac03aeda0c04d | 13,814 |
def render_template_with_system_context(value):
"""
Render provided template with a default system context.
:param value: Template string.
:type value: ``str``
:param context: Template context.
:type context: ``dict``
"""
context = {
SYSTEM_KV_PREFIX: KeyValueLookup(),
}
... | 6df2e7a652595b35919638791aae5465258edf0f | 13,815 |
def ToTranslation(tree, placeholders):
"""Converts the tree back to a translation, substituting the placeholders
back in as required.
"""
text = tree.ToString()
assert text.count(PLACEHOLDER_STRING) == len(placeholders)
transl = tclib.Translation()
for placeholder in placeholders:
index = text.find(PL... | 36fca25dfc78e0f37ddc6193a17f2d29c6192228 | 13,816 |
import torch
def complex(real, imag):
"""Return a 'complex' tensor
- If `fft` module is present, returns a propert complex tensor
- Otherwise, stack the real and imaginary compoenents along the last
dimension.
Parameters
----------
real : tensor
imag : tensor
Returns
... | 272a293e3918e5e067f251a7dae10a4d2c56abf4 | 13,817 |
def get_snps(x: str) -> tuple:
"""Parse a SNP line and return name, chromsome, position."""
snp, loc = x.split(' ')
chrom, position = loc.strip('()').split(':')
return snp, chrom, int(position) | 52672c550c914d70033ab45fd582fb9e0f97f023 | 13,818 |
def qr_match(event, context, user=None):
"""
Function used to associate a given QR code with the given email
"""
user_coll = coll('users')
result = user_coll.update_one({'email': event["link_email"]}, {'$push': {'qrcode': event["qr_code"]}})
if result.matched_count == 1:
return {"status... | 7af48bc9fc97d34eb182eb8f429d93396079db87 | 13,819 |
def update_has_started(epoch, settings):
"""
Tells whether update has started or not
:param epoch: epoch number
:param settings: settings dictionary
:return: True if the update has started, False otherwise
"""
return is_baseline_with_update(settings['baseline']) and epoch >= settings['updat... | d2d2c8d7d8de0a13414a116121fb3cec47bc1d3f | 13,820 |
import torch
def compute_i_th_moment_batches(input, i):
"""
compute the i-th moment for every feature map in the batch
:param input: tensor
:param i: the moment to be computed
:return:
"""
n, c, h, w = input.size()
input = input.view(n, c, -1)
mean = torch.mean(input, dim=2).view(n... | 2ab3b7bfd34b482cdf55d5a066b57852182b5b6a | 13,821 |
def hs_online_check(onion, put_url):
"""Online check for hidden service."""
try:
print onion
return hs_http_checker(onion, put_url)
except Exception as error:
print "Returned nothing."
print error
return "" | 19b7b2f45581e2bdb907d416be1885f569841a86 | 13,822 |
def plotfile(fname, cols=(0,), plotfuncs=None,
comments='#', skiprows=0, checkrows=5, delimiter=',',
names=None, subplots=True, newfig=True, **kwargs):
"""
Plot the data in a file.
*cols* is a sequence of column identifiers to plot. An identifier
is either an int or a string.... | 493fccdf7d3661b9acffd22dbfd5799126a3d4f8 | 13,823 |
def retrieve(object_type, **kwargs):
"""Get objects from the Metatlas object database.
This will automatically select only objects created by the current
user unless `username` is provided. Use `username='*'` to search
against all users.
Parameters
----------
object_type: string
The ... | 54d35c23dd92ad65c5911d8c451b5b1fcbd131da | 13,825 |
def read_plot_pars() :
"""
Parameters are (in this order):
Minimum box width,
Maximum box width,
Box width iterations,
Minimum box length,
Maximum box length,
Box length iterations,
Voltage difference
"""
def extract_parameter_from_string(string):
#returns the part ... | c78dc8e2a86b20eb6007850a70c038de5bf9f841 | 13,826 |
import typing
def create(subscribe: typing.Subscription) -> Observable:
"""Creates an observable sequence object from the specified
subscription function.
.. marble::
:alt: create
[ create(a) ]
---1---2---3---4---|
Args:
subscribe: Subscription function.
... | 79c149545475a7686f8f8dffaed8f343604dd4aa | 13,827 |
def tocl(d):
"""Generate TOC, in-page links to the IDs we're going to define below"""
anchors = sorted(d.keys(), key=_lower)
return TemplateData(t='All The Things', e=[a for a in anchors]) | 8c27c42f05e4055a8e195d4d352345acc7821bae | 13,828 |
def get_upper_parentwidget(widget, parent_position: int):
"""This function replaces this:
self.parentWidget().parentWidget().parentWidget()
with this:
get_upper_parentwidget(self, 3)
:param widget: QWidget
:param parent_position: Which parent
:return: Wanted parent widget
... | ff010f3d9e000cfa3c58160e150c858490f2412d | 13,829 |
def DirectorySizeAsString(directory):
"""Returns size of directory as a string."""
return SizeAsString(DirectorySize(directory)) | 3e3d3b029da40502c2f0e7e5867786d586ad8109 | 13,830 |
def patch_is_tty(value):
""" Wrapped test function will have peltak.core.shell.is_tty set to *value*. """
def decorator(fn): # pylint: disable=missing-docstring
@wraps(fn)
def wrapper(*args, **kw): # pylint: disable=missing-docstring
is_tty = shell.is_tty
shell.is_tty ... | 77655d32a5572824978910a12378a54d83b7e81e | 13,831 |
import torch
import math
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"):
"""
An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range `(-sqrt(3/dim[0]) * s... | aa14ec45c389c55c141d9bffd6ef370313fdf446 | 13,832 |
def get_results(elfFile):
"""Converts and returns collected data."""
staticSizes = parseElf(elfFile)
romSize = sum([size for key, size in staticSizes.items() if key.startswith("rom_")])
ramSize = sum([size for key, size in staticSizes.items() if key.startswith("ram_")])
results = {
"rom": ... | b60052f702e53655ab1a109ea2bb039e78aabaf5 | 13,833 |
def path_element_to_dict(pb):
"""datastore.entity_pb.Path_Element converter."""
return {
'type': pb.type(),
'id': pb.id(),
'name': pb.name(),
} | 2a4e757dedf6707dc412248f84b377c2f375e70c | 13,834 |
def get_orr_tensor(struct):
""" Gets orientation of all molecules in the struct """
molecule_list = get_molecules(struct)
orr_tensor = np.zeros((len(molecule_list),3,3))
for i,molecule_struct in enumerate(molecule_list):
orr_tensor[i,:,:] = get_molecule_orientation(molecule_struct)
return or... | faf42cf76168191835d9dd354ae9bc03198829ad | 13,836 |
def make_request_for_quotation(supplier_data=None):
"""
:param supplier_data: List containing supplier data
"""
supplier_data = supplier_data if supplier_data else get_supplier_data()
rfq = frappe.new_doc('Request for Quotation')
rfq.transaction_date = nowdate()
rfq.status = 'Draft'
rfq.company = '_Test Company... | ee0663231fc0bb06f6f43fa5abecdced048c1458 | 13,837 |
def mlrPredict(W, data):
"""
mlrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matrix of siz... | a37359433b020eb625b37ea57cb15282c4f82c8d | 13,838 |
def add(n):
"""Add 1."""
return n + 1 | c62cee4660540ae62b5b73369bdeb56ccb0088d6 | 13,840 |
def _area(x1, y1, x2, y2, x3, y3):
"""Heron's formula."""
a = np.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))
b = np.sqrt(pow(x3 - x2, 2) + pow(y3 - y2, 2))
c = np.sqrt(pow(x1 - x3, 2) + pow(y3 - y1, 2))
s = (a + b + c) / 2
return np.sqrt(s * (s - a) * (s - b) * (s - c)) | 456ffe56a76fbea082939c278b5f0f2ebaf8c395 | 13,842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.