content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _should_package_clang_runtime(ctx):
"""Returns whether the Clang runtime should be bundled."""
# List of crosstool sanitizer features that require packaging some clang
# runtime libraries.
features_requiring_clang_runtime = {
"asan": True,
"tsan": True,
"ubsan": True,
}
... | 7f54b903f4acc288abca294d857e774ce3daa8b3 | 3,609,866 |
import math
def round_nearest_towards_infinity(x, infinity=1e+20):
""" Rounds the argument to the nearest integer.
For ties like 1.5 the ceiling integer is returned.
This is called "round towards infinity"
Args:
x: the value to round
infinity: the model's infinity value. All values a... | e3edd7dfca255648f02eb9845f411f52c24d3120 | 3,609,867 |
def json_schema(request, ref: str):
"""Return a JSON Schema for a given reference."""
if ref not in SCHEMA_REFS:
return HttpResponseBadRequest("Unknown ref")
return SCHEMA_REFS[ref].schema_json(indent=2) | 2530d31ed2aab344f5a4fc7d1208b3f9f91cfdca | 3,609,868 |
def emprestimo(id):
"""
Deleta uma reserva e gera um empréstimo.
Certifica que a reserva existe.
Atualiza o status do livro para emprestado
"""
reserva = get_reserva(id)
try:
livro = db.query_one('select * from livro where tombo = %s' % reserva['tombo'])
print(livro)
... | 0dba34551b4c6d0e2f85319abf85ad0ed83efc27 | 3,609,869 |
def intersection(line1, line2):
"""Finds the intersection of two lines given in Hesse normal form.
Returns closest integer pixel locations.
See https://stackoverflow.com/a/383527/5087436
"""
rho1, theta1 = line1[0]
rho2, theta2 = line2[0]
A = np.array([
[np.cos(theta1), np.sin(theta... | be158fbffdcbcd35134af7fbab83106ad9b2a94b | 3,609,871 |
from typing import Any
from typing import Dict
def make_kwargs(proxy_info: ProxyInfo, *, nosave: bool = False,
**kwargs: Any) -> Dict[str, Any]:
"""Form the proxy kwargs for requests or urllib
:param proxy_info: ProxyInfo
a namedtuple of the form
(server: str, port: int, d... | 9be26e1b9382eb616f999b8a2553cbdf88c17029 | 3,609,872 |
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
... | abce08b0fdbb3157509281a615572c3a2526d484 | 3,609,873 |
import re
import copy
def model_to_estimator(model):
"""given a model , return a estimator"""
tf=model.copy()
tp=type(tf)
from1=re.search(r'(pyspark.*)\.',str(tp)).group(1)
from2=re.search(r'(pyspark.*)\.(\w+)',str(tp)).group(2)
from2=re.sub(pattern='DecisionTreeRegressionModel', repl='Decisio... | ccb414b8ae8745c31eaa6060e36eb064e8778923 | 3,609,874 |
def regex_chomp(regex, state, tracker):
"""
:param regex: regex object to match with
:param state: ChompState
:param tracker: FroParseErrorTracker
:return: Match object of regex match, or throws ChompError
"""
line = state._curr # state.current()
index = state._column # state.column()
... | d39963a632bd99afe1b9d50f60ebb3203b6b5d21 | 3,609,876 |
def create_html_popup(friends: list) -> str:
"""creates html popup for markrer
Args:
friends (list): list of names
Returns:
str: html in string format
"""
html_template = "Friends:"
for friend in friends:
html_template += f"""<br>
<p>{friend}</p><br>
"""... | 54b1ac02cf59a086a711dcb0b47f14c0ea4e782d | 3,609,877 |
from typing import List
from datetime import datetime
from typing import Union
from pathlib import Path
from typing import Tuple
def collect_radolan_data(
date_times: List[datetime],
time_resolution: TimeResolution,
prefer_local: bool = False,
write_file: bool = False,
folder: Union[str, Path] = D... | 77395e1fea8fd2b6f089e9a9bbba10f0faf91661 | 3,609,878 |
def SetFlags(ea, flags):
"""
Set new value of flags
This function should not used be used directly if possible.
It changes properties of a program byte and if misused, may lead to
very-very strange results.
@param ea: adress
@param flags: new flags value
"""
return idaapi.setFlags(e... | 7ca8b70c1cf0eb1e5236c613cafdae38c7ff2f1d | 3,609,879 |
def createMiddleWare(app, exporter):
"""
Configure a flask middleware that listens for each request and applies automatic tracing.
This needs to be set up before the application starts.
:param app: WSGI application
:param exporter: Exporter instance object (StackdriverExporter)
:return:
"""
... | 62e7eb512ebf86f761f9f35df2a47b94418f658f | 3,609,881 |
def euler_step(theta,dtheta,ddtheta,dt):
"""
Euler Step
Parameters
----------
theta (tf.Tensor):
Joint angles
(N,nq)
dtheta (tf.Tensor):
Joint velocities
(N,nq)
ddtheta (tf.Tensor):
Joint accelerations
(N,nq)
dt (float):
Delta t
... | 402b30a3f24440707ef56b7113b545eb827c704e | 3,609,883 |
def get_cif(ams_id):
"""
get CIF Structure by AMS ID
"""
db = get_amscifdb()
return db.get_cif(ams_id) | 3003f360a3a24574b1d672032d71b376b8df1baf | 3,609,884 |
def no_xray_disturbance(nodist,hole):
"""
takes an archive measurement DataFrame and removes disturbed intervals using XRAY disturbance files
Parameters
__________
nodist : Pandas DataFrame
data frame filtered by iodp_funcs.remove_disturbance
hole : str
IODP hole
Return... | f2023b06b7a7014d0259a8f08625346bcac1cf52 | 3,609,886 |
def beta1() -> float:
"""Mock beta1."""
return 0.9 | 1152a45a891c749b196cab780f8f76afc70c2a65 | 3,609,888 |
def dhcp_relay_show(dut, family="ipv4", interface=None, cli_type=""):
"""
API to show the DHCP relay brief output
Author Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
cli_type = st.get_ui_type(dut, cli_type=cli_type)
if cli_type in ['click', 'klish']:
... | 9cd1d95b61687fc53a5e93d06bc4e5d8affa8435 | 3,609,889 |
def split_condition_code(tree, fields, field, depth,
pre_condition, term_analysis_fields,
item_analysis_fields, cmv):
"""Condition code for the split
"""
predicate = get_predicate(tree)
optype = fields[field]['optype']
operator = PYTHON_OPERATOR[pre... | 88fbf23740e71819e4b0a455637f10b6aa9be26c | 3,609,890 |
from typing import List
def get_cases_country(path: str) -> List[int]:
"""
Counts the number of cases based on the COUNTRIES for the parameter of interest.
Arguments:
path {str} -- path to the dataset csv file for the parameter of interest
Returns:
List[int] -- an ordered list of the number of cases for e... | 2018db97c6ca932b1fe28fcbeb73c8ce04afe716 | 3,609,891 |
def tf_optimize(inputs, outputs, graph_def, fold_constant=None):
"""Optimize tensorflow graph for inference."""
transforms = []
if fold_constant:
transforms.extend([
"fold_constants(ignore_errors=true)",
"remove_attribute(attribute_name=_class)", # remove node colocation att... | bedd14414cce8f6364869b18e831274ab2001d70 | 3,609,892 |
def parse_mask(line):
""" parses the string formated as the PASCAL pixel mask annotation
e.g. Pixel mask for object 1 "PASpersonWalking" :
"PennFudanPed/PedMasks/FudanPed00001_mask.png"
line: string
line in the PASCAL annotation file with mask information
returns: ... | 1db8aa18fa85f3b7a952ba24247ecfa10e1c9245 | 3,609,893 |
def delete_node_layout(node_id):
"""
API entry point to delete the layout for a node.
"""
return node_layout.delete_node_layout(node_id) | 326ebb3fa1a6d0ce75ed2f791a54ff10318f3014 | 3,609,896 |
from typing import Dict
from typing import Tuple
import functools
def _create_nodes_map(
graph_dict: Dict[str, Dict[str, PCollection]]
) -> PCollection[Tuple[NodeId, Node]]:
"""Create a map from Node ID to Node from the given `graph_dict`.
Args:
graph_dict: The map returned from a `unigraph` graph readin... | 05a2d4950325be8d9d8b4d0def7cbb698644b01f | 3,609,897 |
def generatePosSeqList(length):
""" Generates HALF of the possible weaves of a given length or less """
posSeqList = [] # list that will contain the generated weaves
curSeq = [0]*int(length//2) # We devide by 2 as the sigmas have pair powers
endSeq = [4]*int(length//2)
while curSeq != endSeq:
... | 74b3ed4ce5f08ff30ba8f665d1655b8269c3c280 | 3,609,898 |
def prepare_script_args(spec):
"""
Uses the default script args if those items are not specified for
the script.
Args:
spec (dict): Script args to modify with defaults as needed.
Returns:
dict: Modified dictionary with values as needed.
"""
spec['run_in'] = spec.pop... | c2f206d5dba6e4b5727dd7d2f5f1732a582b54b2 | 3,609,899 |
def fetch_MEN(which="all", form="natural"):
"""
Fetch MEN dataset for testing similarity and relatedness
Parameters
----------
which : "all", "test" or "dev"
form : "lem" or "natural"
Returns
-------
data : sklearn.datasets.base.Bunch
dictionary-like object. Keys of interes... | 5452ce4451c2da17d6b3bdf01934dd8e3661da4d | 3,609,900 |
from datetime import datetime
def custom_payload(claims, expiration):
"""
Creates JWT payload.
Author:
Lucas Antognoni
Arguments:
claims (list): Token payload claims.
expiration (datetime.timedelta): Timedelta.
Response:
pay... | 319f89598e1623a746ae4229a262aad0f3b4da65 | 3,609,901 |
import base64
def b64s_to_s(b64s: str) -> str:
"""convert base 64 strting to string
:param b64s: input base 64 string
:type b64s: str
:return: output string
:rtype: str
"""
s = base64.b64decode(b64s.encode('utf8')).decode('utf8')
return s | beb49deb87d45da43cc8f12b3aacec37d7bfd1ed | 3,609,902 |
from typing import Optional
from typing import Tuple
from typing import List
from typing import Dict
def solve_tsp_dynamic_programming(
distance_matrix: np.ndarray,
maxsize: Optional[int] = None,
) -> Tuple[List, float]:
"""
Solve TSP to optimality with dynamic programming.
Parameters
-------... | ec9a12315b6e1cfd1fd144617005ea9ac3169293 | 3,609,903 |
from typing import Counter
def counter(data, n=None):
"""counter方法用于统计元素数量
Parameters
----------
data : list
列表数据
n : int
前n个元素
Returns
----------
"""
ret = Counter(data)
if not n:
ret = ret.most_common(len(ret))
else:
ret = ret.most_common(... | 6fed62dd1478992c13c8dee5dd2cbb7556a5d0fe | 3,609,905 |
def col255_from_RGB(red,green,blue):
""" returns a term256 colour index from RGB value
found at :
https://unix.stackexchange.com/questions/269077/
"""
if red > 255:
red = 255
if green > 255:
green = 255
if blue > 255:
blue = 255
if red < 75:
red = 0... | 6d896f557d5903708f5072d1a875313633cea6b4 | 3,609,906 |
def first_or_default(iterable, predicate=None, default=None):
"""First the first value matching a perdicate otherwise a default value.
:param iterable: The items over which to iterate.
:param predicate: A predicate to apply to each item.
:param default: The value to return if no item matches.
:retu... | 94ee1c97cc752b1f5bb0ac4cc7c3a6a8f3fe4675 | 3,609,907 |
import copy
import itertools
def bin_bp_sparse(M, positions, bin_len=10000):
"""
Perform binning with a fixed genomic length in
base pairs on a sparse matrix. Fragments will be binned such
that their total length is closest to the specified input.
If a contig list is specified, binning will be per... | 1f69207692944dffd0dddab00cc2860a72416590 | 3,609,908 |
def image_md(image_location, caption="", link=None, tooltip=""):
"""
Returns the html code for the individual plot
"""
image = f"""
<a href="{link}" name="gallery-href">
<img src="{image_location}" name="gallery-image" alt="{tooltip}"
style="width:100%" id="{"".join(image_location.split("-... | 3e847459f14d8cfd2c66bed633640bbbb0442321 | 3,609,910 |
import msgpack
def unpacker(*args, **kwargs):
"""Return a MessagePack (with extended types support) Unpacker object."""
return msgpack.Unpacker(*args, ext_hook=_decode_ext_type, raw=False, **kwargs) | ac216bb6a45546a8a4ae620d1dad4345f08b72e3 | 3,609,911 |
def water_budget(ds, dim='p'):
"""Compute water budget if Q2NN is present"""
q2_int = (ds.Q2NN * ds.layer_mass).sum(dim) * 86400
q2_ib = q2_int
prec = ds.Prec
evap = lhf_to_evap(ds.LHF)
return xr.Dataset(
dict(Prec=prec, evap=evap, Q2=q2_ib, imbalance=q2_ib - (evap - prec))) | 12f96fe74a1cc37c41d4186e991815566b8d826a | 3,609,913 |
def get_split_discordants(data, work_dir):
"""Retrieve full, split and discordant reads, potentially calculating with samblaster as needed.
"""
dedup_bam, sr_bam, disc_bam = _find_existing_inputs(data["align_bam"])
if not dedup_bam:
dedup_bam, sr_bam, disc_bam = _extract_split_and_discordants(da... | d601fb8ffd41de8247c77ac3b8256810c9276c34 | 3,609,915 |
def fuzzy_or(args):
"""
Or in fuzzy logic. Returns True (any True), False (all False), or None
See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is
related to the two by the standard De Morgan's law.
>>> from sympy.core.logic import fuzzy_or
>>> fuzzy_or([True, False])
... | 4dac12016b95d3713590bd547aeb2d182de7f02e | 3,609,916 |
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete(uuid, cost_name): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete
removes tapi.topology.CostCharacteristic #... | fbfe8be9fcc7f3f96fc502b2d279bef6db292abb | 3,609,917 |
def save_integrator(key_name):
"""
save the integrator if its explicit
Parameters
---------
key_name
"""
RK=loadRKM(key_name)
if(RK.is_explicit()):
print("Saving "+RK.name+" to file "+str(key_name)+".npz" + " and file "+str(key_name)+".mat")
# an integrator tablaeu ex... | e43f7ae42e1f3cdf4c0211cb1dac3deed04bccb9 | 3,609,918 |
def get_variables_path(export_dir):
"""Return the variables path, used as the prefix for checkpoint files."""
return file_io.join(
compat.as_text(get_variables_dir(export_dir)),
compat.as_text(constants.VARIABLES_FILENAME)) | fb3248a99a8a48522c60aa24ac0a58ed1fd4de93 | 3,609,919 |
def parse_single_geo_arg(key: str) -> GeoPair:
"""
parses a single geo pair with only one value
"""
r = _parse_single_arg(key)
return GeoPair(r[0], [r[1]]) | fbf9d7a0589881af1cd5a3303fc4ecdf6f5d90a2 | 3,609,920 |
from bs4 import BeautifulSoup
import re
def check_currency(response: str) -> dict:
"""Check whether the results have currency conversion
Args:
response: Search query Result
Returns:
dict: Consists of currency names and values
"""
soup = BeautifulSoup(response, 'html.parser')
... | 679b656e6565fcbdc3011ec9164e57baa6d650f4 | 3,609,921 |
from datetime import datetime
import math
def calculate_mean_anniversary(days_of_interest: list):
"""The function calculate_mean_anniversary calculates the mean anniversary based on a geometric approach.
The mean anniversary is valid for the current year. The list of dates are given as string in the format yy... | 431dde8178bed5efb7a5c3967451c7d7fdaa62c2 | 3,609,922 |
def fix_models_py(models_py):
"""
The output of inspectdb is pretty messy, so here we trim down
some of the mess, add mandatory ID field and fix the bad
conversion to CharField (we use TextField instead).
"""
lines = models_py.split("\n")
fixed_lines = []
for line in lines:
# Pos... | 428cce3315a2e47d44e35889e0cccd7d840794aa | 3,609,923 |
def _can_extract_intrinsics_to_top_level_lambda(comp, uri):
"""Tests if the intrinsic for the given `uri` can be extracted.
Args:
comp: The `tff.framework.Lambda` to test. The names of lambda parameters and
block variables in `comp` must be unique.
uri: A Python `list` of URI of intrinsics.
Return... | 99c7f5bb15e11127cc2cbcc82e658722bcc1a9cf | 3,609,924 |
def primitiveValueFrom(interp, s_frame, w_cls, w_obj):
"""
Creates a value of a given Smalltalk object by copying.
:param interp: The interpreter proxy.
:param s_frame: The stack frame.
:param w_cls: The imutable objects target class.
:param w_obj: The Smalltalk object to produce an immutable c... | 6d2cdb407b833d540b55d4b45725eb46116b43c1 | 3,609,925 |
def entertainment():
"""
show entertainment posts
"""
entertainment = Post.query.filter_by(category="Entertainment").all()
return render_template('entertainment.html', post=entertainment) | 4759986bfa0f1522983454f4cec4069b7424de8c | 3,609,926 |
def allsum(my_a, axis=None, dtype=None, out=None, comm=MPI.COMM_WORLD):
""" Parallel (collective) version of numpy.sum
"""
my_sum = np.sum(my_a, axis, dtype)
if my_sum is np.ndarray:
sum = np.empty_like(my_sum)
comm.Allreduce( (my_sum, typemap[my_sum.dtype]), (sum, typemap[sum.dtype]))
... | 25da66cf2e9c12f2b2c589811625333b3bf8e9be | 3,609,928 |
def sum_of_years_digits(year):
"""Calculate the sum of years' digits.
Arguments:
year (``int``): The year to calculate up to.
Returns:
int: The sum of years' digits.
"""
if year <= 0:
return 0
return year + sum_of_years_digits(year-1) | aa3d67cde4af6c8565ef6fdcd8becb0cb3b1fa95 | 3,609,929 |
def codes_code_id_codes_get(code_id, sab=None): # noqa: E501
"""Returns a list of {Concept, Code, Sab} associated with the code_id optionally restricted to SAB
# noqa: E501
:param code_id: The code identifier
:type code_id: str
:param sab: One or more SABs to search
:type sab: List[str]
... | eec7fb87f6050783651b62ce4552c11c99550af4 | 3,609,931 |
def plot_data_with_anomalies(data, anomalies, as_var=False):
""" Plot the data and add anomalies as line on the graph
:argument data: dataframe (same as above)
:argument anomalies: DatetimeIndex of dates (corresponding to anomalies) - dtype=datetime64[ns]
"""
fig, ax = plt.subplots(1, 1, figsize=(2... | 014732f883f25460b692bd03d6ee3dcf7ef4f51e | 3,609,933 |
def density_supercooled_water(T):
"""D. E. Hare and C. M. Sorensen: Density of supercooled water 1987 JChemPhys
valid between -33.4 to -5/+10
Args:
T: in [K]
"""
a = [0.99986, 6.690e-5, -8.486e-6, 1.518e-7, -6.9484e-9, -3.6449e-10, -7.497e-12]
t = T-T0
rho = a[0] + a[1]... | 9a368a5905a298595e7b0d5ecd60486ee1a07c7b | 3,609,934 |
def repel_from_near(lerp_point, drone_num, course, radius=1.0):
"""
Отталкиваемся от дронов если они возши в заданный радиус
:param name:
:param list:
:return:
"""
repel = [0.0, 0.0, 0.0]
for i in range(len(drone_offset_list)):
if drone_offset_list[i][0] != drone_offset_list[dro... | ef2162d5b0612aa0feacbe0b1aae9a4c333fbdb8 | 3,609,935 |
def get_values():
"""
Retrieves two values to multiply
"""
user_values = input("On the next line, enter the values to multiply,\
separated by commas. \n>> ")
input_list = user_values.split(",")
final_list = []
#We've split the user's input into a list, but have no idea if it's any good.
... | ea0fb353d61514e67970d673bbe9fb45a9b20123 | 3,609,936 |
def merge_close_peaks(peaks, minimum_distance):
"""Merge peaks that are too close to each-other vertically.
Peaks that fall within the dilation mask are spurious and likely not peaks we want. When two peaks fall below the
minimum distance, the smallest one will be discarded.
Parameters:
----------... | 3b97f8b652550348f944ffd7451a77d4c8dec4f3 | 3,609,938 |
def LruCache(maxsize=None):
"""LRU Cache decorator.
Args:
maxsize: the maximum cache size, or None for unlimited size.
"""
def wrapper(fn):
return functools32.lru_cache(maxsize=maxsize)(fn)
return wrapper | f1182f575a9145ddbf95b29ff3d746ccbe88adc4 | 3,609,939 |
def parse_inputs():
""" Parser function to take care of the inputs """
parser = ArgumentParser(description='Argument: python data_preprocess.py <data_direction> <output_annotation_path> <test_ratio>')
parser.add_argument('data_dir', type=str,
help='Enter path to data direction.')
... | fb7d67a358eef6703dc0c5c4c12514c1c78a6371 | 3,609,941 |
from typing import List
def concretise_config(
config: StrConfig, available_domains: List[Domain]
) -> ObjConfig:
"""Dereference configuration."""
domain = find_by_repr(available_domains, config.domain)
categories = list(gather_categories(domain.tools).keys())
loaders = [find_by_repr(domain.tools ... | 1504e4eb650af10eb220315517e909508583859a | 3,609,942 |
def nextDay(year, month, day):
"""计算指定日期的下一天(假设给定的日期合法)"""
if day < daysInMonth(year, month):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1 | 7e7c46a88529777694555e71b3d116bd3f46b944 | 3,609,943 |
def load_david_worksheet(fname='fMRI MA significance bias database 03-24-13.xlsx',
verbose=False):
"""load the David et al. data from excel workbook
and return ID and sample size"""
workbook = xlrd.open_workbook(fname)
sheet=workbook.sheet_by_name('Original Sheet')
studies={}
all_ids=[]
... | 19de3c07084450709b3a764c9c8b29f6d3353313 | 3,609,945 |
import mmap
def file_lines(dictionary_file):
"""
Counts the number of lines of the given file.
Parameters
-------
dictionary_file: file
The text file
Returns
-------
int
The number of lines of the given file
"""
buf = mmap(dictionary_file.fileno(), 0)
line... | f74de1cddb1e8c022dac06e70ac6df4d3e597cb1 | 3,609,946 |
def is_holiday(date):
"""
check if one date is holiday in China.
in other words, Chinese people get rest at that day.
:type date: datetime.date | datetime.datetime
:rtype: bool
"""
return not is_workday(date) | d7b4ee9b48216e8d07674eb699f05a3f7fd76029 | 3,609,947 |
def read_dataset_and_unit_h5(h5, expected_unit=None, convert=True):
"""
Reads a dataset that has openPMD unit attributes.
expected_unit can be a pmd_unit object, or a known unit str. Examples: 'kg', 'J', 'eV'
If expected_unit is given, will check that the units are compatible.
If conv... | 4f7d562db53c5a793a8c1a3569789596425a515a | 3,609,948 |
def make_sparse_convmodule(in_channels,
out_channels,
kernel_size,
indice_key,
stride=1,
padding=0,
conv_type='SubMConv3d',
norm_cf... | 29c797f6be6d2830cb9a309b4a105d3fa4ad04c2 | 3,609,949 |
def get_zcoeffs(csv, imfreq):
"""
Given the input frequency of the image, returns the Pandas dataframe with
the coefficients corresponding to the input frequency. The frequencies in
the input CSV file are expected to be in MHz.
Inputs:
csv Input CSV filename, string
imfreq Imag... | d7f60cfdd4249e98e1991b98f5f508e1aa409c60 | 3,609,950 |
import signal
def test_func(s, sr, maximum_duration=30, minimum_duration=None,
frame_length=256, nb_mixtures=3, threshold=0.3,
return_vad=False, return_voices=False, return_cut=False):
""" Splitting an audio based on VAD indicator.
* The audio is segmented into multiple with length... | 3fdd345aa7f465b9501c2cd7e04464d48d0a0cde | 3,609,951 |
import torch
from typing import Union
def _find_layer(model: torch.nn.Module,
target_layer: Union[str, torch.nn.Module]) -> torch.nn.Module:
"""Find the specified layer in a model.
Args:
model: a neural network model as a PyTorch Module.
target_layer: the target layer in the m... | 0d102625102333eb4bd617f14753f1eb46ef6c9d | 3,609,952 |
from typing import Optional
def article(topic: str, article_date: str, title_slug: str) -> tuple:
"""
**article**
:param topic:
:param article_date:
:param title_slug
:return:
"""
link_slug: str = f'{topic}/{article_date}/{title_slug}'
article_data: Optional[dict] = Articles.... | 911f7be750560263671c3636e70cc1eeb3fc58b7 | 3,609,953 |
def parse_simple_expression_list(l):
"""
This parses a comma-separated list of simple_expressions, and
returns a list of strings. It requires at least one
simple_expression be present.
"""
rv = [ l.require(l.simple_expression) ]
while True:
if not l.match(','):
break
... | 8c3772e1bd4cc9587c8095dcba640878c01fc0f4 | 3,609,954 |
def collect_ibkr_listings(exchanges=None, sec_types=None, currencies=None,
symbols=None, universes=None, sids=None):
"""
Collect securities listings from Interactive Brokers and store in
securities master database.
Specify an exchange (optionally filtering by security type, cu... | 2bf05d1e15de4b64fcdaf0270afacab906527841 | 3,609,955 |
def largest_indices(x, K):
"""Returns the indices of K largest entries in x by magnitude
Args:
x (jax.numpy.ndarray): An data vector/point
K (int): The number of largest entries to be identified in x
Returns:
(jax.numpy.ndarray): An index vector of size K identifying the K largest ... | 1ff43b2142abf97946a080fd292d340b37aa8150 | 3,609,956 |
from typing import Iterable
from typing import Any
from typing import List
import itertools
def flatten(val: Iterable[Iterable[Any]]) -> List[Any]:
"""
Flatens a list of list into a list
>>> flatten( [['abc','def'],[12,34,46],[3.14, 2.22]])
['abc', 'def', 12, 34, 46, 3.14, 2.22]
"""
return li... | cd9ae9e393569ba7800735d09c8621f0d64beed3 | 3,609,957 |
def surprisal_graph(transition_matrix, states=None, symmetrized=True, stationary_distribution=None):
"""Return the surprisal graph of a discrete-time Markov chain.
Parameters
----------
transition_matrix : (N, N) array_like
Transition matrix of a discrete-time Markov chain. Must be
a s... | 215529a140e80f080cf8a9e69c56826ebb0803fa | 3,609,958 |
def get_output_list(file_row):
"""Return list of dict for output file"""
data = []
list_mammo = get_row_nr(file_row, 'mammo_params')
list_us = get_row_nr(file_row, 'us_params')
list_mri = get_row_nr(file_row, 'mri_params')
all_params = list_mammo + list_us + list_mri
for x in range(len(all_p... | c431f6660c65f6ab54bbc4cdf9c50a6d7b93d062 | 3,609,959 |
import io
import csv
def to_csv(members):
"""Convert JSON data structure to CSV string."""
with io.StringIO() as fp:
cw = csv.writer(fp)
if len(members):
cw.writerow(members[0].keys())
for member in members:
cw.writerow(member.values())
value = fp.getval... | 0ed85a10417dee1ca98a28e05e1ae2d24dcebfe0 | 3,609,960 |
import math
def plot_location(latitude, longitude, bearing, distance):
"""Plot a new location based on starting point, bearing and distance"""
bearing_rad = math.radians(bearing)
lat1 = math.radians(latitude)
lon1 = math.radians(longitude)
d_over_r = distance / EARTH_RADIUS
lat2 = math.asin... | 64e4bd1d1102e4df77ad60c473eee6558f942896 | 3,609,961 |
def num_sources():
"""Get the number of sources."""
return len({s for s in SourceName}) | 5539a871717dda34e4cb08f62d07e592d3f2c2f4 | 3,609,963 |
def _get_panelargs(
side, share=None, width=None, space=None,
filled=False, figure=False
):
"""
Return default properties for new axes and figure panels.
"""
if side not in ('left', 'right', 'bottom', 'top'):
raise ValueError(f'Invalid panel location {side!r}.')
space = space_user = ... | 0273f7e439e02ed1c8afd98d011395d30bca34f3 | 3,609,964 |
def relu(x):
""" REctified Linear Unit: y = x if x >= 0; y = 0 if x < 0;
:param owl.NArray x: input
:return: result ndarray
:rtype: owl.NArray
"""
return _owl.NArray.relu(x) | 81459cb70817ce9d658823bbd68165dbc55fe6ad | 3,609,965 |
def find_max_treatment_effect_phenotype(g, zeta_probs, factual_outcomes):
"""
Find the group with the maximum treatement effect phenotype
"""
mean_differential_survival = np.zeros(zeta_probs.shape[1]) # Area under treatment phenotype group
outcomes_train, interventions_train = factual_outcomes
... | 0e6c014002d717355f4c9c1da020a2f8312142fc | 3,609,966 |
def make_random_image(filename=None,
dims=(10, 10, 10),
xform=None,
imgtype=1,
pixdims=None,
dtype=np.float32):
"""Convenience function which makes an image containing random data.
Saves and returns the... | d66b757c90e9f26f0d3ca6248ca28e578cb80f4c | 3,609,967 |
from typing import Any
import re
def _check_lat_or_long(val: Any, clean: bool, hor_dir: str) -> Any:
"""
Function to check if a coordinate instance is valid
"""
# pylint: disable=too-many-boolean-expressions
if val in NULL_VALUES:
return (None,) * 4 + (0,) if clean else False
pat = LA... | e34a44b562c25ec9dca06136966b24ba30de0321 | 3,609,969 |
def integrate(avg_daily_sentiment, interval):
"""
Takes a list of average daily sentiment scores and returns a list of definite integral estimations calculated
with Simpson's method. Each integral interval is determined by the `interval` variable. Shows accumulated sentiment.
"""
# Split into sliding window list ... | 37c36c7a23e7af83cb43789d6401bad01c7ae89c | 3,609,970 |
def split_sentences(inp_text, nlp_model):
"""
Splits an input string into sentence determined by spacy model
:param inp_text: string with input text
:param nlp_model: sciSpacy model
:return: list of sentences in string format
"""
doc = nlp_model(inp_text)
sentences_list = [sentence.text ... | b5617d9334509edf09bf4a0360d3030e67ddf800 | 3,609,971 |
def _get_rotation_indices_gl(self, linkages):
"""
Precompute indices that are then used to rotate along the i-j axis only the
proper portion of the coordinates array. Works only for glycans.
Returns
rotation_indices : dict of dict of tuples
dictionary of residue numbers, dicctiona... | 490bcae9dbc8ed74469a7c2aa68566c76e6fdd7c | 3,609,972 |
def _point(x,index=0):
"""Convert tuple to a dxf point"""
return '\n'.join([' %s\n%s'%((i+1)*10+index,float(x[i])) for i in range(len(x))]) | b5d2b3345b53bf2bd5e7fb93ee57fa9eb2a599b9 | 3,609,975 |
import socket
def myip() -> str:
"""returns a string with the computers default IP address
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip | c30a433cc49c4d58a209ded2d00578a11667372c | 3,609,976 |
def not_empty(message=None) -> Filter_T:
"""
验证输入不为空。
返回:
nonebot.typing.Filter_T:
"""
def validate(value):
if value is None:
_raise_failure(message)
if hasattr(value, '__len__') and value.__len__() == 0:
_raise_failure(message)
return va... | 26b09dc50fd9f5eb5bc5ecde424cdfcda78b34d6 | 3,609,978 |
def get_video_dimensions(lines):
"""Has it's own function to be easier to test."""
def get_width_height(video_type, line):
dim_col = line.split(", ")[3]
if video_type != "h264":
dim_col = dim_col.split(" ")[0]
return map(int, dim_col.split("x"))
width, height = None, No... | 7df1dbc3e190908852684735bc1242db4e3c456b | 3,609,979 |
def factorial(x):
"""
The factorial_ (denoted :math:`n!`) is the product of all positive
integers less than or equal to a positive integer (:math:`n`).
.. _factorial: https://en.wikipedia.org/wiki/Factorial
Equation:
.. math::
n! = \\prod_{k=1}^n k
Args:
x: A numer... | dc9a064d957dbd90b6fc05008eff8166306b271a | 3,609,980 |
def __get_database_filepath(config: ChiaTeaConfig) -> str:
"""Get the database filepath from the config
Parameters
---------
config : ChiaTeaConfig
config to read filepath for cert and key
Returns
-------
db_filepath : str
path where the database is or will be stored
""... | 74648a989c7783aca82bd1d74a6b3ad29e23a983 | 3,609,981 |
import torch
from typing import Iterable
def brownian_bridge(n_step, sample_shape=()) -> torch.Tensor:
"""
:param n_step: first and last steps are 0 and 1
:param sample_shape:
:return: b[step, sample_shape]
"""
assert n_step >= 2
if not isinstance(sample_shape, Iterable):
sample_s... | e71c8e011fe0fc352b053aee39d74b5572740291 | 3,609,982 |
def expand_ambiguous_dna(seq):
"""return list of all possible sequences given an ambiguous DNA input"""
d = IUPAC.IUPACData.ambiguous_dna_values
return tuple(map("".join, product(*map(d.get, seq)))) | f420d2ceeb33ba28a7fb73f276744aa313716cfa | 3,609,983 |
def _check_selection(selection):
"""Handle default and validation of selection"""
available = ["counts", "exposure", "background"]
if selection is None:
selection = available
if not isinstance(selection, list):
raise TypeError("Selection must be a list of str")
for name in selecti... | 454b36833a5117b2d1bab377094e8e3ec0c06969 | 3,609,984 |
def read_wgs(filename, wgsname=None, boun_cond=None):
""" read a LaWGS file and create a LaWGS object
:param filename: filename of the LaWGS file
:param wgsname: "name" for the LaWGS object
:param boun_cond: a tuple containing the boundary conditions of each network
:return: LaWGS object
"""
... | 03e0bf906a5e8c59f911d08fbae670170f75ecde | 3,609,985 |
def calculate_v6_Psi2(chi_6222, chi_6222_err, vn_array):
"""
v6(Psi2) = chi_6222*sqrt(<abs(V2)**6>)
"""
dN = real(vn_array[:, 0])
Q2 = dN*vn_array[:, 2]
Q4 = dN*vn_array[:, 4]
Q6 = dN*vn_array[:, 6]
nev = len(dN)
N6_weight = dN*(dN - 1.)*(dN - 2.)*(dN - 3.)*(dN - 4.)*(dN - 5.)
... | 9de98855b5ea991e0315897a6ed51028fe93ae5a | 3,609,986 |
def shallTreatUninstalledPython():
"""*bool* = derived from Python installation and modes
Notes:
Not done for standalone mode obviously. The Python DLL will
be a dependency of the executable and treated that way.
Also not done for extension modules, they are loaded with
a Pytho... | a0ea3da4822448452b9d2965e5c885f071381d73 | 3,609,987 |
def force(value):
"""
This helper function forces evaluation of a promise. A promise
for this function is something that has a __force__ method (much
like an iterator in python is anything that has a __iter__
method).
"""
f = getattr(value, '__force__', None)
return f() if f else value | eccdbfe927eeac54246ac777ed16864a7da38ca7 | 3,609,988 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.