content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def predict(listing: Listing):
"""
Make a prediction for the AirBnB Optimal Listing Price 🔮
### Request Body; listed in ascending order of feature importances
- `review_scores_rating`: overall host review score
- `review_scores_checkin`: host review score for check-in
- `property_type`:... | 59e6a128d24df9539ed2e9199c882c8c11a24ef9 | 70,534 |
import tqdm
def calculate_coverage(aln, reads_mapped):
"""Calculate base and read coverage."""
_base_cov_dict = defaultdict(list)
read_cov_dict = defaultdict(lambda: 0)
allowed_operations = set([0, 7, 8])
with tqdm(total=reads_mapped, unit_scale=True) as pbar:
for read in aln.fetch(until_e... | 46f566fd09a4a6fd439b459845ee16ded1f8b729 | 70,536 |
def get_rna_brain_fantom():
"""Get RNA from mouse brain - FANTOM."""
return _get_data(protein_atlas.ProteinAtlasRnaBrainFantom) | 163f96e5b1263197e47d2f96b432c5b3883ecf92 | 70,537 |
def force_repeat_tie(threshold=True, selector=None) -> ForceRepeatTieCommand:
"""
Makes force repeat-ties command.
"""
return ForceRepeatTieCommand(selector, threshold=threshold) | 9123a63a782cac3e02b22379fe831a2bf2ac10cf | 70,538 |
def list_style_image(token, base_url):
"""``list-style-image`` property validation."""
if token.type != 'function':
if get_keyword(token) == 'none':
return 'none', None
parsed_url = get_url(token, base_url)
if parsed_url:
if parsed_url[0] == 'url' and parsed_url[1... | 77e61463c85874b6b9c2f1da83f67b38250d96ea | 70,539 |
import msgpack
def msgpack_restore(encoded_pytree):
"""Restore data structure from bytes in msgpack format.
Low-level function that only supports python trees with array leaves,
for custom objects use `from_bytes`.
Args:
encoded_pytree: msgpack-encoded bytes of python tree.
Returns:
Python tree o... | 5a49c876eff5ed13509e50f899f7581f1204cccf | 70,540 |
def estimate_log_evidence(samples, param_grid, log_numerator, max_components=5,
grid_fraction=0.1, plot=True, seed=123):
"""Estimate the log evidence using MCMC samples.
The evidence is estimated at each grid point using the ratio of the
log_numerator and the empirical density of ... | 3395f700d7c3d24421ac3eb0a32d3ee41e4deab4 | 70,541 |
from datetime import datetime
def convert_taxonomy_date(s):
"""
Returns a datetime representation of a date (in string format) loaded from the taxonomy. It
is assumed that the input format will be YYYY-MM-DD based upon observed values from within
the taxonomy.
If the input is not valid th... | 5677cbf22903cf274b03004a4cf75d38306a365c | 70,542 |
def OffsetOnSurface3(thisCurve, surface, distance, fittingTolerance, multiple=False):
"""
Offset a curve on a surface. This curve must lie on the surface.
Args:
surface (Surface): A surface on which to offset.
distance (double): A distance to offset (+)left, (-)right.
fittingToleran... | 9d5d795e6d094f380a5fcf5bf343a51ff6a4db4c | 70,543 |
def _create_user(cursor: Cursor, name: str) -> Result[Password]:
"""
Create a PostgreSQL user with a random password, if a user with that name doesn't already exist.
"""
passwd = Password.new()
query(cursor, _format("CREATE USER {} ENCRYPTED PASSWORD %s "
"NOCREATEDB NOSUPE... | b820913fcf1648f673e5c022b09a90a84b0dd3ba | 70,544 |
from datetime import datetime
def sysdate(as_string: bool=True, compact: bool=False):
"""
Get the current date, optionally formatted as a string.
"""
if as_string:
return datetime.datetime.now().strftime('%Y%m%d' if compact else '%Y-%m-%d')
else:
assert not compact, 'Cannot set `co... | 37619cf1cd8a6250f4ba221730343d8f13e7c318 | 70,545 |
def get_user(uid, app=None):
"""Gets the user data corresponding to the specified user ID.
Args:
uid: A user ID string.
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance.
Raises:
ValueError: If the user ID is None, empty or malformed.
... | b16e31b3eeae883732418d711ff7354d0a8136f8 | 70,547 |
def units_print_view(request, pk, side):
"""
Draft for one part of the rack
"""
rack = _rack(pk)
direction = _direction(pk)
return render(request, 'print.html', {
'side_name': _side_name(side),
'rack': rack,
'start_list': _start_list(pk, direction),
... | a4c2df4e706359ac5982bb25ca8196f764d66fdf | 70,548 |
def opening(values: np.ndarray, window_width: int) -> np.ndarray:
"""
Function to get opening of `values` array with structuring elements with `window_width` width.
Opening ... dilatation of the erosion.
Parameters:
values (np.ndarray): Array fo values that are to be opened.
window_widt... | 75358aff0c019a83c0307eee65a9e5097866cb67 | 70,549 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up OwnTracks based off an entry."""
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)
dev_ids = {
identifier[1]
for device in dev_reg.devices.values()
for identifier in... | 9076f5b950363bd4218befda8994ed020f05d6b2 | 70,550 |
import requests
def make_secure_api_call(url, headers = {}) -> str:
""" Make API call with error handling
Parameters
----------
url: str
The url to make the api call
headers: dict
The headers used in the api call
"""
try:
response = requests.get(url, headers = head... | b3f80825e2dc3c99a341dcc78386ecb78a642f40 | 70,551 |
def pix_to_non_square_ndc(i, S1, S2):
"""
The default value of the NDC range is [-1, 1].
However in the case of non square images, we scale the NDC range
to maintain the aspect ratio. The smaller dimension has NDC
range from [-1, 1] and the other dimension is scaled by
the ratio of H:W.
e.g.... | a0e41eb9fba7a817391ad6bcf901c608c808b11d | 70,552 |
def grid_values(grid):
"""
Convert grid string into {<box>: <value>} dict with '.' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long.
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'.
- values: Value in corresponding box, ... | 8652899a9663c3ffb83dd78234fb1571d857ab3a | 70,554 |
from typing import Tuple
from typing import List
def parsemsg(s: str) -> Tuple[str, str, List]:
"""
Breaks a message from an IRC server into its prefix, command, and
arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0:1] == ':' and ' ' i... | 9168dfa9a257c0ef1f11f84bf60b9d9e657057dc | 70,555 |
def get_valid_nodes(module, oc_exec, exclude_node):
"""Return a list of nodes that will be used to filter running pods"""
call_args = oc_exec + ['get', 'nodes']
res = call_or_fail(module, call_args)
valid_nodes = []
for line in res.split('\n'):
fields = line.split()
if not fields:
... | 464f06a39c924984cbeacc8f7498ddcb9e5cb980 | 70,556 |
def vline(chart: alt.Chart, value: float) -> alt.Chart:
"""Draw a vertical line on an Altair chart object."""
line = alt.Chart().mark_rule(color="grey").encode(x="val:Q")
return _add_line(chart, value, line) | d0bf2f0267041bb48277db610aa4ffd0fcf71b6f | 70,557 |
def d2_psi_heterodyne(t, psi, A, args):
"""
Need to cythonize
X = \\frac{1}{2}(C + C^\\dagger)
Y = \\frac{1}{2}(C - C^\\dagger)
D_{2,1}(\psi, t) = \\sqrt(1/2) (C - \\langle X \\rangle) \\psi
D_{2,2}(\psi, t) = -i\\sqrt(1/2) (C - \\langle Y \\rangle) \\psi
"""
X = 0.... | 39370c10b3df7cb6aa26af779150b377270e1692 | 70,558 |
def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(itemgetter(i), args))) != 1:
break
i += 1
return args[... | fa80d17cc41b716068dc741ea775c79356a6ad76 | 70,559 |
from datetime import datetime
def array_profile(
x: np.ndarray,
name: str = None,
timestamp: datetime.datetime = None,
columns: list = None,
):
"""
Generate a dataset profile for an array
Parameters
----------
x : np.ndarray
Array-like object to track. Will be treated as ... | c55668d8f5669dd3dba837040ef97f22f9d34c71 | 70,561 |
def Vector3_get_dimension():
"""Vector3_get_dimension() -> unsigned int"""
return _RMF.Vector3_get_dimension() | 5b7017be0fc3c1b06ec93710ca674f1fc019b560 | 70,562 |
def quat2dcm(quat):
"""quat2dcm(vec4f quat) -> mat3f"""
return _libvncxx.quat2dcm(quat) | 1f0b39ab9cdeb69613d43679bff989db7b9763e1 | 70,563 |
def cluster_chrom(tracklist, chrom, genome, blacklist, xcov=0.3, whitelist=None,
min_elements=None, n_ele_prop=0.1, min_tracks=None,
n_track_rep_prop=10e-10, neighborhood_dist=10000,
min_crb_separation=10000, max_crb_size=3e10, prefix='CRB'):
"""
Load & cl... | 189ce6b1550f4160741722e1734901e9208fede6 | 70,564 |
from operator import concat
def get_inventory(marketplace, address):
"""
Get the items the address owns on a marketplace.
"""
context = GetContext()
# Return the serialized inventory for the address.
inventory_marketplace_key = concat(inventory_key, marketplace)
storage_key = concat(inven... | 655e8120e2e5cbf226c3af379903250353934247 | 70,566 |
def create_app(config):
"""
App factory for Flask app. Setup of database, login, navbar and registering of blueprints
:param config:
:return: running flask app
"""
# create pvtool
app = Flask('pvtool')
app.config.from_object(config)
# database
db.init_app(app)
# create db
... | 62e6e388e003023baab6a51b5619b8db276f23df | 70,567 |
def make_offspring(parents, noffs=None, dam_list=None, sire_list=None, mu=1e-12, family_name='offs'):
"""
Mate individuals in a base population to create simulated offspring. Lists of
specific sires and dams can be provided with the options dam_list and
sire_list. If only the number of offspring are spe... | e0135eb0cc6cad9df1ea8dca42e35af0738f1540 | 70,569 |
def cosine_similarity(intersection_num, all_items_num,
first_set_len, second_set_len):
"""
Count cosine similarity based on intersection data
:param intersection_num: len of intersection of two sets
:param all_items_num: num of all items, for example, sum of views
:param first_... | 90a8be939730307069f6758fe6a93299d6484b42 | 70,570 |
def suggest(word):
"""Renvoie le mot le plus proche disponible dans le fichier keywords.json"""
return getMatchCoefficient(keywords, word)[0]["value"] | 3b72372243d2369741f96bb299fe11de1ecc8ba9 | 70,571 |
import random
def random_walk(graph, node, steps=8):
"""
Given a graph and a specific node within the graph, returns a node after steps random edge jumps
:param graph:
A networkx graph
:param node:
Any node within the graph
:param steps:
The number of steps within the random walk
:return:
A node within... | ad75cadc8e1df8edf5ebbb030de9b80076ab1f4c | 70,572 |
def get_test_model_full():
"""Returns a maximally complex test model,
using all supported layer types with different parameter combination.
"""
input_shapes = [
(26, 28, 3),
(4, 4, 3),
(4, 4, 3),
(4,),
(2, 3),
(27, 29, 1),
(17, 1),
(17, 4),... | be3e4dd8c0b1f0265c7e09155eca758a0a8fdc1d | 70,573 |
from typing import Callable
from typing import Any
def rfc6979(ec: Curve, hf: Callable[[Any], Any], mhd: bytes, q: int) -> int:
"""Return a deterministic ephemeral key following rfc6979"""
if not 0 < q < ec.n:
raise ValueError(f"private key {hex(q)} not in [1, n-1]")
hsize = hf().digest_size
... | 4a0cd11320a8ad327e8b8780d03a37b4e7ee3b16 | 70,575 |
import requests
from typing import List
import urllib
def list_directories(_):
"""Constroi a lista de diretorios do nextcloud no caminho passado
e adiciona as opcoes do promt.
Returns:
List: Lista com as opcoes
"""
try:
response = requests.request(method='PROPFIND',
... | e3cccba962ff93dc0d4f33541ac955fe80373e48 | 70,576 |
def traceBeam(gratAlign,order=1.,wave=2.48,blaze=30.):
"""Traces a beam to grating, applies misalignment,
then traces to focal plane and returns mean
x,y position
x refers to spectral direction
"""
#Compute yaw to achieve Littrow configuration
phi0 = arccos(sin(1.5*pi/180)/cos(blaze*pi/180))... | 8dfc7f796c58cebc2ab7119d75cdba984475166e | 70,577 |
def check_repos(repo_configs: list[RepoInfo], github_token: str = None) -> bool:
"""
Check a list of repos to verify that information provided is accurate
:param repo_configs: list of RepoInfo to check
:param github_token: github token to use for authentication
:return: None
"""
for repo in repo_configs:
... | 6040d78bb2445215da6d5b08033df2bd56a6a6f3 | 70,578 |
def _get_sample_data(random_state=None):
"""
get mnist data
input data is returned after normalization.
objective data is returned after one-hot encoded.
"""
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = np.expand_dims(X_train, axis=3) / 255.
X_test = np.expand_dims(... | be0a3daed5e93ceca35ef85c2c1bb233875003ba | 70,579 |
def get_n_points(points, point_type):
"""Compute the number of points.
Parameters
----------
points : array-like
Input points.
point_type : str, {'scalar', ''vector', 'matrix'}
Type of input points.
Returns
-------
n_points : int
Number of points.
"""
n_... | 1124f8740fea090d22f7791735000e74116eaa79 | 70,580 |
def fetch_issue_new_stock_info(stock_code):
"""获取发行新股信息"""
url_fmt = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vISSUE_NewStock/stockid/{}.phtml'
url = url_fmt.format(stock_code)
df = pd.read_html(url, attrs={'id': 'comInfo1'})[0]
return df | 2aa9d3ae163f81655a55e01d4c9e567df0524505 | 70,581 |
def vote_for_thread(request, course_id, thread_id, value):
"""
given a course id and thread id vote for this thread
ajax only
"""
thread = cc.Thread.find(thread_id)
result = _vote_or_unvote(request, course_id, thread, value)
return result | 1c64c2611214f69b7e17531e9045e17be8849b09 | 70,582 |
def return_date_of_quantile_sold_q4(df_daily_revenue: pd.DataFrame, percent: float):
"""Returns the date in which a specified percent of the bookings
is made for all rent rooms.
Parameters
----------
df_daily_revenue : pd.DataFrame
Pandas dataframe with information about daily revenue.
... | a398b0e7e572bfc0db0adcc7fc33ca7399bf4fc5 | 70,583 |
from typing import List
from typing import Any
def get_last_key_from_integration_context_dict(feed_type: str, integration_context: List[Any] = []) -> \
str:
"""
To get last fetched key of feed from integration context.
:param feed_type: Type of feed to get last fetched key.
:param integration... | 64eeb53cf00636dfc73866c64c77e2964149209e | 70,584 |
def add_pano_sensors_to_config(config: CN) -> CN:
"""Dynamically adds RGB and Depth cameras to config.TASK_CONFIG, forming
an N-frame panorama. The PanoRGB and PanoDepth observation transformers
can be used to stack these frames together.
"""
num_cameras = config.TASK_CONFIG.TASK.PANO_ROTATIONS
... | 16eda122838cf7a11c197f96019f3a5a3bfa0c36 | 70,585 |
def edit_ttp(cid, old_ttp, new_ttp, analyst):
"""
Edit an existing TTP.
:param cid: ObjectId of the Campaign.
:type cid: str
:param old_ttp: Original value of the TTP.
:type old_ttp: str
:param new_ttp: New value of the TTP.
:type new_ttp: str
:param analyst: The user editing the TT... | 33e45e07e66d32619fdea73bdadce559255969eb | 70,586 |
import re
def english_syllables(word):
"""Simple heuristic for the number of syllables in an English word. 91% agreement with CMUDict."""
pos = ["[aeiouy]+", "[^cgj]eo|[^cgst]ia|ii|[^cgstx]io|io$|[^g]iu|[^qg]ua|[^g]uo", "^mc|(s|th)ms?$", "[aeiouy]ing"]
neg = ["[aeiouy]n?[^aeiouy]h?e$", "[aeiouy]([^aeiouyt... | 000a353633c25067472c131c78a8c16eda45b522 | 70,587 |
def compute_cooccurence(motives, ids=None):
"""compute_cooccurence."""
if ids is None:
ids = [id for id in motives]
seqs_summary = defaultdict(list)
for seq_id, begin, end, i in hits(motives, ids=ids):
seqs_summary[seq_id].append((begin, end, i))
distances = defaultdict(list)
si... | 4f942753cc64703fc297781bbf5f37085014ae85 | 70,588 |
def sequence_contains_non_standard(sequence):
"""
Checks if a sequence contains non-standard nucleotides
"""
return any([x in sequence.lower() for x in NON_STANDARD_NUCLEOTIDES]) | 419b544e429d4d6370d3198b54b17d4356801ca0 | 70,589 |
def employee_to_dict(employee_id):
"""
Returns employee dictionary representation.
:param employee_id: employee id
:return: employee dictionary representation
"""
employee = get_employee_by_id_service(employee_id)
return {
'id': employee.id,
'forename': employee.forename,
... | 3ad97c55e8f356f588f3607660613c2d1dc8c553 | 70,590 |
def parse_file(data_dict):
""" takes the streptomedb dictionary and returns a list of lists with
NPs which is easy to use
data_dict: strep dictionary created with make_dict()
"""
key_list = []
for key in data_dict.keys():
key_list += [key]
value_list = []
for value in d... | ad1c80729bf38b868c839aef2b9b6d76d1ad17d5 | 70,592 |
import scipy
def besinc(x):
"""The sombrero, jinc, or besinc function
(https://en.wikipedia.org/wiki/Sombrero_function --- note this
implementation follows the convention from Blahut, Theory of
Remote Image Formation, 2005, see p. 82).
"""
y = np.empty_like(x)
I = np.where(x != 0)
y[I... | 0bdcec13b84d0bce048dd0ce7398a21c0118a244 | 70,593 |
import time
def sgd_subset_dense(train_X, train_Y, w, iter_sgd, alpha, regParam) :
"""
Computes stochastic gradient descent for a partition (in memory)
Parameter:
train_X : list of pyspark.mllib.linalg dense or sparse vectors
train_Y : list of labels
w : numpy matrix holding the model weights
i... | a0e88fd04886618ce0966fe4d1a206a852fe9954 | 70,594 |
import math
def _parseSeconds(data):
"""
Formats a number of seconds into format HH:MM:SS.XXXX
"""
total_seconds = data.total_seconds()
hours = math.floor(total_seconds / 3600)
minutes = math.floor((total_seconds - hours * 3600) / 60)
seconds = math.floor(total_seconds - hours * 3600 - min... | b01a66f66dc3cdc930aff29069c865cab5278d08 | 70,595 |
def creates_cycle(connections, test):
"""
Returns true if the addition of the 'test' connection would create a cycle, assuming that no cycle already exists in
the graph represented by 'connections'.
:param connections: List of connections, with each connection a tuple of form (sender, receiver)
... | 43d942fb413ee720200081754dceb99ca87bf1cd | 70,596 |
import torch
def PredictRegularizationConstrainR(P, Q, R):
"""
FunkSVD+Regularization+矩阵R的约束(取值只能是0-5, P,Q>0)
"""
B = 0.1 # 正则话的系数
R_pred = torch.mm(P, Q.t()) # 矩阵相乘
N,M = R.shape
loss = 0
for i in range(N):
for j in range(M):
if R[i][j] > 0:
loss =... | f9cb4ced0f780f8002b890e332559e2e51d8fd35 | 70,597 |
def get_top_side_rect(rect):
"""
this function return a manipulator rect for the transform
handler.
_____________*____________
| |
| |
|________________________|
"""
if not rect:
return None
return QtCore.... | d59bb24fbec35e6d5348c8058fcebbf97a7a4f87 | 70,599 |
from pathlib import Path
def generate_filename(candidate: Path) -> Path:
"""Generate a filename which doesn't exist on the disk. This is not atomic."""
orig = candidate
i = 0
while candidate.exists():
stem = orig.stem
candidate = orig.with_stem(f"{stem}-{i}")
i += 1
return... | 4a304b30aac5091e8a3f59db3d7d293b272b92ef | 70,600 |
import io
def build_report(
*tables_desc: TableDesc,
width: int,
height: int,
) -> bytes:
""" Сформировать отчет
:param tables_desc: Описания таблиц для отчета
:param width: Ширина листа
:param height: Высота листа
"""
with io.BytesIO() as buffer:
doc = Simp... | 18c584995d4bec27ed0a64dc0afd4ad774d2ca11 | 70,601 |
def _IsMPKeyName(name):
"""Returns True if the key name looks like MP (not pre-MP).
An MP key name does not contain the strings "_premp" or "_premp", and
ends in something like "_mp" or "_mp_v2" or "_mpv2".
"""
return (_MP_KEY_NAME_PATTERN.search(name) and
not _PRE_MP_KEY_NAME_PATTERN.search(name)) | 24024cd1a3da57f0321f643f0b62e6e5427167bc | 70,602 |
def getPlaylists(sg):
"""
Returns all playlists based on the show specified in the configuration file(s).
Args:
param1 (shotgun_api3.Shotgun): Shotgun DB Object.
Returns:
list: List of dictionaries with Shotgun entity information.
"""
sgPlaylists = sg.find(
"Playlist",... | cec358f95dc9353a6636dd3adcea2c064626e069 | 70,603 |
def load_data(filename: str):
"""
Load Agoda booking cancellation dataset
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector in either of the following formats:
1) Single dataframe with last column representing ... | 3ab8e167df2305017fa3a6690f8b620020d75071 | 70,604 |
from typing import Optional
def code_block(text: str, language: Optional[str]) -> str:
"""Formats text for discord message as code block"""
return f"```{language or ''}\n" f"{text}" f"```" | c54d5b3e6f456745817efd03b89bd56d7fe4794e | 70,605 |
def get_current_gw():
"""
Returns the current gameweek
"""
return BOOTSTRAP_STATIC['current-event'] | e4965f3155e4d36a2085b76a1bbf09c355a0b226 | 70,606 |
import sqlite3
def version(database):
""" """
conn = bou.backing.open(database)
try:
with conn:
curr = conn.cursor()
smt = curr.execute("""
SELECT migration
FROM _bou
ORDER BY id
LIMIT 1
""")
... | dada19f0f33f87a320db189faaca9f0a13d0fc55 | 70,607 |
def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... | 22a2331b5772f00514ca1ddbb44f6e94e3782d76 | 70,609 |
from typing import Any
def tvt_by_nors(
ccagt: CCAgT,
categories_infos: CategoriesInfos,
tvt_size: tuple[float, float, float] = (.7, .15, .15),
**kwargs: Any
) -> tuple[set[int], set[int], set[int]]:
"""This will split the CCAgT annotations based on the number of NORs
into each image. With a s... | 213c201c60b3186dd59fbb8e6576bcabffe64de0 | 70,610 |
from typing import Iterable
def get_event_log_records(
instance: DagsterInstance,
last_storage_id: int,
record_filter_limit: int
) -> Iterable[EventLogRecord]:
"""Returns a list of Dagster event log records in ascending order
from the instance's event log storage.
:param instance: ... | cf2ecc1284427fb5c7cb58ec9e26d30c303cd815 | 70,611 |
import requests
import time
def get_encryption_data():
"""Dynamically obtain the Auth token public key and encryption algorithm.
This function will make an API call to the auth server upon service start up
when the environment variable ``PRODUCTION`` is set to ``true`` or ``beta``.
The value of ``bet... | 3cfd512657984d68e0ebae140d2bc1daddf09e98 | 70,612 |
def skia_select(conditions, results):
"""Replaces select() for conditions [UNIX, ANDROID, IOS]
Args:
conditions: [CONDITION_UNIX, CONDITION_ANDROID, CONDITION_IOS]
results: [RESULT_UNIX, RESULT_ANDROID, RESULT_IOS]
Returns:
The result matching the platform condition.
"""
if len(conditions) != 3 o... | 3304fd1c55dffbeb42a1a418040813ff2534b8f4 | 70,613 |
def date_search(date: str) -> list:
"""
Для поиска по дате в поле published_item таблицы rss_tab.
Добавляет данные в log_tab, при поиске.
:param date: подстрока, вхождение которой в published_item необходимо найти.
:return: список словарей с результатами поиска из rss_tab.
"""
try:
... | 6c9cb097b8b8220b559a734264a0afd112d4042c | 70,614 |
from datetime import datetime
import json
def api(request):
"""
Handle the follow params:
?search=Something+yadda
&start=2009-01-01-2014-12-30&end=2014-12-30
&point=-33.4246,151.3441,
&distance=100
Code mostly written by Lyndon D'arcy
(imported from https://github.com/logworthy/... | 0f860a7432d54a48c8adabb90737dcfa1d0278c6 | 70,615 |
from typing import Union
def _flight_intersects(
flight: Flight, shape: Union[ShapelyMixin, base.BaseGeometry]
) -> bool:
"""Returns True if the trajectory is inside the given shape.
- If an Airspace is passed, the 3D trajectory is compared to each layers
constituting the airspace, with correspondi... | 041644b9bb92d32943071cd7c51f545d44cfe271 | 70,616 |
import psutil
def check_cpu_constrained():
""""Return True if the cpu is having too much usage, False otherwise."""
return psutil.cpu_percent(1) > 80 | b5af66c73b9c85b9824b15bffc3915e69efa07d2 | 70,617 |
def np_inverse_softmax(x):
"""Invert a softmax operation over the last axis of a np.ndarray."""
return np.log(x / x[Ellipsis, :1]) | 124297e509f7d9b836b7c618335bde951cbc9087 | 70,618 |
def Fredkin_check(function):
"""Decorator to check the arguments of calling Fredkin gate.
Arguments:
function {} -- The tested function
"""
def wrapper(self, control_qubit):
"""Method to initialize Fredkin gate.
Arguments:
control_qubit {Qubit} -- Possible valu... | 7b62bc1998baffcffa896a6a549c3044ebbc9abd | 70,620 |
def current_scopes():
"""
init security setting
:return: pending
"""
return [] | 2aa8500f0c1487723d74d975cf9e50f92904e1de | 70,622 |
def training_decoding_layer(dec_embed_input, target_length, dec_cell, initial_state,
output_layer, vocab_size, max_target_length):
"""Create the training logits"""
training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,
... | 60bcf80d8f9b8a540c23ae7fb474de240fc8e708 | 70,623 |
def subtend(x1, y1, x2, y2):
"""ANGLE SUBTENDED BY TWO VECTORS (wrt THE ORIGIN)"""
# v1 (dot) v2 = |v1| |v2| cos(theta)
# d = r1 r2 cos(theta)
d = dot([x1, y1], [x2, y2])
r1 = hypot(x1, y1)
r2 = hypot(x2, y2)
costheta = d / (r1 * r2)
theta = arccos(costheta)
return theta | bfe8993c836c94cccc2cd98f85693cb1a53496ee | 70,624 |
def GetWifiInterface():
"""Gets the first Wi-Fi interface name.
Returns:
interface: str, the first Wi-Fi interface name (e.g. en0) or None if no
interface exists.
"""
interfaces = systemconfig.GetNetworkInterfaces()
for interface in interfaces:
if interface['type'] == 'IEEE80211':
return ... | a99b13ee7ea047d3461035fdda9d0f7b2f201d09 | 70,625 |
from typing import List
def _load_images(img_list: List) -> np.ndarray:
"""
This private function loads the numpy array image files
that are passed within input parameter and append them into a list
:param img_list: List, Contains absolute paths to image.npy files
:return: N-dimensional array, Loa... | eb47d06e29f3dbc22dcebd1cc636fc3e95c222bf | 70,626 |
import csv
def load_farm_attributes(crop_type):
""" Loads the attributes for specified crop to be used in the farm vector
attribute table """
with open(farm_attribute_table_path(crop_type), 'r') as f:
reader = csv.DictReader(f)
return list(reader) | e9df8c50c4198a417dd5cd0cde0dd69e2f195c91 | 70,627 |
def softmax_layer(avg_per_word, U, b, y_mask, maxw, training=False):
"""
Produces the final labels via softmax
:param avg_per_word: Output from word-averaging
:param U: Classification weight matrix
:param b: Classification bias layer
:param y_mask: Because not all fragments are the same length, ... | d54c6bad48580095671747e18d4e694ae34bde7b | 70,628 |
from typing import Dict
from typing import Any
from typing import List
def github_installation(
options: Dict[str, Any],
env: sphinx.environment.BuildEnvironment,
) -> List[str]:
"""
Source to provide instructions for installing from GitHub.
:param options: Mapping of option names to values.
:param env: Th... | e1d8d80cf0e84479e77e5e2093705e9b639b8e48 | 70,629 |
def attention_bias_local(length, max_backward, max_forward):
"""Create an bias tensor to be added to attention logits.
A position may attend to positions at most max_distance from it,
forward and backwards.
This does not actually save any computation.
Args:
length: int
max_backwar... | 7548dc0d6ecdaa9dfcba66845d203c7fa1e088ed | 70,630 |
def demo_regression_report():
"""Make a demo regression report."""
x = np.linspace(0, np.pi * 4, 1001)
truth = np.stack([np.sin(x), np.cos(x)], axis=-1)
label = np.random.binomial(1, .2, size=x.shape)
predict = np.stack([
truth[:, 0] + (
(1 - label) * np.random.normal(0., scale=.... | 895dd769ab44025fdd71a01bb87011e4a142dec0 | 70,631 |
from re import T
import scipy
def model2geogcoords(
xg: dict[str, T.Any],
parm: xarray.DataArray,
lalt: int,
llon: int,
llat: int,
altlims: tuple[float, float] = None,
glonlims: tuple[float, float] = None,
glatlims: tuple[float, float] = None,
):
"""
Grid the scalar GEMINI outp... | af4feeb974671a761e3a979bb45d6ad097d03755 | 70,633 |
import re
from typing import Counter
def tokenizeLyrics(genius,artist_name,track_name):
"""
Tokenize Lyrics of song
Arguments:
genius:
artist_name:
track_name:
Return:
line_split_lyrics:
word_frequency
"""
#Initialize tokenizer
tknzr = nltk.Twee... | 365a7e522b9d2fece6081ea01513f13e941c23f2 | 70,634 |
def api_asset_get():
"""Get assets with specified names from the bank"""
names = request.args.getlist("name")
result = []
for name in names:
asset = app.bank.get(name)
if asset:
result.append(asset)
return jsonify(sorted(result)), 200 | 83aff57d194f877967caa962b5e6abe8580e4f67 | 70,635 |
import itertools
import scipy
import numpy
def cluster(point_list, std, chance_correct):
"""
Given a list of points (x,y), the standard deviation of the point position measurements,
and the chance that the point is correctly identified as part of the group,
this returns the expectation point of where ... | f440c96578a6b0b4aa219e60604046818568896c | 70,636 |
def upsample_ps(x, r=(1, 1)):
"""
Performs phase shift upsampling for width and height
Args:
x: Tensor to upsample
r: A tuple of upsample factors(height and width) (Default value = (1)
Returns:
Tensor with height of original_height*r[0] and width original_width*r[1]
"""
x = _p... | cabd3c4f76d2f099d71b08502854d362e91972f5 | 70,637 |
def _AddMergeFromStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def MergeFromString(self, serialized):
length = len(serialized)
try:
if self._InternalParse(serialized, 0, length) != length:
raise message_mod.DecodeError('Unexpected end-group tag.')
except (... | 777201a242f0a9dfca8b7234546926dd8b8a6188 | 70,638 |
def check_ratio_sum(ratio):
"""
Check the given ratio is valid or not. Sum of ratio should be 100
"""
train_ratio = int(ratio[0])
val_ratio = int(ratio[1])
test_ratio = int(ratio[2])
qa_ratio = int(ratio[3])
total = train_ratio + test_ratio + val_ratio + qa_ratio
if total != 100:
raise ValueError("Sum of al... | 34ce3c7c9e0edecbdaa54e44ed39060df150c8dd | 70,640 |
def check_box(
iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy"
):
"""Check box for tp/fp/ignore.
Arguments:
iou (np.array): iou between predicted box and gt boxes.
difficult (np.array): difficult of gt boxes.
order (np.array): sorted order of iou's.
... | 581aac0b3541535c6cd91243ab99a842d0183f8b | 70,641 |
def check_mnist_cifar_dataset(method):
"""A wrapper that wrap a parameter checker to the original Dataset(ManifestDataset, Cifar10/100Dataset)."""
@wraps(method)
def new_method(*args, **kwargs):
param_dict = make_param_dict(method, args, kwargs)
nreq_param_int = ['num_samples', 'num_parall... | 932014d6a6e6046a4862d6c02b06414ab9ee4856 | 70,642 |
def parent_technique_of(thesrc):
"""return subtechnique_id => {technique, relationship} describing the parent technique of the subtechnique"""
return get_related(thesrc, "attack-pattern", "subtechnique-of", "attack-pattern")[0] | f91c65ad8769b3adc157a7c783f15c6f49b0e465 | 70,643 |
def index():
"""
主页
:return:
"""
return render_template('index.html', remote_address=request.remote_addr) | 62105d3b1373ff159655ae8e390081f65924b848 | 70,644 |
from typing import List
def get_mol_props_for_map(mols: List[Chem.Mol]):
"""Return the heavy atom count, carbon fraction, ring atom fraction and largest ring size."""
hac = []
c_frac = []
ring_atom_frac = []
largest_ring_size = []
for mol in mols:
atoms = mol.GetAtoms()
size =... | 0b5dbbe1e0ec17edc7c28cced3f196c5a38e6023 | 70,645 |
def get_chat_messages(chat_slug) -> QuerySet:
""" get chat messages """
return Chat.objects.get(slug=chat_slug).message.filter() | ca80795bcbb99f6cb68dd3531d86d07927295f9e | 70,646 |
def mock_qnode(mock_device):
"""Simple PassthruQNode with default properties."""
def circuit(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
node = PassthruQNode(circuit, mock_device)
return node | 97e1e4bbf3b879e80777d185ed219c54b11bb4cd | 70,647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.