content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def visualize_img(img,
cam,
kp_pred,
vert,
renderer,
kp_gt=None,
text={},
rotated_view=False,
mesh_color='blue',
pad_vals=None,
no_text=Fals... | eb182cdd4042595abfba3c399c20fd5bba0ca352 | 3,657,577 |
import scipy
def conv_noncart_to_cart(points, values, xrange, yrange, zrange):
"""
:param points: Data point locations (non-cartesian system)
:param vals: Values corresponding to each data point
:param xrange: Range of x values to include on output cartesian grid
:param yrange: y
:param zrang... | cba013444ecdbd4abec14008dc6894e306244087 | 3,657,580 |
import urllib
import json
def createColumnsFromJson(json_file, defaultMaximumSize=250):
"""Create a list of Synapse Table Columns from a Synapse annotations JSON file.
This creates a list of columns; if the column is a 'STRING' and
defaultMaximumSize is specified, change the default maximum size for that... | 9eba1d44a9fec8e92b6b95036821d48d68cd991b | 3,657,581 |
from typing import Callable
from re import T
from typing import Optional
import warnings
def record(
fn: Callable[..., T], error_handler: Optional[ErrorHandler] = None
) -> Callable[..., T]:
"""
Syntactic sugar to record errors/exceptions that happened in the decorated
function using the provided ``er... | e538c51aeb4234aa85d90d9978d228bf0f505aac | 3,657,582 |
import torch
def bbox_overlaps_2D(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeate boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to... | 86920dac357285b3681629474ed5aaad471ed7f8 | 3,657,583 |
def decoder(data):
"""
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
... | 217f52081a476ef1c48d2d34d020ec6c7c9e1989 | 3,657,584 |
def calculate_exvolume_redfactor():
"""
Calculates DEER background reduction factor alpha(d)
See
Kattnig et al
J.Phys. Chem. B, 117, 16542 (2013)
https://doi.org/10.1021/jp408338q
The background reduction factor alpha(d) is defined in Eq.(18)
For large d, one can use the limiting express... | 3583e1526f1636feaa86a77c7f5ba51d816abe26 | 3,657,585 |
def get_successors(graph):
"""Returns a dict of all successors of each node."""
d = {}
for e in graph.get_edge_list():
src = e.get_source()
dst = e.get_destination()
if src in d.keys():
d[src].add(dst)
else:
d[src] = set([dst])
return d | 1ec7b0ab8772dc738758bb14fe4abd5dd4b9074e | 3,657,586 |
def readDataTable2o2(request):
"""Vuetify練習"""
form1Textarea1 = request.POST["textarea1"]
template = loader.get_template(
'webapp1/practice/vuetify-data-table2.html')
# -----------------------------------------
# 1
# 1. host1/webapp1/templates/webapp1/practice/vuetify-data-table2.... | 01688c20fa5057829338bbd76520a7b0510923ad | 3,657,587 |
from .sigma import decode_cf_sigma
from .grid import decode_cf_dz2depth
def get_depth(da, errors="raise"):
"""Get or compute the depth coordinate
If a depth variable cannot be found, it tries to compute either
from sigma-like coordinates or from layer thinknesses.
Parameters
----------
{erro... | 048208629eef6e5ecf238212e7a865e5fbaea993 | 3,657,588 |
def route53_scan(assets, record_value, record):
"""
Scan Route53
"""
for i, asset in enumerate(assets):
asset_type = asset.get_type()
if asset_type == 'EC2' and record_value in (asset.public_ip, asset.private_ip):
assets[i].dns_record = record['Name'].replace('\\052', '*')
... | eccbb2d716ef7b5dd713e7fbbd210c246c97347d | 3,657,589 |
import requests
def process_language(text):
"""
Fetch from language processing API (cloud function)
:param text:
:return:
"""
# The language processing seems to fail without acsii decoding, ie remove emoji and chinese characters
request = {
"text": text.encode("ascii", errors="ign... | d5b164cf0722093988f7cbb3f93ef62bc7c98758 | 3,657,590 |
def to_int(text):
"""Text to integer."""
try:
return int(text)
except ValueError:
return '' | d870ee05c3117111adcf85c91038b19beaf9585b | 3,657,591 |
def flooding(loss, b):
"""flooding loss
"""
return (loss - b).abs() + b | c34eedf0421b60e27bd813381ff7dfe96a3912eb | 3,657,593 |
def CreateConditions(p,avec,bvec,indexgenerator=CreateLyndonIndices):
"""This creates the set of equations using by default the Lyndon Basis elements.
Parameters
----------
p : the considered order
avec: The set of symbols to use for the first operator.
bvec: The set of symbols to use for the s... | 61ed4373d18a730838110865c8d4334176427bc4 | 3,657,594 |
def with_conf_blddir(conf, name, body, func):
"""'Context manager' to execute a series of tasks into code-specific build
directory.
func must be a callable taking no arguments
"""
old_root, new_root = create_conf_blddir(conf, name, body)
try:
conf.bld_root = new_root
conf.bl... | b01af0d8a44ad432020cc800f334f4de50b5036d | 3,657,595 |
def many_to_one(clsname, **kw):
"""Use an event to build a many-to-one relationship on a class.
This makes use of the :meth:`.References._reference_table` method
to generate a full foreign key relationship to the remote table.
"""
@declared_attr
def m2o(cls):
cls._references((cls.__nam... | 528f6391535a437383750346318ac65acaa8dfdc | 3,657,596 |
import sqlite3
def get_cnx(dbname=None, write=False):
"""Return a new connection to the database by the given name.
If 'dbname' is None, return a connection to the system database.
If the database file does not exist, it will be created.
The OS-level file permissions are set in DbSaver.
"""
if... | f2e3cc300fa4cb122a9fe4705d41878332929702 | 3,657,597 |
def nir_mean(msarr,nir_band=7):
"""
Calculate the mean of the (unmasked) values of the NIR (near infrared) band
of an image array. The default `nir_band` value of 7 selects the NIR2 band
in WorldView-2 imagery. If you're working with a different type of imagery,
you will need figure out the appropri... | 7ba6ea8b7d51b8942a0597f2f89a05ecbee9f46e | 3,657,598 |
def decode(invoice) -> LightningInvoice:
"""
@invoice: is a str, bolt11.
"""
client = CreateLightningClient()
try:
decode_response = client.call("decode", invoice)
assert decode_response.get("error") is None
result = decode_response["result"]
assert result["valid"], ... | c713ec8708214312b84103bceb64e0876d23bc29 | 3,657,599 |
def timing ( name = '' , logger = None ) :
"""Simple context manager to measure the clock counts
>>> with timing () :
... whatever action is here
at the exit it prints the clock counts
>>> with timing () as c :
... whatever action is here
at the exit it prints the clock coun... | f22769f267df8472f8b11db64ab6817db6e24414 | 3,657,601 |
def abs(x):
"""
complex-step safe version of numpy.abs function.
Parameters
----------
x : ndarray
array value to be computed on
Returns
-------
ndarray
"""
if isinstance(x, np.ndarray):
return x * np.sign(x)
elif x.real < 0.0:
return -x
return x | 71503b89e3a78e12a50f88ce2e0a17301f985ec7 | 3,657,602 |
import time
import re
from operator import sub
async def add_comm_post(request):
# return json.dumps(current_id, title, link, proc_id)
"""current_id это id ветки"""
# ip = request.environ.get('REMOTE_ADDR')
data = await request.post(); ip = None
print('data->', data)
#get ip address client
peername = request.tr... | 1038edd1834786ba1325e7f28f77f505adc8fb4b | 3,657,603 |
def reachable_from_node(node, language=None, include_aliases=True):
"""Returns a tuple of strings containing html <ul> lists of the Nodes and
pages that are children of "node" and any MetaPages associated with these
items.
:params node: node to find reachables for
:params language: if None, retur... | dcc93486fcae168293f17ee2a7c067dbc1eef5fe | 3,657,604 |
def init_data():
"""
setup all kinds of constants here, just to make it cleaner :)
"""
if args.dataset=='imagenet32':
mean = (0.4811, 0.4575, 0.4078)
std = (0.2605 , 0.2533, 0.2683)
num_classes = 1000
else:
raise NotImplementedError
if args.whiten_image==0:
... | 7d75af1f316a703041926d9a1875ae18f19c8342 | 3,657,605 |
def make_status_craft():
""" Cria alguns status de pedido de fabricação"""
if Statusfabricacao.objects.count() == 0:
status1 = Statusfabricacao(order=0, status='Pedido Criado')
status2 = Statusfabricacao(order=1, status='Maturação')
status3 = Statusfabricacao(order=2, status='Finalizaçã... | 01b9e1cbb48654f3baab7a4e55cd0f22a0bb60fe | 3,657,606 |
import requests
import json
def _call_rest_api(url, input_data, request_type):
"""Calls the other rest api's"""
try:
if request_type == 'post':
req = requests.post(url, params=input_data, json=input_data, timeout=30)
else:
req = requests.get(url, params=input_data, time... | 8c67e79c6867d1e63a1487c747682c24da229e46 | 3,657,607 |
def compute_tso_threshold(arr, min_td=0.1, max_td=0.5, perc=10, factor=15.0):
"""
Computes the daily threshold value separating rest periods from active periods
for the TSO detection algorithm.
Parameters
----------
arr : array
Array of the absolute difference of the z-angle.
min_td... | 4188d4a290e884210351f928d18d6f4bdd4e8a0b | 3,657,608 |
def run_generator(conversation_name):
"""
Input:
conversation_name: name of conversation to analyze
Output:
username of next speaker, message for that speaker to send next
"""
state = settings.DISCORD_CONVERSATION_STATES.get(conversation_name, {})
(
next_speaker_username... | 22735cdd46469976d079f065ee60e3a886dfc654 | 3,657,609 |
def count_uniques(row):
"""
Count the unique values in row -1 (becase nan counts as a unique value)
"""
return len(np.unique(row)) - 1 | af28e419aba44992ee27c57dacb271ff692fc535 | 3,657,610 |
import numpy
def gmres_dot(X, surf_array, field_array, ind0, param, timing, kernel):
"""
It computes the matrix-vector product in the GMRES.
Arguments
----------
X : array, initial vector guess.
surf_array : array, contains the surface classes of each region on the
... | 89ab7b49ef8f55bdeddbd9676acdc6cbe0de321f | 3,657,611 |
import torch
def update_pris(traj, td_loss, indices, alpha=0.6, epsilon=1e-6, update_epi_pris=False, seq_length=None, eta=0.9):
"""
Update priorities specified in indices.
Parameters
----------
traj : Traj
td_loss : torch.Tensor
indices : torch.Tensor ot List of int
alpha : float
... | 41648ae78f25618b2789d8dde41cffbe0445d16b | 3,657,612 |
from typing import Sequence
from pydantic import BaseModel # noqa: E0611
import hashlib
def get_library_version(performer_prefix: str, schemas: Sequence[Schema]) -> str:
"""Generates the library's version string.
The version string is of the form "{performer_prefix}_{latest_creation_date}_{library_hash}".
... | 90bf2c695eece054f20bc0636b8e9759983affef | 3,657,613 |
def sizeFromString(sizeStr, relativeSize):
"""
Converts from a size string to a float size.
sizeStr: The string representation of the size.
relativeSize: The size to use in case of percentages.
"""
if not sizeStr:
raise Exception("Size not specified")
dpi = 96.0
cm = 2.54
if len(sizeStr) > 2 and sizeStr[-2:... | 5f53d7d1ea86d4c54beb3aaebca228f7706e5a9b | 3,657,614 |
from typing import Union
from typing import List
def plot_r2(
model: mofa_model,
x="Group",
y="Factor",
factors: Union[int, List[int], str, List[str]] = None,
groups_df: pd.DataFrame = None,
group_label: str = None,
views=None,
groups=None,
cmap="Blues",
vmin=None,
vmax=Non... | 4898f56ca89ef55db775f0dc3b0106c36a2ced05 | 3,657,615 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import List
def all(x: Union[ivy.Array, ivy.NativeArray],
axis: Optional[Union[int, Tuple[int], List[int]]] = None,
keepdims: bool = False)\
-> ivy.Array:
"""
Tests whether all input array element... | 3854912ea0d6fceb4dc51576dd4b11923da68876 | 3,657,616 |
import re
def verify_time_format(time_str):
"""
This method is to verify time str format, which is in the format of 'hour:minute', both can be either one or two
characters.
Hour must be greater or equal 0 and smaller than 24, minute must be greater or equal 0 and smaller than 60
:param time... | fee469248d4d1d792c1ed858cf9043e5695c9f5d | 3,657,617 |
def extract_region_df(region_code="11"):
"""
Extracts dataframes that describes regional-level vaccines data for a single region, making some analysis on it.
:rtype: Dataframe
"""
df = RAW_DF
df = df.loc[df['codice_regione_ISTAT'] == region_code]
df = df.sort_values('data_somministrazione... | 8c3e77c1548b8bf40d0be31ac52237c532a4c622 | 3,657,618 |
from bs4 import BeautifulSoup
def get_title(offer_markup):
""" Searches for offer title on offer page
:param offer_markup: Class "offerbody" from offer page markup
:type offer_markup: str
:return: Title of offer
:rtype: str, None
"""
html_parser = BeautifulSoup(offer_markup, "html.parser"... | 72618da71ea63d1b3431ba76f5d8a9549af6fe76 | 3,657,619 |
def get_twinboundary_shear_structure(twinboundary_relax_structure,
shear_strain_ratio,
previous_relax_structure=None,
**additional_relax_structures,
):
"""
If lates... | c155db78f4d3d7f939e7c38e0c05955c3bd0f8c9 | 3,657,621 |
def _map_spectrum_weight(map, spectrum=None):
"""Weight a map with a spectrum.
This requires map to have an "energy" axis.
The weights are normalised so that they sum to 1.
The mean and unit of the output image is the same as of the input cube.
At the moment this is used to get a weighted exposure... | 5a1d9b9e3a94854e8c53947ca494f7448d2af570 | 3,657,622 |
def fetch_all_db_as_df(allow_cached=False):
"""Converts list of dicts returned by `fetch_all_db` to DataFrame with ID removed
Actual job is done in `_worker`. When `allow_cached`, attempt to retrieve timed cached from
`_fetch_all_db_as_df_cache`; ignore cache and call `_work` if cache expires or `allow_cach... | c7f049590c8405a862890944cfaabfefebea1d58 | 3,657,623 |
def tool_proxy_from_persistent_representation(persisted_tool, strict_cwl_validation=True, tool_directory=None):
"""Load a ToolProxy from a previously persisted representation."""
ensure_cwltool_available()
return ToolProxy.from_persistent_representation(
persisted_tool, strict_cwl_validation=strict_... | e1f96d66cb1634d4de82b3e31f0fb9dd81080262 | 3,657,624 |
def has_space_element(source):
"""
判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组
:param:
* source: (list, set, dict) 需要检查的对象
:return:
* result: (bool) 存在 None 或空字符串或空格字符串返回 True, 否则返回 False
举例如下::
print('--- has_space_element demo---')
print(has_space_... | ab8a968fb807654af73d9017145c0af2259ae41e | 3,657,625 |
def return_latest_psm_is(df, id_col, file_col, instr_col, psm_col):
""" Extracts info on PSM number, search ID and Instrument from the last row in DB
"""
last_row = df.iloc[-1]
search_id = last_row[id_col]
instr = last_row[instr_col]
psm = last_row[psm_col]
psm_string = str(psm) + ' PSMs in ... | 73c5acc945b9a6ef40aa1ce102351152b948a4b6 | 3,657,626 |
def add_parser_arguments_misc(parser):
"""
Adds the options that the command line parser will search for, some miscellaneous parameters, like use of gpu,
timing, etc.
:param parser: the argument parser
:return: the same parser, but with the added options.
"""
parser.add_argument('--use_gpu',... | 706ec64dfd6393fd1bd4741568e5e1af1d22a4d0 | 3,657,627 |
def plugin_init(config):
"""Registers HTTP Listener handler to accept sensor readings
Args:
config: JSON configuration document for the South device configuration category
Returns:
handle: JSON object to be used in future calls to the plugin
Raises:
"""
handle = config
retur... | a3e81bebdc806073b720e0a3174e62240ba81724 | 3,657,629 |
import time
import json
def search(query,page):
"""Scrapes the search query page and returns the results in json format.
Parameters
------------
query: The query you want to search for.
page: The page number for which you want the results.
Every page returns 11 results.
... | 4bcc78aeb29715adaca7b99d98d94c28448e24f7 | 3,657,630 |
def quote_with_backticks_definer(definer):
"""Quote the given definer clause with backticks.
This functions quotes the given definer clause with backticks, converting
backticks (`) in the string with the correct escape sequence (``).
definer[in] definer clause to quote.
Returns string with th... | ab87c8582d8081e324b494d7038916e984d5813a | 3,657,632 |
import base64
def cvimg_to_b64(img):
"""
图片转换函数,将二进制图片转换为base64加密格式
"""
try:
image = cv2.imencode('.jpg', img)[1] #将图片格式转换(编码)成流数据,赋值到内存缓存中
base64_data = str(base64.b64encode(image))[2:-1] #将图片加密成base64格式的数据
return base64_data #返回加密后的结果
except Exception as e:
return... | c9f4c99ff24578ac4f6216ddefade0602c60c697 | 3,657,633 |
from PIL import Image
from scipy.misc import fromimage
from skimage.color import label2rgb
from skimage.transform import resize
from io import StringIO
def draw_label(label, img, n_class, label_titles, bg_label=0):
"""Convert label to rgb with label titles.
@param label_title: label title for each labels.
... | 11b8f1e9c774df3e6312aa3dd0f71e7f300b5547 | 3,657,634 |
def inspect(template_dir, display_type=None):
"""Generates a some string representation of all undefined variables
in templates.
Args:
template_dir (str): all files within are treated as templates
display_type (str): tabulate.tabulate tablefmt or 'terse'.
Examples:
Yields an ov... | 1f557da1742ca3c2118bb5629f228079ee14e729 | 3,657,635 |
def calc_fitness_all(chromosomes, video_list, video_data):
"""Calculates fitness for all chromosomes
Parameters
----------
chromosomes : np.ndarrray
List of chromosomes
video_list : np.ndarray
List of all video titles (in this case number identifiers)
video_data : pd dataframe
... | e0a28880a31fb5d1546c4f959cd1836e89822471 | 3,657,636 |
from typing import List
from typing import Set
def grouping_is_valid(
proposed_grouping: List[Set[str]],
past_groups: List[Set[str]],
max_intersection_size: int,
) -> bool:
"""Returns true if no group in the proposed grouping intersects with any
past group with intersection size strictly greater t... | caeb7568a2e8fddea9058ccc512dc9c06070ece9 | 3,657,637 |
def next_wire_in_dimension(wire1, tile1, wire2, tile2, tiles, x_wires, y_wires,
wire_map, wires_in_node):
""" next_wire_in_dimension returns true if tile1 and tile2 are in the same
row and column, and must be adjcent.
"""
tile1_info = tiles[tile1]
tile2_info = tiles[tile2]
... | 2c2b6a2cb4d117f2435568437d38f05311b7dd13 | 3,657,638 |
from typing import Optional
def get(*, db_session, report_id: int) -> Optional[Report]:
"""
Get a report by id.
"""
return db_session.query(Report).filter(Report.id == report_id).one_or_none() | 021a7d35e060a2c92c9443361beff03de9aaf048 | 3,657,639 |
import urllib
def host_from_path(path):
"""returns the host of the path"""
url = urllib.parse.urlparse(path)
return url.netloc | 95b362e8f20c514a77506356c3a4a0c1ef200490 | 3,657,640 |
def sampleM(a0, bk, njk, m_cap=20):
"""produces sample from distribution over M using normalized log probabilities parameterizing a
categorical dist."""
raise DeprecationWarning()
wts = np.empty((m_cap,))
sum = 0
for m in range(m_cap):
wts[m] = gammaln(a0*bk) - gammaln(a0*bk+njk) + log(... | 76cc9e0bd6a0594bd8b6350053957073ccf9caf9 | 3,657,641 |
def or_default(none_or_value, default):
"""
inputs:
none_or_value: variable to test
default: value to return if none_or_value is None
"""
return none_or_value if none_or_value is not None else default | 43200fe3bd1308eed87de0ad905873fd3c629067 | 3,657,642 |
def find_optimal_components_subset(contours, edges):
"""Find a crop which strikes a good balance of coverage/compactness.
Returns an (x1, y1, x2, y2) tuple.
"""
c_info = props_for_contours(contours, edges)
c_info.sort(key=lambda x: -x['sum'])
total = np.sum(edges) / 255
area = edges.shape[0... | 016815811b6fa80378142303e3dce8f7736c514c | 3,657,643 |
import re
def scrape(html):
"""정규표현식으로 도서 정보 추출"""
books = []
for partial_html in re.findall(r'<td class="left">Ma.*?</td>', html, re.DOTALL):
#도서의 URL 추출
url = re.search(r'<a href="(.*?)">', partial_html).group(1)
url = 'http://www.hanbit.co.kr' + url
#태그를 제거해 도서의 제목 추출
... | 8703c48748607934491e92c3e0243e92cd7edf12 | 3,657,644 |
def get_time_zone_offset(area_code):
""" Returns an integer offset value if it finds a matching area code,
otherwise returns None."""
if not isinstance(area_code, str):
area_code = str(area_code)
if area_code in area_code_mapping:
return area_code_mapping[area_code][1] | 4697a07d53af25ef70facf30f4bbef2472494781 | 3,657,645 |
def true_false_counts(series: pd.Series):
"""
input: a boolean series
returns: two-tuple (num_true, num_false)
"""
return series.value_counts().sort_index(ascending=False).tolist() | 7fc7d0beb1d11aa7a4e3ccb6dd00155194deac3d | 3,657,646 |
def phyutility(DIR,alignment,min_col_occup,seqtype,min_chr=10):
"""
remove columns with occupancy lower than MIN_COLUMN_OCCUPANCY
remove seqs shorter than MIN_CHR after filter columns
"""
if DIR[-1] != "/": DIR += "/"
cleaned = alignment+"-cln"
if os.path.exists(DIR+cleaned): return cleaned
assert alignment.end... | 42a14d2588e71af5834179f0364925da31d9ef34 | 3,657,647 |
def configProject(projectName):
""" read in config file"""
if projectName==None:return
filename=os.path.join(projectsfolder,unicode(projectName),u"project.cfg" ).encode("utf-8")
if projectName not in projects:
print 'Content-type: text/plain\n\n',"error in projects:",type(projectName),"projectName:",[projectName... | e11c31be073b8699c2bd077815720467b9fd6e2e | 3,657,648 |
def bitwise_not(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The BitwiseNot operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param extent_type: on... | 0edaeaf2b96a48520309dee4809c3251d47c98e8 | 3,657,649 |
import re
def keyclean(key):
"""
Default way to clean table headers so they make good
dictionary keys.
"""
clean = re.sub(r'\s+', '_', key.strip())
clean = re.sub(r'[^\w]', '', clean)
return clean | 0f28f0e92e2817a98a31396949690a46e7538ace | 3,657,650 |
import collections
def get_rfactors_for_each(lpin):
"""
R-FACTORS FOR INTENSITIES OF DATA SET /isilon/users/target/target/Iwata/_proc_ox2r/150415-hirata/1010/06/DS/multi011_1-5/XDS_ASCII_fullres.HKL
RESOLUTION R-FACTOR R-FACTOR COMPARED
LIMIT observed expected
5.84 60.4% 50.1... | 937ad8e2cf01fa6ab92838d235a385f9bbfb1b63 | 3,657,651 |
def value_left(self, right):
"""
Returns the value of the right type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression.
"""
return right.value if isinstance(right, self.__class__) else right | f28c2f0548d3e004e3dd37601dda6c1ea5ab36f6 | 3,657,652 |
def correct_throughput(inspec, spFile='BT-Settl_Asplund2009.fits', quiet=False):
"""
Main function
Inputs:
inspec - list of input spectra, each list item should
be a 3xN array of wavelenghts (in microns),
flux, and variance. One list item for each
... | 1c1eecf308f738cce891176ab8e527be97839493 | 3,657,653 |
import numbers
import collections
def convert_list(
items,
ids,
parent,
attr_type,
):
"""Converts a list into an XML string."""
LOG.info('Inside convert_list()')
output = []
addline = output.append
if ids:
this_id = get_unique_id(parent)
for (i, item)... | 3e73fa756e5bd2685d529bb21170ab35dd6dedff | 3,657,654 |
def get_mid_surface(in_surfaces):
"""get_mid_surface gives the mid surface when dealing with the 7 different surfaces
Args:
(list of strings) in_surfaces : List of path to the 7 different surfaces generated by mris_expand
Returns:
(string) Path to the mid surface
"""
return in_surf... | 718ab8fa7a3b716241ae05a4e507f40ab6cb0efd | 3,657,655 |
def parse_type(msg_type):
"""
Parse ROS message field type
:param msg_type: ROS field type, ``str``
:returns: base_type, is_array, array_length, ``(str, bool, int)``
:raises: :exc:`ValueError` If *msg_type* cannot be parsed
"""
if not msg_type:
raise ValueError("Invalid empty type")
... | 1dfe4f3abb7b69bed17b60ee2666279081666dc6 | 3,657,656 |
from typing import List
from typing import Optional
import glob
def preprocess(feature_modules: List, queries: List[Query],
prefix: Optional[str] = None,
process_count: Optional[int] = None):
"""
Args:
feature_modules: the feature modules used to generate features, each ... | 2896482423d9306d01d225ef785e0680844a13a4 | 3,657,657 |
def to_distance(maybe_distance_function):
"""
Parameters
----------
maybe_distance_function: either a Callable, which takes two arguments, or
a DistanceFunction instance.
Returns
-------
"""
if maybe_distance_function is None:
return NoDistance()
if isinstance(maybe_... | 4e801a948d86594efdb1d05f352eb449e8bbdd02 | 3,657,658 |
def echo(text):
"""Return echo function."""
return text | c128bc86bc63006a1ac5b209c10b21f787b7100a | 3,657,659 |
def zernike_name(index, framework='Noll'):
"""
Get the name of the Zernike with input index in input framework (Noll or WSS).
:param index: int, Zernike index
:param framework: str, 'Noll' or 'WSS' for Zernike ordering framework
:return zern_name: str, name of the Zernike in the chosen framework
... | 33e73739c11bc2340a47162e161ba7d87e26d279 | 3,657,661 |
def discriminator_train_batch_mle(batches, discriminator, loss_fn, optimizer):
"""
Summary
1. watch discriminator trainable_variables
2. extract encoder_output, labels, sample_weight, styles, captions from batch and make them tensors
3. predictions = discriminator(encoder_output, captions, styles, t... | 2bb4cd47ddeea5c2edb6f627e39843ba18593833 | 3,657,662 |
def get_subs_dict(expression, mod):
"""
Builds a substitution dictionary of an expression based of the
values of these symbols in a model.
Parameters
----------
expression : sympy expression
mod : PysMod
Returns
-------
dict of sympy.Symbol:float
"""
subs_dict = {}
... | 075b406dfbdcb5a0049589880ad8b08fbd459159 | 3,657,663 |
def save_index_summary(name, rates, dates, grid_dim):
"""
Save index file
Parameters
----------
See Also
--------
DataStruct
"""
with open(name + INDEX_SUMMARY_EXT, "w+b") as file_index:
nlist = 0
keywords_data, nums_data, nlist = get_keywords_section_data(rates) ... | ac807dac6a1c63eca7b20322dc2c4122dc0b7ec8 | 3,657,664 |
def fluxes_SIF_predict_noSIF(model_NEE, label, EV1, EV2, NEE_max_abs):
"""
Predict the flux partitioning from a trained NEE model.
:param model_NEE: full model trained on NEE
:type model_NEE: keras.Model
:param label: input of the model part 1 (APAR)
:type label: tf.Tensor
:param EV1: input... | 3f5ecf95c27a4deb04894c84de903a5eb34858d0 | 3,657,665 |
def xml_string(line, tag, namespace, default=None):
""" Get string value from etree element """
try:
val = (line.find(namespace + tag).text)
except:
val = default
return val | 77745d463cf6604ed787e220fdabf6ff998f770e | 3,657,666 |
from datetime import datetime
def generate_header(salutation, name, surname, postSalutation, address, zip, city, phone, email):
"""
This function generates the header pdf page
"""
# first we take the html file and parse it as a string
#print('generating header page', surname, name)
with open('... | c979c2985d730eee0ce5b442e55a050e7cc4a672 | 3,657,667 |
def cli_cosmosdb_collection_exists(client, database_id, collection_id):
"""Returns a boolean indicating whether the collection exists """
return len(list(client.QueryContainers(
_get_database_link(database_id),
{'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [{'name': '@i... | 99ada0b4c4176b02d4bbe00c07b991a579a917d0 | 3,657,668 |
def probabilities (X) -> dict:
""" This function maps the set of outcomes found in the sequence of events, 'X', to their respective probabilty of occuring in 'X'.
The return value is a python dictionary where the keys are the set of outcomes and the values are their associated probabilities."""
# The set of outcomes... | c908a1186feea270be71bb1f03485c901bc82733 | 3,657,669 |
import time
import requests
def get_recommend_news():
"""获取新闻推荐列表"""
# 触电新闻主页推荐实际URL
recommend_news_url = 'https://api.itouchtv.cn:8090/newsservice/v9/recommendNews?size=24&channelId=0'
# 当前毫秒时间戳
current_ms = int(time.time() * 1000)
headers = get_headers(target_url=recommend_news_url, ts_ms=cu... | 3bee0bb7c1fb977d9380a9be07aab4b802149d6a | 3,657,670 |
def put_profile_pic(url, profile):
"""
Takes a url from filepicker and uploads
it to our aws s3 account.
"""
try:
r = requests.get(url)
size = r.headers.get('content-length')
if int(size) > 10000000: #greater than a 1mb #patlsotw
return False
filename, h... | 7bc201b754f33518a96a7e6a562e5a6ec601dfb5 | 3,657,671 |
from typing import Tuple
from pathlib import Path
from typing import Dict
def get_raw_data() -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Loads serialized data from file.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]: Tuple of
features, labels and classes for the dataset.
""... | 58e98b733c396fa8dca5f9dd442625283cae5f1e | 3,657,672 |
import requests
def cog_pixel_value(
lon,
lat,
url,
bidx=None,
titiler_endpoint="https://titiler.xyz",
verbose=True,
**kwargs,
):
"""Get pixel value from COG.
Args:
lon (float): Longitude of the pixel.
lat (float): Latitude of the pixel.
url (str): HTTP URL... | 40494f5ee491283b127409f52dd0e1d9029bce52 | 3,657,673 |
def select_daily(ds, day_init=15, day_end=21):
"""
Select lead time days.
Args:
ds: xarray dataset.
day_init (int): first lead day selection. Defaults to 15.
day_end (int): last lead day selection. Defaults to 21.
Returns:
xarray dataset subset based on time... | 9948ecba5acc3c1ca2fe28526585d0bfa81fb862 | 3,657,674 |
def project_polarcoord_lines(lines, img_w, img_h):
"""
Project lines in polar coordinate space <lines> (e.g. from hough transform) onto a canvas of size
<img_w> by <img_h>.
"""
if img_w <= 0:
raise ValueError('img_w must be > 0')
if img_h <= 0:
raise ValueError('img_h must be > ... | 7a6a75daedadc6ddfd6f8f55a7a57ae80865605e | 3,657,675 |
def standardize_for_imshow(image):
"""
A luminance standardization for pyplot's imshow
This just allows me to specify a simple, transparent standard for what white
and black correspond to in pyplot's imshow method. Likely could be
accomplished by the colors.Normalize method, but I want to make this as
expl... | 8b89235623746019b53d3c44dd8cecc2d313ffbd | 3,657,676 |
def err_failure(error) :
""" Check a error on failure """
return not err_success(error) | 17e9edbbe7bb5451d991fb94108148d2d0b1c644 | 3,657,677 |
def rah_fixed_dt( u2m, roh_air, cp, dt, disp, z0m, z0h, tempk):
"""
It takes input of air density, air specific heat, difference of temperature between surface skin and a height of about 2m above, and the aerodynamic resistance to heat transport. This version runs an iteration loop to stabilize psychrometric data fo... | bd48c62817f25964fa394ace35ab24357d455797 | 3,657,678 |
def process_grid_subsets(output_file, start_subset_id=0, end_subset_id=-1):
""""Execute analyses on the data of the complete grid and save the processed data to a netCDF file.
By default all subsets are analyzed
Args:
output_file (str): Name of netCDF file to which the results are saved for the... | 4103cffd3b519f16205fbf5dfb38ae198f315258 | 3,657,679 |
def bulk_lookup(license_dict, pkg_list):
"""Lookup package licenses"""
pkg_licenses = {}
for pkg in pkg_list:
# Failsafe in case the bom file contains incorrect entries
if not pkg.get("name") or not pkg.get("version"):
continue
pkg_key = pkg["name"] + "@" + pkg["version"]... | aa06b02fdfaa079dbfc4e1210ccccc995393dc52 | 3,657,680 |
def pack_bits(bools):
"""Pack sequence of bools into bits"""
if len(bools) % 8 != 0:
raise ValueError("list length must be multiple of 8")
bytes_ = []
b = 0
for j, v in enumerate(reversed(bools)):
b <<= 1
b |= v
if j % 8 == 7:
bytes_.append(b)
... | fadfb5e6abdb80691473262fac57f22384827c50 | 3,657,681 |
def init_ring_dihedral(species,instance,geom = []):
"""
Calculates the required modifications to a structures dihedral to create a cyclic TS
"""
if len(geom) == 0:
geom = species.geom
if len(instance) > 3:
if len(instance) < 6:
final_dihedral = 15.
... | 7799ec63b4188d79104e4ab758fb42b497a64053 | 3,657,682 |
from typing import List
from typing import Optional
def get_largest_contour(
contours: List[NDArray], min_area: int = 30
) -> Optional[NDArray]:
"""
Finds the largest contour with size greater than min_area.
Args:
contours: A list of contours found in an image.
min_area: The smallest ... | e505e9265540ae2f35e2de0f587aeaee067e5583 | 3,657,683 |
def mask_to_segm(mask, bbox, segm_size, index=None):
"""Crop and resize mask.
This function requires cv2.
Args:
mask (~numpy.ndarray): See below.
bbox (~numpy.ndarray): See below.
segm_size (int): The size of segm :math:`S`.
index (~numpy.ndarray): See below. :math:`R = N` ... | 5fd4003595ce7b13bcf59ce8669bfdb37a545d5b | 3,657,686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.