content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import re
def group_files(filenames,
filename_re=FILENAME_OPFILE_RE,
verbose=False):
"""
Group all filenames by their session ID, camera (aka recording), resolution (i.e. width x height) and frame index.
:param filenames: List of filenames to be grouped together.
... | 01132c39f7ec060084d91927e5d51a2c4c8b0fa8 | 3,626,400 |
from typing import Any
from typing import Type
from typing import cast
def create(
name: str,
/,
**fields: Field[Any],
) -> Type[Structure]:
"""
Functional API for creating structure.
:param name: structure type name
:param fields: structure fields
"""
cls = cast(StructureMeta, ... | 1c543e86a45ae8758ac6923eaf75a48942707600 | 3,626,401 |
from typing import Optional
def from_pretty_midi(
midi: PrettyMIDI,
resolution: int = DEFAULT_RESOLUTION,
mode: str = "max",
algorithm: str = "normal",
collect_onsets_only: bool = False,
first_beat_time: Optional[float] = None,
) -> Multitrack:
"""Return a Multitrack object converted from ... | bdf0c1f1c85f5a2ca8f9818e050b64a51e87ddf5 | 3,626,402 |
def assign_role():
"""
This API assigns one role to the user in the request
"""
user_id = request.json.get('user_id', None)
role = request.json.get('role', None)
user = query_validated_user(user_id)
if user:
user.role = role
db.session.add(user)
db.session.commit()
... | 688e01369653115866c34fe8969f15410d066ddc | 3,626,403 |
import os
import json
import atexit
def _create_tmp_customize(bases, prefix=None):
"""Create a temporary """
temp_dir = TemporaryDirectory(prefix=prefix)
# kustomize only recognizes relative paths, so convert that
bases = [os.path.abspath(base) for base in bases]
bases = [os.path.relpath("/", ba... | 30817c526d51869316d3bca872a0b1c74ab7a021 | 3,626,404 |
def segment(image):
""" Segment the image -- return the scores.
:param image: An image with shape 3 x 360 x 480 (sized to match the net)
:return: The output scores (len(LABELS) x 512 x 512)
"""
assert image.shape == (3, 360, 480)
net().blobs['data'].data[...] = np.array([image])
results =... | ff93d246ae63fb7a273a24adc95e6e4666c0797e | 3,626,405 |
def get_reg_name(*args):
"""
get_reg_name(int reg, size_t width, char buf, int reghi=-1) -> ssize_t
get_reg_name(int reg, size_t width, char buf) -> ssize_t
"""
return _idaapi.get_reg_name(*args) | 21c0085f11efe7de93e89dc047165cd8235da184 | 3,626,406 |
def ast_for_factor(factor: 'Ast', ctx: 'ReferenceDict'):
"""
factor ::= [unaryOp] invExp [suffix];
"""
assert factor.name is UNameEnum.factor
unary_op: 'Tokenizer' = None
suffix: 'Tokenizer' = None
n = len(factor)
if n is 3:
unary_op, inv, suffix = factor
elif n is 2:
... | 1b25b144f72adea6e4e5fb6f2bb2c9ee9a69515f | 3,626,407 |
def spherical_to_cartesian_4d(thetas, r=1.0):
"""
Converts points on the hypersphere S^3 in R^4 given in
spherical coordinates to their cartesian value.
:param thetas: [N, 3]
thetas = [theta_1 | theta_2 | theta_3], with theta_i [N, 1]
0 <= theta_1 < 2 * pi and
0 <= theta_2 < pi
... | b8624b7c546ca61ab6b4aa17ab191aaa40331d4e | 3,626,408 |
def sheets_get_ranges(spreadsheet_id, sheet_ranges):
""" Returns a Value Ranges for the input ranges.
See Sheets API Documnetation for rangee syntax
Sample: ['Sheet1', 'Sheet2] returns all values on these sheets
"""
service = get_sheets_service()
response = service.spreadsheets().value... | 5586b3d6566d8106b5a154b82b550bade4b3a354 | 3,626,409 |
from typing import Any
from typing import List
def Json(v: Any, fname: str, lazy: List[Any]):
"""
Default JSON encoder using ``json.dumps``.
This version encodes ``None`` as json null value.
"""
return text_escape(dumps(v)) | 036252d6970802c7fea2b819184e1281469e7b08 | 3,626,410 |
def sem_id_get(obs_id):
"""
Retrieves all the sem_ids associated with an observer
http://vm-webtools.keck.hawaii.edu:50001/v0/semesterIds/?obs_id=2003
:param obs_id: observer id
:type obs_id: int
:rtype: List[str]
"""
# authenticate,
# use a master id in check_obs_id or check ==... | f1f11f827fa27f807396acd4714aa31d9c4e0de9 | 3,626,411 |
def welcome():
"""Print a welome message."""
print "Python %s %s, %s" % (NAME, VERSION, BUILDDATE)
print "A %s" % DESCRIPTION
print
return() | a3b624af86aa861b6d7d529ce8d08ad33a4a4dae | 3,626,412 |
def _update_improper_axes(
n, ax, axes, atomcoords, groups, rtol, atol, normalize=False # found axes
):
"""Update axes with ax and return it.
Helper function for _get_improper_axes.
"""
if normalize:
norm = np.linalg.norm(ax)
if np.isclose(norm, 0.0, rtol=rtol, atol=atol):
... | ae623a8c17110ecde23391ef709be76904d76b69 | 3,626,413 |
def resolver_for(domain, mname):
"""Return a resolver object whose nameservers are obtained by
asking the SOA MNAME (master name) for its addresses and listing
the remaining NS addresses after that. Master is assumed to be
most up-to-date, but may not always be reachable."""
addresses = []
maybe... | 1b3dad4fec5a1c591401ff6b709bc05ce09e7411 | 3,626,414 |
def div(client, symbol, timeframe="6m", col1="open", col2="close"):
"""This will return a dataframe of
Vector Arithmetic Div
for the given symbol across the given timeframe
Args:
client (pyEX.Client); Client
symbol (string); Ticker
timeframe (string); timeframe to use, for pyEX.... | 68da946181e39c8b2ec03fb82ee63da1c4804512 | 3,626,415 |
import itertools
def create_possible_expected_messages(message_template, expected_types):
"""
Some error messages contain dictionaries with error types. Dictionaries
in Python are unordered so it makes testing unpredictable. This
function takes in a message template and a list of types and returns
... | 674dec990e0786d3e313a9b8deec72e37588d8eb | 3,626,416 |
def chkSort(array):
"""Make sure sort actually did its job"""
for i in range(0, len(array)-2):
if array[i] > array[i+1]:
print("{} is not greater than {} for indices=({},{})").format(array[i+1], array[i], i, i+1)
return False
return True | 759c0b64fcf41121433264abbb80203534355e98 | 3,626,417 |
import json
def fetch_dss_files(uuid):
"""
Initiate checking out a file for download from the HCA data store (DSS)
parameters:
- name: uuid
in: path
type: string
description: UUID of the file to be checked out
- name: fileName
in: query
ty... | c396b6b530a905eaa1df9f0b32289776edf334c9 | 3,626,418 |
from sys import path
def topology_tiscali2(**kwargs):
"""Return a scenario based on Tiscali topology, parsed from RocketFuel dataset
Differently from plain Tiscali, this topology some receivers are appended to
routers and only a subset of routers which are actually on the path of some
traffic are sel... | 2ea884373568f7dfa67a35c00fd50c87c7df8059 | 3,626,419 |
from typing import List
from typing import Optional
from typing import Tuple
def eval_final_hand(cards: List[Card]) -> Optional[Tuple[str, PokerHand, int]]:
""" Turns a list of 7 cards into a string representation of the best hand possible with those 7 """
cards.sort(reverse=True)
# Get valid five card c... | 05161fb9e806dd6ab172ba4e12cbd924b8eb19f0 | 3,626,420 |
from typing import Tuple
def grab_color() -> Tuple[Tuple[int, int, int], Tuple[int, int]]:
"""
returns a list with a tuple containing the RGB value of the most
present color around the mouse and the position at the time of measurement
"""
pos = mouse.get_position()
m = 2
rect = (pos[0] - ... | d133ff7764e64509a2da04d80d1725468c861593 | 3,626,421 |
import numpy
def get_dihedral_angle1(p0,p1,p2,p3):
"""http://stackoverflow.com/q/20305272/1128289"""
p = [p0, p1, p2, p3]
b = p[:-1] - p[1:]
b[0] *= -1
v = numpy.array( [ v - (v.dot(b[1])/b[1].dot(b[1])) * b[1] for v in [b[0], b[2]] ] )
# Normalize vectors
v /= numpy.sqrt(np.einsum('...i,.... | 9762342b6e1f0f6413e20569d96aadeeb0766374 | 3,626,422 |
def calc_delta_lampams2(
multipanel, constraints, delta_lampams, pdl, n_plies_to_optimise):
"""
calulates all ply partial lamination parameters in a multipanel structure
that correspond to a specific ply drop layout
INPUTS
- multipanel: multipanel structure
- delta_lampams: all ply par... | d3dd52bfcba94fe4f06d7c9b1aad25d827c48842 | 3,626,423 |
def merge_user_data(spark, table_type, table_num, start_num=0):
"""
:param table_type: 【str】 'click' or 'top' or 'play'
:return: 【dataframe】 返回每种行为数据所有表的merge表
"""
spark.sql("use {}".format(user_pre_db))
if start_num == 0:
ret = None
else:
# 本来想运行完,删除掉改过名的表merge_{}_{},但在保存前删除... | 48686485ea7f8e2aea790062d4cf0a5ca54142a2 | 3,626,424 |
import os
import email
def get_version_from_pkg_info():
"""Get the version from PKG-INFO file if we can."""
pkg_info_path = os.path.join(os.path.dirname(__file__), 'PKG-INFO')
try:
pkg_info_file = open(pkg_info_path, 'r')
except (IOError, OSError):
return None
try:
pkg_info... | 010d3872fb0b0ca753ad64b318a5da148b38968f | 3,626,425 |
from typing import Counter
def gridToList(box):
"""
:summary: Reads text fields into a list for racksorter module
:param QGroupBox box: group box to read the grid from
:rtype: list
:return: racksorter module-ready list of the permutation
"""
l = []
layout = box.layout()
positions ... | a91dbe0316502f58d4144b22ddacdb26cdf215e7 | 3,626,426 |
def get_unavailable_agents(day):
"""Determine agents with no availability for a given day."""
day_number = day.weekday()
unavailable = set()
for handle in df_agents.index:
if len(df_agents.loc[handle, "slot_ranges"][day_number]) == 0:
unavailable.add(handle)
print(f"\nUnavailab... | 453ac16b4335201925ebad5fa48c915e8f92f2c5 | 3,626,427 |
def compare_descriptor_types(a, b):
"""Compare two metric types to sort them in order."""
# pylint: disable=invalid-name
a_root = a['type'][len(CUSTOM_PREFIX):]
b_root = b['type'][len(CUSTOM_PREFIX):]
return (-1 if a_root < b_root
else 0 if a_root == b_root
else 1) | b34288136ce83c16671df03fd68d9694b2ee0228 | 3,626,428 |
def get_image(image) -> Image.Image:
"""
Gives back the given image as a PIL.Image.Image instance
Args:
image: the given image, it can be a filepath (str, bytes or Path), an URL (which will be downloaded), a BytesIO or a PIL.Image.Image instance
Returns:
A PIL.Image.Image insta... | 3ac8c6606e8ea15c49860c0714bc73565d50a73f | 3,626,429 |
def get_worksheet(ts: ThoughtSpot, connection_guid: str, worksheet_guid: str) -> Worksheet:
"""
:param ts: The connection to ThoughtSpot for API calls.
:param connection_guid: GUID for the connection with the table to map to (not always the old connection)
:param worksheet_guid: GUID for the worksheet t... | 4ce5b567317f744444f6478d4365a1fd84dcd792 | 3,626,430 |
def run_grover_search(number_of_qubits, oracle, oracle_args):
"""
Uses Grover's quantum search to find the single answer to a problem
with high probability.
Parameters:
number_of_qubits (int): The number of qubits that the oracle expects
(the number of qubits that the answer will co... | cc47f645bbd6c9a12acf4698060fde3e76d92097 | 3,626,431 |
def compute_epsilon(target_delta, steps, noise_multiplier, batch_size, dataset_size):
"""Computes epsilon privacy value for given hyperparameters."""
if noise_multiplier == 0.0:
return float("inf")
orders = [1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64))
sampling_probability = batch... | 02a52d87f36d04481efdb70c81b1bd2760c77732 | 3,626,432 |
import re
def findCisIndexes(cisSplits, protSeq, overlapFlag, maxDistance):
"""
Called by cisOrigins(), this function returns the location data of where different pairs of cisSplits (which
combine to form a given peptide) exist in a protein sequence. The output data structure is a series of embedded
l... | 013b1776225b6b294e9489280734730a6411d502 | 3,626,433 |
def export_selected_games_pgn_no_comments(grid, filename):
"""Export selected records in PGN export format excluding comments.
If any records are bookmarked just the bookmarked records are exported,
otherwise all records selected for display in the grid are exported.
"""
if filename is None:
... | 74894757ac92612aaad3d14eea822e1c6717488f | 3,626,434 |
def add_dimensions(G, naming_convension: NamingConvension = None) -> list:
""" Walks graph setting all edge names and dimensions
"""
if naming_convension is None:
naming_convension = DefaultNamingConvension(G)
for edge in G.edges():
edge.params = None
steps = []
indexes = {'inpu... | c369bb2b8452224b9e91b1d57315d8b2662196df | 3,626,435 |
from datetime import datetime
def add_day(date: str, format_='%Y-%m-%d', to_str=False, **kwargs) -> datetime:
"""一个日期加多少天或者时间
:param date: 一个正确的日期
:param format_: 日期格式化
:param to_str: 是否打印字符串
:param kwargs: 可以填写 :days=xx,seconds=xx,microseconds=xx,milliseconds=xx,minutes=xx,hours=xx,weeks=xx
:... | b8810e177347fb6a0d28e454c4f4d37b98354f89 | 3,626,436 |
def fetch_swiss_exchanges(session, target_datetime, logger):
"""Returns the total exchanges of Switzerland with its neighboring countries."""
swiss_transmissions = {}
for exchange_key in ['AT', 'DE', 'IT', 'FR']:
exchanges = ENTSOE.fetch_exchange(zone_key1='CH',
... | 4441215d4c4f1b9e162ef5dedec156d88783308d | 3,626,437 |
import json
def delete_volumes(repository_name, branch_name):
"""
Trigger lambda function that deletes EBS volumes.
:param repository_name: Full repository name.
:param branch_name: Branch name that is deleted.
:return: Number of EBS volumes that are deleted successfully, number of EBS volumes tha... | 939434708567cba4c20ac30595220c7da5299a9e | 3,626,438 |
from albumy.models import User
def load_user(user_id):
"""根据session中的user_id获取User对象"""
user = User.query.get(int(user_id))
return user | 925c573e747d5a5fa388d2368c79e81730ee396d | 3,626,439 |
def load_saved_recipes(filename):
"""
Internal method for reading contens of given file.
"""
contents = []
try:
# Read file line by line, recipe by recipe
with open(filename, 'r') as recipes_file:
contents = recipes_file.readlines()
return contents
... | 60cf9ace8cd3cbcc40aae6fa5c1d2def50bf95b9 | 3,626,440 |
def get_range(arr, refarea):
"""
determine plot scale range
"""
auto_crange: float = 99.8
refvalue = np.nanmean(arr[refarea[0]:refarea[1], refarea[2]:refarea[3]]) # reference values
if str(refvalue) == 'nan':
refvalue = 0
dmin_auto = np.nanpercentile((tscuml[-1, :, :]), 100 - auto_cr... | 9807359eb6cf37f445a1550069e214b999a010a1 | 3,626,441 |
def label_repo(
source: str = typer.Argument(CWD),
input: str = typer.Option('', '-i', '--input'),
output: str = typer.Option('', '-o', '--output'),
template: str = typer.Option('', '-t', '--template'),
) -> int:
"""
Labels the local data (no template handling yet).
"""
repo_root = input... | e5dc00c9b5bb41e031158d37737cd3e1679e4e48 | 3,626,442 |
def get_longest_word_trie_ds(words: list[str]) -> str:
"""Returns the longest word character composable from other words in input array
Args:
words: array of strings words representing an English Dictionary
Returns:
the longest word in words that can be built one character at a time by
... | 043b56db322c6b4eedbac0d9c237ba996cbdb03c | 3,626,443 |
def occnet_decoder(embedding, samples, apply_sigmoid, model_config):
"""Computes the OccNet output for the input embedding and its sample batch.
Args:
embedding: Tensor with shape [batch_size, shape_embedding_length].
samples: Tensor with shape [batch_size, sample_count, 3].
apply_sigmoid: Boolean. Whe... | a16e5dd8ee594df79a0178f96e4bbd987c7e3d0e | 3,626,444 |
from typing import Sequence
from typing import Callable
from typing import Any
async def async_combine_middlewares(
middlewares: Sequence[Middleware],
web3: 'Web3',
provider_request_fn: Callable[[RPCEndpoint, Any], Any],
) -> Callable[..., RPCResponse]:
"""
Returns a callable function which will c... | e87eae3e97f12d2eec9a83849e7152a5b5d221bf | 3,626,445 |
def embedding_attention_seq2seq_context(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size,
num_heads=1, output_projection=None,
... | 9e89ae6afa90bce223b9185eb0f6d2ad41916dc0 | 3,626,446 |
import argparse
def is_positive_integer(value: str) -> int:
"""
Helper function for argparse.
Raise an exception if value is not a positive integer.
"""
int_value = int(value)
if int_value <= 0:
raise argparse.ArgumentTypeError(f"{value} is not a positive integer")
return int_value | 69ac61d949ddac0788dade92da28f37842c209ea | 3,626,447 |
import glob
def _create_image(dirs, class_info, params, count, output_dir):
"""Creates a dataset image at the desired directory. Returns bbox cache for creating annotations."""
# open the map and create a copy of it as a new image
background_image = Image.open(choice(glob.glob(dirs['maps']+'.png')))
n... | c5a06ff125d47f931e7a82ad1a4042aa735d64ba | 3,626,448 |
def compute_predictions_for_a_single_pipeline(p,df_X):
"""
This function finds predictions for a single pipeline (it is assumed that
this is already the best model)
Parameters
----------
p : prediction_class object
df_X: DataFrame
Input dataframe with possible all the original attr... | 9eda59f867dffa9d559774e68d314bd7698942f1 | 3,626,449 |
from typing import Sequence
from re import T
from typing import Callable
def min_edit_distance(
source: Sequence[T], target: Sequence[T],
ins_cost: Callable[..., int] = lambda _x: 1,
del_cost: Callable[..., int] = lambda _x: 1,
sub_cost: Callable[..., int] = lambda x, y: 0 if x == y el... | d2e36275d2de9c27a1d910371059cabed54b52a7 | 3,626,450 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Home Connect light."""
def get_entities():
"""Get a list of entities."""
entities = []
hc_api = hass.data[DOMAIN][config_entry.entry_id]
for device_dict in hc_api.devices:
entity_dicts... | 94c6473917ef31b2ca15ef70c2e783bd5cb2e565 | 3,626,451 |
import torch
def combine(batch, i):
"""
Combines the vectors for a specific type of sequence
and removes extra padding
Args:
batch: list
i: int
indicates the type of sequence
(4, 5, 6) --> (passage, query, qa_answer)
Returns:
vectors: 2d long tensor [bs x max_len]
"""
vectors = torch.cat([exampl... | 28ad3d16e89e0b3d2e3ef7cb966f577e7f1d1037 | 3,626,452 |
def GetNetworkConfig(has_external_ip, network):
"""Helper method to create a network config."""
network_interfaces = {
'network': network
}
if has_external_ip:
network_interfaces['accessConfigs'] = [{
'name': 'external-nat',
'type': 'ONE_TO_ONE_NAT'
}]
return network_interfaces | c0ee213c5c289fb2f6eb4b34fc18028233a1d162 | 3,626,453 |
import traceback
def base_federated_role(
construct,
resource_name: str,
federated_resource: str,
assume_role_action: str,
conditions: dict,
actions: list,
resources: list,
):
"""
Function that generates an IAM Federated Role with a Policy.
:param construct: Custom construct th... | ea3c83d215ae5064c889f12ac3cacdef388d312d | 3,626,454 |
from operator import inv
def zeros(a):
"""
Return the number of cleared bits in the sequence.
>>> assert zeros([0, 0]) == 2
>>> assert zeros([0, 1]) == 1
>>> assert zeros([1, 0]) == 1
>>> assert zeros([1, 1]) == 0
>>> assert zeros([1, 1, 1, 0, 1]) == 1
>>> assert zeros([0, 1, 0, 0, 0]... | 76f041390dfe43bcc583e39fc7a3e3d761f87c25 | 3,626,455 |
from datetime import datetime
import requests
def test_commit_in_last_year_no(monkeypatch):
"""
11. Has there been a commit in the last year?
"""
headers = {}
def mock_get(*args, **kwargs):
return MockResponseCommitsNo()
today = datetime.now()
test_date = datetime.strptime(BAD_DA... | d1145722747acc11cfdcaca8ee9066ad00572f42 | 3,626,456 |
def load_response_function(f, fstar=19.09e-3):
"""Load in LISA response function from file
Load response function and interpolate values for a range of frequencies.
Adapted from https://github.com/eXtremeGravityInstitute/LISA_Sensitivity
to use binary files instead of text. See Robson+19 for more detai... | c81e1ad91cda0b3f13a826605a797f72a62fc965 | 3,626,457 |
def edit(request):
"""
Save profile changes.
Args:
request (HttpRequest):
Request with user profile data passed with the `GET` method.
Returns:
An `HttpResponse` with search results.
"""
if request.method == 'POST':
# Apparently, `<form> .__ call __ ()` can... | 3050b80ec2ad23c8f73a84f7790541bae6199a90 | 3,626,458 |
def _make_training_input_fn(transformed_dataset):
"""训练数据处理"""
def input_fn():
x, y = [], []
s = set()
for tdt in transformed_dataset:
x.append(tdt["x"].tolist())
s.add(len(tdt["x"].tolist()))
y.append(tdt["y"])
print(list(s))
x, y = np... | d186c372af031224a090ac6c59b195528554a427 | 3,626,459 |
import select
def _do_select_for_plugin_api(params):
"""A version of select_for_plugin_api which accepts indirect products."""
if not params:
fail("Empty select_for_plugin_api")
expanded_params = dict(**params)
# Expand all indirect plugin_apis to point to their
# corresponding direct pl... | 83a30862c29ac88c736614102786ca2ac12c2bdd | 3,626,460 |
def escape_special_char(string):
"""
Is called on all paths to remove all special characters but it's not good.
Should be moved in core
Should be called only in get_wrapper_path and unescape_special_char in get_entry
and in script += 'menu_click... in menu_click as it's already done
... | cb3d4bd0d7370ec9c3d76543db8e3aafaf1bd8e8 | 3,626,461 |
import requests
import json
def search_product_with_application_id(app_id):
"""
Searches for Products based on application id association
:param app_id: application id that is being used in products
:return : True or False Indicates Success (Product Found) or Failure (Product Not Found) and ProductID
... | 6047de50d7760edded8b7376a0d9e8803fd8ede8 | 3,626,462 |
def jinc(x, normalize=True):
"""Evaluate the jinc function in the input corodinate ``x``
Parameters
----------
x : a single point or an ndarray
the input corodinate
normalize : bool, optional
if ``True`` (default), the normalized jinc (``jinc(0)=1``)
is returned
Returns... | c928569800eade81dd3cb7700daf795f7cf5c9d4 | 3,626,463 |
from pathlib import Path
def fp_search_rglob(spt_root="../",
st_rglob='*.py',
ls_srt_subfolders=None,
verbose=False,
):
"""Searches for files with search string in a list of folders
Parameters
----------
spt_root : string... | e8fe03f9549ae77147ec96263411db9273d2c4cb | 3,626,464 |
def decode_atbash(string, abc=None):
"""
Decodes a string with the classic atbash ciphering method
:param string:
:param abc:
:return decoded string:
"""
if abc is None:
abc = abc_en.copy()
elif type(abc) == list:
abc = abc.copy()
elif type(abc) != tuple:
retu... | 8302af799509304a8a1621a6d2a3fcb1387c930e | 3,626,465 |
def affine_subbasis(mode, dim=3, sub=None, dtype='float64'):
"""Generate a basis set for the algebra of some (Lie) group of matrices.
The basis is returned in homogeneous coordinates, even if
the group required does not require translations. To extract the linear
part of the basis: lin = basis[:-1, :-1... | 1496ad50c8ee30f351385477a23bed7f22bc6c1b | 3,626,466 |
def transition_layer(x, nb_channels, dropout_rate=None, compression=1.0, weight_decay=1e-4):
"""
Creates a transition layer between dense blocks as transition, which do convolution and pooling.
Works as downsampling.
"""
x = BatchNormalization(gamma_regularizer=l2(weight_decay), beta_regularize... | 629094116f43bb0ffa625796b2088b167079d1cf | 3,626,467 |
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (... | 6b14de32ba6835fe72ca5784aaedfbb4abe65362 | 3,626,468 |
import math
def unit_cross_product(uvec1, uvec2):
"""
Returns unit cross product between two unit vectors
Ensures the result is itself a unit vector
"""
cos = np.dot(uvec1, uvec2)
sin = math.sqrt(1 - cos**2)
# if the number of atoms is > 3 and there are 3 colinear atoms this will fail
... | de07e29df68d744c6c9903b9664abeab899b3869 | 3,626,469 |
import warnings
import uuid
def new_test_image():
"""
Creates an automatically generated test image.
In your testing `tearDown` method make sure to delete the test
image with the helper function `delete_test_image`.
The recommended way of using this helper function is as follows:
object_1.... | b70ffbd6ddd7c41674a1dc85d8331d36fb4a1d42 | 3,626,470 |
from pathlib import Path
import urllib
def move_data(
uid,
array_uri,
coverage_vector_uri,
cells_vector_uri,
outdir_uri,
access_key,
secret_key,
):
"""
Placeholder for moving data. Nothing fancy.
Not using until more testing is done regarding tiledb.move and
tiledb.consolid... | 6e76633e76a022f0be29e96040ac2e2bedff7abd | 3,626,471 |
def _(word):
"""Returns the translated word from the dict_lang python dict.
If the word is not found, it returns the same word (in english)
Arguments:
word {str} -- word to translate
"""
global dict_lang
if dict_lang == {}:
load_dictionary()
try:
word_result = di... | 1e16000ffe59454024b0825b8ebf5610adc0192a | 3,626,472 |
def diff(f, a, b, n):
"""An iterative version of a forward differentiation method."""
x = np.linspace(a, b, n+1)
y = np.zeros(len(x))
z = np.zeros(len(x))
h = (b-a)/float(n)
for i in xrange(len(x)):
y[i] = f(x[i])
for i in xrange(len(x)-1):
z[i] = (y[i+1] - y[i])/h
z[n] =... | 1acdc675bc5c825c45550680f71a57f8d94fbb48 | 3,626,473 |
def get_minimum(feature):
"""Get minimum of either a single Feature or Feature group."""
if hasattr(feature, "location"):
return feature.location.min()
return min(f.location.min() for f in feature) | aec98f5bc065c6a97d32bc9106d67579f76f7751 | 3,626,474 |
def compute_average_top_k_loss(loss: tf.Tensor,
top_k_percentage: float) -> tf.Tensor:
"""Computes the avaerage top-k loss per sample.
Args:
loss: A tf.Tensor with 2 or more dimensions of shape [batch, ...].
top_k_percentage: A float representing the % of pixel that should be... | 6cbc4a720f7441f06d315a1b4ce29dfd3e33f12d | 3,626,475 |
def isUniqueSFW(str):
"""
Given a string, checks if the string has unique charachters
Note that this solution is inefficient as it takes O(n^2)
"""
l = len(str)
for i in range(l):
for j in range(l):
if i != j and not ord(str[i]) ^ ord(str[j]):
return False
... | 369eddfc360a2661e063183a30c9d511a5deb3de | 3,626,476 |
def get_3x3_homothety(x,y,z):
"""return a homothety 3x3 matrix"""
a= [x,0,0]
b= [0,y,0]
c= [0,0,z]
return [a,b,c] | 5c6c2d8931334cc13297e787a079499753c1976c | 3,626,477 |
def http_die_soon(req):
"""Disable keep-alive to make HTTP proxy act like SOCKS. By doing this
wstan server can remain unchanged, but it will increase latency."""
dropped = [i for i in req.split(b'\r\n') if not _keep_alive.match(i)]
end = dropped.index(b'')
return b'\r\n'.join(dropped[:end] + [b'Con... | 2fe5326d97bd6fa8d84ac5c50b3570a038be7749 | 3,626,478 |
def non_max_suppression(boxes, scores, threshold):
"""
Performs non-maximum suppression and returns indices of kept boxes.
:param boxes: [N, (y1, x1, y2, x2)]. Notice (y2, x2) lays outside the box.
:param scores: 1d array of box scores.
:param threshold:
:return:
"""
assert boxes.shape[0... | 876b59ddf4e8955e4385873189313e8441119571 | 3,626,479 |
def extract_glimpse_numpy_like(inp, glimpse_shape, glimpse_offsets, name=None, uniform_noise=None, fill_value=None):
""" Based on: https://github.com/tensorflow/tensorflow/issues/2134#issuecomment-262525617
Works like numpy with pixel coordinates starting at (0, 0), returns:
inp[:, glimpse_offset[0] : g... | 94404ae41532eb142b9abf3bc03b4df296d9f642 | 3,626,480 |
def readShimadzuDatafile(fn, chapter_num=-1, return_all_sections=False):
""" read the ascii data from Shimadzu Lab Solutions software
the file appear to be split in to multiple sections, each starts with [section name],
and ends with a empty line
returns the data in the sections titled
... | d9d7fca23476a303a3fa3915cd083a8c03b7129c | 3,626,481 |
def next_not_tail(*args):
"""next_not_tail(ea_t ea) -> ea_t"""
return _idaapi.next_not_tail(*args) | d69cc61137e96c627143217611aaaabfd293a772 | 3,626,482 |
def AddInterestedUserAndUrl(existing_url_key, bots_user_key):
"""Updates user models's interested_url and url model's interested_user field.
This method updates url and bots_user model in trasaction to maintain the
atomicity.
Args:
existing_url_key: Key of the url entity to update (db.Key).
bots_user_... | c2652a3cd18745b65e725df69056a33124dbb217 | 3,626,483 |
def sql_to_python_type(sql_type: str) -> type:
"""Turn an SQL type into a dataframe dtype"""
if sql_type.startswith("CHAR(") or sql_type.startswith("VARCHAR("):
return pd.StringDtype()
elif sql_type.startswith("INTERVAL"):
return np.dtype("<m8[ns]")
elif sql_type.startswith("TIMESTAMP(")... | fa668314e0a7022f8e46ead8d099cae210c7b73b | 3,626,484 |
def scrape_to_list_value(scraped_rows, i, list_name):
"""insert row of rows of scraped data
input i for skipping rows
return value in dollars"""
to_scrape = scraped_rows[i::7]
list_name = []
for i in range(len(to_scrape)):
num = float(to_scrape[i][0].replace(',', '.'))
num_dollar... | 62117d0d78a4fd691baa4163a19962c2fb1443d3 | 3,626,485 |
def _marathon(config_schema, info):
"""
:param config_schema: Whether to output the config schema
:type config_schema: boolean
:param info: Whether to output a description of this subcommand
:type info: boolean
:returns: process return code
:rtype: int
"""
if config_schema:
... | f05b48c0ac6db196265f7c8840d9cee33c2769ff | 3,626,486 |
def process_owner_me_query():
"""Return features that the current user owns."""
user = users.get_current_user()
if not user:
return []
features = models.Feature.get_all(filterby=('owner', user.email()))
feature_ids = [f['id'] for f in features]
return feature_ids | e8cb698247c5eb986416013a2ad791612a4ff95a | 3,626,487 |
def velocity_traj(arr, dt=1.0, axis=0, endpoints=True):
"""Calculate velocity from `arr` (usually coordinates) along time`axis`
using timestep `dt`.
Central differences are used (example x-coord of atom 0:
``x=coords[:,0,0]``)::
v[i] = [ x[i+1] - x[i-1] ] / (2*dt)
which returns nstep-2 po... | 62e0de52a24e3dfc081ed5b5ed7be67b1026b409 | 3,626,488 |
import os
def getPerturbationMeasures(
fName,
tmpDataPath = None,
keepAnalysisFile = False
):
"""
performes perturbation measures using Praat's default settings
@param fName the name of the WAV file that should be analyzed
@param tmpDataPath the path for temporary files. if None, see @ref runPraatScript
... | dabab0b41b140daa91c9060601db207d85cc2699 | 3,626,489 |
def litho_ruler(
height = 2 ,
width = 0.5,
spacing = 1.2,
scale = [3,1,1,1,1,2,1,1,1,1],
num_marks = 21,
layer = 0,
):
""" Creates a ruler structure for lithographic measurement with marks of
varying scales to allow for easy reading by eye.
Parameters
----------
height :... | 177381fdd11b322817c1353b40ff3e3edac29bc6 | 3,626,490 |
import functools
def create_recurrent_model(vocab_size = 10000,
num_oov_buckets = 1,
embedding_size = 96,
latent_size = 670,
num_layers = 1,
name = 'rnn',
s... | dfbd4b7fe08d3a9114a82801495efe807191683e | 3,626,491 |
def get_template(template_name):
""" Returns a lxml Element containing the new terminal layout.
"""
template_path = path_template(template_name)
new_division = ET.parse(template_path)
return new_division.find("div") | 0374a9b00a40d76f8d57ac35969516c58e81fa0e | 3,626,492 |
def get_nodes_from_vpc_id(vpc_id):
""" calculate node-ids from vpc_id. If not a vpc_id, then single node
returned
"""
try: vpc_id = int(vpc_id)
except ValueError as e: return ["%s" % vpc_id ]
if vpc_id > 0xffff:
n1 = (0xffff0000 & vpc_id) >> 16
n2 = (0x0000ffff & vpc_id)
... | 5c3a6506a721f9d518579df39a91ec38118d5e75 | 3,626,493 |
from io import StringIO
def format_config_vals(config_vals):
"""Format an iterable of config values from a config object."""
text_buffer = StringIO()
for i, k, v in config_vals:
val = "" if v is None else str(v)
text_buffer.write(
(" " * i)
+ colorize(pad_line(st... | 1a7cd1b0f1a085c510c860ff097be010aea68997 | 3,626,494 |
from typing import List
def extract_imports(node: Module) -> List[ParsedImport]:
"""Extract parsed imports from module."""
node_imports = []
for node_import in node.iter_imports():
from_module = ''
import_data = []
for part in filter_nodes(node_import, [Name, Keyword, Operator]):
... | 6bae0fc8d136758de684be0f9be543758c87e94d | 3,626,495 |
def optimize_k_knn(X_train, y_train, X_test, y_test, min_k=3, max_k=10, score='micro'):
"""
Find best k neighbor number for KNN model based on scores on testing data
Score is based on f1_score, for options refer to sklearn.metrics
"""
k_f1 = []
for k in range(min_k, max_k+1):
knn = ... | 0b234439f5fdee345a50a60e6835f4b62d500de0 | 3,626,496 |
from click.testing import CliRunner
def run_cmd(*args):
"""Run the provided arguments
"""
runner = CliRunner()
return runner.invoke(main, args) | 3c0d665cebb66ac8715edee838d1feb86fb445db | 3,626,497 |
def condor_r_step(wkspace, sys=None, job_name="rank", dag=None):
"""Generate a condor job for running the ranking steps.
Parameters
----------
wkspace : pathlib.Path
Path of the config file.
sys : list(str), optional
Specific ystematics to use.
job_name : str
Name for th... | 1d0531d7a02433a9e354e736cebd7f2f7b05fd6a | 3,626,498 |
from datetime import datetime
def utc2local(utc_time):
"""
UTC time to local time.
UTC time format: 2020-02-02T02:02:02.202002Z, formatting UTC timestamp according to "%Y-%m-%dT%H:%M:%S.%fZ".
:param utc_time: UTC time
:return: local time
"""
local_format = "%Y-%m-%d %H:%M:%S"
# The for... | a2661758eb6176e7d7e4a0b6d5338b0f2c531757 | 3,626,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.