content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import select
async def get_team_list(session: Session = Depends(get_session)):
"""Get team list"""
statement = select(Team)
results = session.exec(statement).all()
return results | fb86056805ca713c8413ab1a2d5249326a9ff39a | 73,788 |
from typing import Dict
def NDFRTDDA(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/yue",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the NDFRTDDA graph.
The graph is automatically retrieved from the Yue repository.
Parameters
... | 81dc685cf1c927d9a00dd891cdca1229aaf6d49c | 73,789 |
from typing import Union
from typing import Optional
from typing import Tuple
def fetch_schema_locations(source: Union['XMLResource', XMLSourceType],
locations: Optional[LocationsType] = None,
base_url: Optional[str] = None,
allow: str =... | b2557f7de7313317db5ba424ce0a830774f76246 | 73,791 |
def readiob2(file, cols=('form', 'lemma', 'pos', 'att', 'gold_label', 'label', 'label/score')):
"""
Reads IOB2 file
"""
f = open(file)
sents = []
tmp = []
for line in f:
#print line
if line == "\n":
sents.append(tmp)
tmp = []
elif len(line.spli... | 69f38c5a8401450631c8a087ddc9c082577212c7 | 73,793 |
def split_train_val_partition(data,split_train_percentage, seed):
""" Partitions data into two partitions named tain and val
Args:
data (tuple): Containig two tensors one with the data samples and
the other with its correspondant labels
Returns:
... | 9c448f0f292cc32302e61f2c615d4e11475b1733 | 73,794 |
def add_polymarker(wks,plot,x,y,rlistc=None,isndc=0):
"""
Adds polymarkers to an existing plot and returns a PlotId representing
polymarkers added.
pmarker = Ngl.add_polymarker(wks, plot, x, y, res=None)
wks -- The identifier returned from calling Ngl.open_wks.
plot -- The id of the plot which you want to add the ... | a2c12ad7c148e0ad28eb94d8cb155e06998aa684 | 73,795 |
def delete(body, req):
"""Handles reqests and performs the delete on the Google Sheet"""
if req.query is not None or req.query['row_number'] is None:
raise Exception('Invalid request: missing query params.')
row_number = int(req.query['row_number'])
worksheet = get_sheet()
row = worksheet.r... | 1169ed55579e5a3b9975ba9b78f35daea250f061 | 73,796 |
def raw_einsum(
subscripts, *operands, keep_dims=frozenset(), out_append="{i}", einsum_kwargs=None, **kwargs
):
"""Wrap :func:`numpy.einsum` crudely.
Usage examples of all arguments is available at the
:ref:`einsum section <linalg_tutorial/einsum>` of the linear algebra module tutorial.
The descri... | b557b452618e2065b2a765edbf565e76a02b8265 | 73,798 |
def corr_coef(s_input: str) -> float:
"""
Used for parsing some inputs to this program, namely input correlation coefficients
:param s_input: String passed in by argparse
:return: Float value of correlation coefficient
"""
c = float(s_input)
if c < CORR_MIN_SCALING or c > CORR_MAX_SCALING... | 1d2da3fc29598348dfdc8be699af133b9e05314d | 73,799 |
def get_user(session: scoped_session, tg_user: User) -> User:
"""Get the user from the event."""
user = session.query(User).get(tg_user.id)
if user is not None and user.banned:
return user
if user is None:
user = User(tg_user.id, tg_user.username)
session.add(user)
try:
... | 0f0f3d7b6166adbbaac0ee8b90cff12e71261191 | 73,800 |
import torch
def single_roi_extractor__forward__openvino(ctx,
self,
feats,
rois,
roi_scale_factor=None):
"""Replaces SingleRoIExtractor wi... | fe9ac4ce577d4c6f0992eec558c6816257be0270 | 73,801 |
def trace_polygon(input_mask, mask_slice):
"""Convert mask with only edge pixels into a single contiguous polygon"""
# now extract the edges to trace
slice_edges = input_mask.astype(np.int16) - \
ndimage.binary_erosion(input_mask).astype(np.int16)
# trace edge from this region and id... | 09b7f5b4ed4d5c4ad236772ccbe777716853aaab | 73,802 |
import requests
from bs4 import BeautifulSoup
import re
def currency_hist(index_name="欧元/美元", start_date="2005/01/01", end_date="2020/01/17"):
"""
外汇历史数据获取, 注意获取数据区间的长短
:param index_name: {'欧元/美元': 'eur-usd', '英镑/美元': 'gbp-usd', '美元/日元': 'usd-jpy', '澳大利亚元/美元': 'aud-usd', '美元/加拿大元': 'usd-cad', '澳大利亚元/港币': ... | 45cd655a585960bde19da62f3393a4a623718204 | 73,803 |
def LinearGainLine(x1,y1,x2,y2):
"""
returns tuple (m,b)
that satisfies the equation y=mx+b
uses two points in histogram space to determine slope
x : 0..nbins
y : 0..255
"""
if (x2 > x1):
m = -(y1-y2) / (x2-x1)
else:
m = 0
b = x1
return m,b | 71d1d321c85636e15f05e3ab26c66a48a1cc5103 | 73,804 |
import base64
def display_base64_plot(fig):
"""Convert plot (matplotlib or seaborn) into base64 image (png) object
Args:
fig: matplotlib figure
Returns:
base64 object: Image of plot
"""
buf = BytesIO() # create in-memory file
fig.savefig(buf, format='png', bbox_inches='tigh... | acc82a7b31682513ef98622514c1f86587d87228 | 73,805 |
def ravanbakhsh_set_layer(layer_size,
inputs,
mask=None,
sequential=False,
activation_fn=tf.nn.tanh,
dropout=0.0,
name=None):
"""Layer from Deep Sets paper: https... | b52d1319330d8e15d3fc30e1e1d7747abebfc740 | 73,806 |
def redeem_insecure(code):
"""
Redeems a code in such a way that it should be possible to exploit if you
can make two requests at roughly the same time.
Args:
code: The code to redeem.
Returns:
A JSON counter, with the value 0 on success and -1 if no coupon was redeemed at all.
... | 5e4ca9550ce651db38e1de5eb21ef91a594275f7 | 73,807 |
def whitespace_or_bracket_after():
"""Check if there is whitespace or a closing
bracket to the right of the cursor"""
d = get_app().current_buffer.document
return bool(
d.is_cursor_at_the_end_of_line
or d.current_char.isspace()
or d.current_char in ")]}"
) | 17aed298a13d6b1fc354b3956a26c04dc67d27e3 | 73,808 |
import hashlib
def generate_key(instrument, run_id):
"""
Generate a secret key for a run on a given instrument
:param str instrument: instrument name
:param int run_id: run number
"""
if not hasattr(settings, "LIVE_PLOT_SECRET_KEY"):
return None
secret_key = settings.L... | 9980e2235be2c9e004b8106e7fef20cecede9ef8 | 73,809 |
def conv_transpose2d_nchw(inputs, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1, out_dtype="float32"):
"""Convolution transpose 2d NCHW layout
Args:
-----------------------------
inputs : GraphNode
shape [batch, channel, height, width]
weight : tGraphNode
... | 2c9e61e9dc49e835ce09cb73f0f0beb99bf31b54 | 73,810 |
import time
def wecom_hook(title='Task Done', text=None, hook_url=None):
"""装饰器里不可变参数
:param title:
:param text: 如果为空,用函数返回值填充【text覆盖函数返回值】
:param hook_url: hook_url或者群名称
:return:
"""
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
s = time.time()
r = w... | 6dd8c8f50b354484a960baeff3f7dfe3f9976cf5 | 73,811 |
def sorted_names(queue):
"""Sort the names in the queue in alphabetical order and return the result.
:param queue: list - names in the queue.
:return: list - copy of the queue in alphabetical order.
"""
new_queue = queue[:]
new_queue.sort()
return new_queue | b56bc362eb29d6395d8f74c187d0449a29f41302 | 73,812 |
def mean(num_lst):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_list : list
List of numbers to calculate the average of
Returns
-------
The average/mean of num_lst
"""
Sum = sum(num_lst)
count = 0
for num in num_lst:
count += 1
return Sum / count | 4339a8f755ebb26328bbbc76b2b76034d21ea004 | 73,813 |
def find_cycle(start, graph):
"""Finds a path from `start` to itself in a directed graph.
Note that if the graph has other cycles (that don't have `start` as a hop),
they are ignored.
Args:
start: str name of the node to start.
graph: {str => iterable of str} is adjacency map that defines the graph.
... | 0ce38b4813f6a0e55898ff3c17b54d35935ce85f | 73,815 |
import numpy
def square_aspect(xlim, ylim):
"""Calculates the limits to produce a square plot if all axes are
equal scale.
"""
x0, x1 = xlim
y0, y1 = ylim
x_range = numpy.abs(x1 - x0)
y_range = numpy.abs(y1 - y0)
if x_range > y_range:
fac = (x_range - y_range) / 2
r... | 65e4c6518004a86b258d9d7084215c116ea7b733 | 73,816 |
def oni_filter(traj, enso_type="N"):
"""
Filter out trajectories that have the given ENSO type(s).
Valid ENSO types include: "WE" (Weak El Niño), "ME" (Moderate El Niño), "SE" (Strong El Niño), "VSE" (Very Strong El Niño),
"WL" (Weak La Niña), "ML" (Moderate La Niña), "SL" (Strong La Niña), "N" (Neither... | 232947df727be4c42b5fa38d9720524690aef69f | 73,817 |
def MFMO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2013-11-16", **kwargs
) -> Graph:
"""Re... | f29c2a28aabe0dc38d7af739b115faf493af2361 | 73,818 |
import _functools
def apply_test(func):
"""
Execute test function after the initialize.
Notes
-----
[Example](https://stackoverflow.com/a/15196410)
"""
@_functools.wraps(func)
def wrapper(self, *args, **kwargs):
res = func(self, *args, **kwargs)
self.tests()
re... | be6ce533bdbbf9ae527656409708e7bd01109c8a | 73,819 |
def trials_to_df(trials):
"""Returns DataFrame of trial metrics."""
group, mouse, date, success, total_bouts, total_time, idle_time, bpm, auc = [], [], [], [], [], [], [], [], []
for trial in trials:
group.append(trial.group)
mouse.append(trial.mouse)
date.append(trial.date)
... | e2637502332618bdd23ab8f92dcee56c959f323e | 73,820 |
from pathlib import Path
def _read_all_pollutant_data(pollutant, comuni_names):
""" Read all the available pollutant data across multiple files and comune
"""
# Read data from the files
base_path = "../data/yearly_emissions"
all_data = [_read_pollutant_data_in_file(file_name, pollutant, comuni_nam... | e7e2d4a3e32c7908bc6c462817f32784503ea34e | 73,822 |
def get_default_estimator():
"""Retrieve a default choice of probability estimator
Returns:
sklearn model with predict_proba() method
"""
return LogisticRegression() | 552ff75cd0e1c6c323abf7baaaca4f663f205602 | 73,823 |
def broaden(mask):
""" Takes a 1D boolean mask array and returns a copy with all the non-zero
runs widened by 1.
"""
if len(mask) < 2:
return mask
# Note: the order in which these operations are performed is important.
# Modifying newmask in-place with the |= operator only works for if
... | 40f0e179ff3c773ba7149c45a07d34730716bee0 | 73,824 |
def postprocess_model_outputs(reg_output, cls_output):
""" Postproces raw outputs of the VisemeNet.
Args:
reg_output: Shape as (Num Frames, 22)
cls_output: Shape as (Num Frames, 22)
Return:
viseme_outputs: JALI based Lip blendshapes coefficients
"""
assert reg_output.shape ==... | 697cce5deebdca7e6c1eb30a4287b2f62446815e | 73,825 |
def extract_writer_path_argument(writer):
"""
Extracts path argument from pandas to_ methods.
Argument in position 1 (after self) is currently returned.
This function is needed to unwrap decorated writers.
>>> extract_writer_path_argument('to_pickle')
"""
return extract_writer_arguments(wri... | d3099cf2564cefd604ae2b29be60563a32fd5d46 | 73,826 |
def evaluate(values: list, poly: Polynomial):
"""Evaluate a polynomial using the provided values."""
pt = type(poly)
if pt == Sum:
return sum(evaluate(values, i) for i in poly)
elif pt == Prod:
res = 1
for item in poly:
res *= evaluate(values, item)
return r... | 1b482bf09de76bb1e9cc93562d644408e21d3218 | 73,827 |
def find_events(events, start, end, at_words=None):
"""Return (date, text, event) tuples for the events in our date range.
"""
things = set()
for event in events:
things.update(event.get_dates(start, end, at_words))
return things | 52a7250ad6ee172d52d3c563318eac3c4fd436cd | 73,828 |
import numpy
def peaks(n=40,noise=0.02):
"""Example 2D data: peaks function"""
nr,nc = n,n+5
x = numpy.linspace(-3,3,nr)
y = numpy.linspace(-3,3,nc)
[X,Y] = numpy.meshgrid(x,y)
v = 3*(1-X)**2*numpy.exp(-X**2 - (Y+1)**2) \
- 10*(X/5 - X**3 - Y**5)*numpy.exp(-X**2-Y**2) \
- 1... | f44e99bee0db2a35b93f804bf3a834314ee80f08 | 73,829 |
import hashlib
import md5, sha
def hashed_download_url(download_url, mode='simple', data=None, download=None):
""" Add a hash marker to the download_url.
This is done by fetching the URL, creating
one or more hash/size entries and appending these
as fragment to the download_url.
... | 5ce5b8a3d9d4daae48db793acfa5582e5d27b3c2 | 73,830 |
def ed_simple_chemical(definition: str, **kwargs) -> sbol3.ExternallyDefined:
"""Creates an ExternallyDefined Simple Chemical Component.
:param definition: The URI that links to a canonical definition external to SBOL, recommended ChEBI and PubChem.
:param kwargs: Keyword arguments of any other ExternallyD... | 2ab074771fd3aeb6921a63e5eee69c4fb16e43df | 73,832 |
def ess(x):
"""
Calculate the effective sample size (ESS) of a Markov chain `x`.
Parameters
----------
x : array_like, shape (n, m)
Markov chain.
Returns
-------
ESS : array_like, shape (m,)
Effective sample size per dimension.
"""
n, m = x.shape
return [n ... | d9dade45d77e8dd6c5a1973f666418608ec427ee | 73,833 |
def has_connected_children(bone):
""" Returns true/false whether a bone has connected children or not.
"""
t = False
for b in bone.children:
t = t or b.use_connect
return t | b88106b3ceac26987253e2995cda851f7a622d2f | 73,834 |
def create_user(first_name, last_name, email, phone_number, dob, address_id):
"""
Creates immutable user data structure
:param first_name: user's first name (string)
:param last_name: user's last name (string)
:param email: user's email (string)
:param phone_number: user's phone number (string)... | 2c6f647ac7f85fd56f4870bade01bb7a951ff4d2 | 73,835 |
def _argsort(seq):
"""The numpy sort is inconistent with the matlab version for values that
are the same
"""
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__) | a4b5117d8adef5295fb54e01b77e8d13e696925c | 73,836 |
def generate(content,
report_number=None,
doi_url=None,
month=None,
year=None,
authors=None,
**kwargs):
"""Take in LaTeX body with metadata and generate the LaTeX code using the NIST template
:param report_number:
:param doi_url:
:param month:
:param ... | b2ebb047433f1666f608665d21d4d9cec328ccd0 | 73,837 |
import warnings
def combined_hcw_with_contact(datastore,
healthcare_professional, contact_health_worker,
is_carer_for_community,
group, name):
"""
Deprecated, please use combined_healthcare_worker.combined_hcw_with_conta... | 500599a9e4d2fe45036876eceed91f5d6b6d83b6 | 73,838 |
def dist2weights_trapez(dist, max_r, r2, max_w=1, min_w=0):
"""Trapezoidal distance weighting.
Parameters
----------
dist: float or np.ndarray
the distances to be transformed into weights.
max_r: float
maximum radius of the neighbourhood considered.
r2: float
intermediat... | 19c68d49a1b5da3d56c02816024a7d565ab40778 | 73,839 |
def need_login(callback):
"""decorator to ensure a function is only callable when the user is logged in"""
def wrapper(*args, **kwargs):
session = session_manager.get_session()
if session['valid'] and (('id' in kwargs and kwargs['id']==session['user']['id']) or session['user'].is_staff):
... | adfd001402d75fb3703341fee7c1e2dc43b765fb | 73,840 |
import six
def ask_for_export_email():
"""Ask for a registered email address."""
print('You have not set the email variable at the top of this script.')
print('Please set this variable in the script, or enter it below. Note')
print('that you need to register your email at JSOC first. You can do')
... | 7ac8497021e71718f70c54f4c2b045fa455d65e5 | 73,841 |
def three_element_pharmacophore():
"""Returns as pharmacophore with three elements"""
hb_acceptor = PharmacophoricPoint(
feat_type="hb acceptor",
center=puw.quantity([1,0,0], "angstroms"),
radius=puw.quantity(1.0, "angstroms")
)
ring_1 = PharmacophoricPoint(
feat_type="ar... | d2c940fb7bf44ce17df9eab88a7e19a997d2f57c | 73,842 |
async def crawl(url, _list, deep, get, exclude=()):
"""Crawl for Bosch API correct values."""
try:
resp = await get(url)
if ("references" not in resp or deep == 0) and ID in resp:
if not resp[ID] in exclude:
_list.append(resp)
else:
if "references"... | 272da4a0a792826120d9607d27c1009386a1358d | 73,843 |
def _get_indices_and_values(x, index_matrix, jump_locations, values, side):
"""Computes values and jump locations of the piecewise constant function.
Given `jump_locations` and the `values` on the corresponding segments of the
piecewise constant function, the function identifies the nearest jump to `x`
from th... | e238a28d6c295d17e42f8f785a0794f0eedca8e4 | 73,844 |
import torch
def kmeans_init(X, k):
"""
Returns centroids for clusters using the kmeans++ initialization algorithm.
Accepts the data and the number of desired clusters (k).
See: https://en.wikipedia.org/wiki/K-means%2B%2B
"""
X = X.unique(dim=0)
n = X.shape[0]
idx = torch.randint(hig... | 3f06ff9dced03eb566f0122836e70252493f37ec | 73,845 |
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
x = cache
dx = np.where(x > 0, d... | 2fe1f97e383e730653ce2afaaf7e22327f64d69e | 73,846 |
def delete():
"""Delete a food item from the restaurant list."""
id = request.form.get("id")
Food.query.filter_by(id=id).delete()
db.session.commit()
flash("Item deleted!")
Food.query.all()
return redirect(
url_for("views.dashboard",
user=current_user,
... | 1f1eef9fdba22969ff9d2bd838f8a69ede6e100b | 73,847 |
def plot_planckian_locus_CIE1960UCS(planckian_locus_colours=None, **kwargs):
"""
Plots the *Planckian Locus* according to *CIE 1960 UCS* method.
Parameters
----------
planckian_locus_colours : array_like or unicode, optional
*Planckian Locus* colours.
Other Parameters
-------------... | ada45ce16f4ac0601cabd845aab12ac0b61b30a8 | 73,848 |
def tau_score(Y_true, Y_pred, sample_weight=None):
"""Kendall tau.
The Kendall tau is a metric of the correspondence between two rankings.
Values closer to 1 indicate strong agreement, and values closer to -1
indicate strong disagreement.
Parameters
----------
Y_true : ndarray of shape (n_... | 7fc047bfd068ff9ce058ec0523db076e762012e7 | 73,849 |
from typing import Union
def _str(s: Union[bytes, str], encoding) -> str:
"""
Ensure *s* is a string.
"""
if isinstance(s, str):
return s
return s.decode(encoding) | f16929b8de9a073be819f88d7d727aec53690f2d | 73,850 |
def openmc_name_to_onix_name(name):
"""Converts a nuclide's name written with OpenMC format ('U235_m1') into ONIX format ('U-235*').
**Note**: ONIX will adopt OpenMC name format in the next release.
Parameters
----------
name: str
Name of a nuclide in OpenMC format ('U235_m1')
"""
... | cc1ea4b766d6cfa5c2f253d6c80370c0fbb5028b | 73,851 |
from typing import Iterable
from typing import Dict
from typing import Any
from typing import Optional
from typing import List
def solve(output: Iterable[Variable], args: Dict[Variable, Any], executor: Optional[Executor] = None) -> List: # noqa: C901
"""Resolve the specified output variables.
The argument v... | 2fe5e7098b6091220ad886739ac7641dfd9ab338 | 73,852 |
def dlookup_in(d, l):
"""Return key from a dict if l in val."""
for k,v in d.iteritems():
try:
if l in v:
return k
except TypeError:
continue
return None | fa53a4e30607c783096b37eef3b3ca936de07097 | 73,854 |
import warnings
def calculate_residue_depth(aromatic_residues, model):
"""Returns a list of surface exposed residues as determined by residue depth.
Parameters
----------
aromatic_residues: list of :class:`Bio.PDB.Residue.Residue`
residues included in the analysis
model: :class:`Bio.PDB.M... | 20803e4e91682dcb8c095cf5e5e7ffdc2cff455f | 73,855 |
def clean_dataframe(df):
""" Clean up the dataframe.
Args:
df (pandas.DataFrame): Pandas dataframe.
Returns:
df (pandas.DataFrame): Cleaned pandas dataframe.
"""
# Remove duplicated rows
cols = ["cord_uid", "doi"]
df = remove_duplicates(df, cols)
# Remove rows... | 0cfe1a9700da145d24ea1418cd47f8e924892768 | 73,856 |
def new_gwyitem_string(item_key, value):
""" Create a new string GWY file item
Args:
item_key (string): GWY file item name
value (string): GWY file item value
Returns:
gwyitem (<cdata GwyfileItem*>): new GWY file item or
None if value is None... | 32480361d94243395f1d98e15d53cc7145831572 | 73,857 |
def CheckAccess(role, target=None, user=None, policy=None):
"""Checks whether the given user has the specified access role.
Args:
role: A Role constant identifying the desired access role.
target: The object to which access is desired. If 'role' is in MAP_ROLES,
this should be a Map object; if 'ro... | b1bdc309563e6798c8a71240e9f8109004d1b17d | 73,858 |
def api_delete_post(post_id):
"""Deletes a post (thread or post)"""
# parse request env
ipv4_addr = request.environ.get('REMOTE_ADDR', request.remote_addr)
# delete content from db
result = delete_post(post_id, ipv4_addr)
return jsonify(result), result['status'] | 8cf2f7e008f40b3d4b15dd47ae1edab1f91ba14e | 73,859 |
def percent(x, y):
"""Compute the percentage `x/(x+y)*100`.
"""
if x+y == 0:
return np.nan
return x / (x+y) * 100 | 2a922360677adb3a96c6c6330a80961a4be68057 | 73,860 |
import re
def get_valid_filename(name: str) -> str:
"""Return validf filename from HA entity name."""
return re.sub(r"(?u)[^-\w.]", "", str(name).strip().replace(" ", "_")) | 47426a4d1d9355eebb74c5f700bef30a8678eb72 | 73,862 |
def run_app(cmd_mgr, argv=None):
"""Runs application."""
return JiraApp(
description="The command line interface for Jira REST API",
version=jiractl.__version__,
command_manager=cmd_mgr,
deferred_help=True
).run(argv) | 0c8140aace0fba2765201e4a27b1450fc65af770 | 73,863 |
def svn_diff_fns2_invoke_datasources_open(*args):
"""
svn_diff_fns2_invoke_datasources_open(svn_diff_fns2_t _obj, void diff_baton, apr_off_t prefix_lines,
apr_off_t suffix_lines, svn_diff_datasource_e datasources,
apr_size_t datasources_len) -> svn_error_t
"""
return _diff.svn_diff_fns2_in... | d384e57da34ddfc39aa19fd82e1e21404bbf4208 | 73,864 |
def load_XYZRGBA(path, format=None):
"""
Load pointcloud from path.
Currently supports PCD and PLY files.
Format should be "pcd", "ply", or None to infer from the pathname.
"""
format = _infer_format(path, format)
p = PointCloud_PointXYZRGBA()
try:
loader = getattr(p, "_from_%s_f... | df9f7c47df3b4980425ac6918931d554ad605c84 | 73,865 |
import ast
def network_select_nodes(network, message="Select nodes."):
"""Select multiple nodes of a network.
Parameters
----------
network: :class:`compas.datastructures.Network`
message: str, optional
Returns
-------
list of hashable
"""
keys = []
guids = rs.GetObjects(... | 9ad3d775276c1f77df46a30d7389c5035f890554 | 73,866 |
def compute_pkg_type(package, type_):
"""
:param package: package that type is being imported into, ``str``
:param type: message type (package resource name), ``str``
:returns: python package and type name, ``(str, str)``
"""
splits = type_.split(genmsg.SEP)
if len(splits) == 1:
retu... | f275ce15265f926a65e42034570a615d91cf31f0 | 73,867 |
def get_class(score,cls):
"""Convert a score a 2 classes index
to a 2D score vector
Args:
score (float): The total score of cls+detection
Returns:
np.array: the score devided between two array position with the cls index
having the score value and the other one 1-score
"""
... | c2e9f16c42968b32a405cf5444d0b8e5ccafc818 | 73,869 |
def load_table_schema(name, con):
"""
load table schema from database
Parameters
----------
name : string, name of SQL table
con : sqlalchemy.engine.Engine or sqlite3.Connection
Returns
-------
sqlalchemy Table object
Example
-------
>>> import pandas as pd
>>> fro... | c026db975b373833f6f90637fd5a69aec6cefdca | 73,870 |
def remove_duplicates_for_fetch(items: list, last_fetched_ids: list) -> list:
"""Remove items that were already sent in last fetch.
Args:
items (list): Items retrieved in this fetch.
last_fetched_ids (list): ID's of items from last fetch.
Returns:
(list) New items wi... | 705e786563206015877798e227c89a978831f97f | 73,871 |
def append_unique(the_list, new_item):
"""
append the newe_item to the_list, only if it does not exist
:param the_list:
:param new_item:
:return:
"""
exist = any(new_item == item for item in the_list)
if not exist:
the_list.append(new_item)
return the_list | 2974643e1cbbc7c0cf8dccb7ddc1fd21368eb3f8 | 73,873 |
def densify(embeddings, positive_seeds, negative_seeds, entity_seeds, notity_seeds, lexicon2_vocab={}, **kwargs):
"""
Adapted from: http://arxiv.org/pdf/1602.07572.pdf
"""
p_seeds = {word:1.0 for word in positive_seeds}
n_seeds = {word:1.0 for word in negative_seeds}
e_seeds = {word: 1.0 for wor... | 4a56f2c67e19de908e8c15a33aa2454ac36acc4d | 73,874 |
def xm(A):
"""Returns the maximum number of emmited neutrons in a
A(g,xn)X reaction
See function cs_gxn()
Arguments:
A {int} --
Returns:
int -- Maximum number of neutrons to be produced
"""
return int(1.4 * A**.457) | 80b9d3c808e286d975894e830251c80bd614a2c7 | 73,876 |
def nearest(
lat: float,
lon: float,
n: int = 1,
is_airport: bool = False,
sends_reports: bool = True,
max_coord_distance: float = 10,
) -> "dict/[dict]":
"""
Finds the nearest n Stations to a lat,lon coordinate pair
Returns the Station and coordinate distance from source
NOTE:... | b32189325fa5e83680fe7c39926369fa010d2751 | 73,877 |
import re
def pad_numbers(s):
"""Modify a string to make its numbers suitable for natural sorting."""
return re.sub(r'\d+', lambda m: m.group(0).rjust(16, '0'), s) | a1556d8b430d8745bff3c7f414304a6864384f2f | 73,878 |
from typing import Tuple
from typing import List
def flatten(array: Tuple[List[Tuple[int, int, int, int, int]]]):
"""
:param array:
:return:
Flattens move tuple a single level deep
"""
flat_list = []
for sublist in array:
for item in sublist:
flat_list.append(item)
... | 835f2d166a07c41d1803e2c1c4a7244990326302 | 73,879 |
def vgg_19(inputs,
num_classes=1000, # no effect
is_training=False, # no effect
dropout_keep_prob=0.5, # no effect
spatial_squeeze=True, # no effect
scope='vgg_19',
reuse = False,
fc_conv_padding='VALID'):
"""Changed from t... | 800155764890dcf776c32b453a917973375b0d90 | 73,881 |
def mapFromClm_fast(clm, nside):
"""
Given an array of C_{lm} values, produce a pixel-power-map (non-Nested) for
healpix pixelation with nside
@param clm: Array of C_{lm} values (inc. 0,0 element)
@param nside: Nside of the healpix pixelation
return: Healpix pixels
Use Healpix s... | 86d2c0b3a7ebaf88fd2e9e11e3b5bee130e86436 | 73,883 |
def fibonacci_iter(n):
"""Fibonacci series by bottom-up iteration with optimized space.
- Time complexity: O(n).
- Space complexity: O(1).
"""
if n <= 1:
return n
# Track the last two fib numbers.
a, b = 0, 1
for _ in range(2, n + 1):
# Add two numbers and then shift po... | 5a49ec3c670e73573ae7a36328734af54887ea86 | 73,885 |
def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader):
"""Provides yaml.load alternative with preserved dictionary order.
Args:
stream (string): YAML string to load.
loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe
load.
Returns:
OrderedDict: Pars... | 7af6b3f7df0259675f533d5b61a8c537bdca177f | 73,886 |
def cluster_leave(username, hostname):
"""
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
"""
... | bfca6fd0903f6d322ccf0841bd7a5a502f83354a | 73,887 |
from typing import Optional
def get_enrollment_account_scope(billing_account_name: Optional[str] = None,
enrollment_account_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEnrollmentAccountScopeResult:
"""
... | 5da83d525ece9de108b8ebc54cccea25bed5a2e4 | 73,888 |
def put_handler(request, response):
"""HTTP PUT Handler"""
try:
if "multipart" in request["header"]["Content-Type"]:
request = form_parser(request)
request["content"] = multipart_parser(request)
else:
request["content"] = parse_fields(request["body"])
... | 4c2852dd8ac274c929b07de72e74f4b10de9eccd | 73,889 |
def get_playoff_bracket_string(league):
"""
Creates and returns a message of the league's playoff bracket.
:param league: Object league
:return: string message league's playoff bracket
"""
bracket = league.get_playoff_winners_bracket()
return bracket | 0ac2e02493a99c830704d6651125e0c30c8f4c7c | 73,890 |
def odd_man_out(inp):
"""If input looks like an odd integer, return
twice its value; otherwise, return None"""
try: #If it's a number, can it be cast as an integer?
inp = int(inp)
except:
return None
#try: #Is it a number at all? If not, give up.
#inp/1
#except:
... | ad9899878b856b5965cf9860c94c05f1e4c9123b | 73,892 |
from typing import List
async def send(
message: str, queue: str, routing_key: str, params: List[str] = Query([])
):
"""
Send a message to Angora.
"""
print(message, queue, routing_key, params)
try:
Message(EXCHANGE, queue, message, data=params).send(
USER, PASSWORD, HOST,... | 759ecf139ed5bcca8c7e5a71e70b4d9b7083cf44 | 73,893 |
def multibillings(request):
""" Lists all multibills """
context = {}
multibills = MultiBilling.objects.annotate(num_closed_events=Sum(Case(
When(events__closed=True, then=1),
default=0,
output_field=IntegerField())))
page = request.GET.get('page')
sort = reques... | db62c1ea5ddb9624189a2f5702515a9d21db937c | 73,894 |
def oxygen_abundance(Z):
"""
Set the oxygen abundance.
We assume Asplund et al 2009 abundance at Zsun and that Ao scales linearly with Z. Z in solar units
"""
Ao = 4.90e-4
return Ao*Z | 1fe4ad34afbbe4c43fd883df434d9fcc7a83b9b7 | 73,895 |
import doctest
def load_tests(loader, tests, ignore):
""" Add the Doctests from the module """
tests.addTests(doctest.DocTestSuite(DistFunctions, optionflags=doctest.ELLIPSIS))
return tests | 55bbf667a02054c29b5466d378d77e5003ff6ba6 | 73,896 |
def save_keyframe_images(images_dir, data_source, region_index):
"""
save image of the region at each key frame
Args:
images_dir,
data_source, region_index
"""
results = data_source.get_results()
region = results.get_regions()[region_index]
key_frames = results.ge... | a200defea32485a0e6892d62b199574f9e283b42 | 73,897 |
def subdivide_dict(dictionary, num_subdivisions):
"""
Distributes the k: v pairs in dict to N dicts.
"""
subdicts = [{} for i in range(num_subdivisions)]
for i, k in enumerate(dictionary.keys()):
sub_index = i % num_subdivisions
subdicts[sub_index][k] = dictionary[k]
return subdi... | 6aa9abeff609115e1ecd1085d4ba0d875c59bf2d | 73,898 |
def get_version(clang):
""" Returns the compiler version as string.
:param clang: the compiler we are using
:return: the version string printed to stderr """
output = run_command([clang, '-v'])
# the relevant version info is in the first line
return output[0] | 7eee3767ef66d7f41289c285c001cfc83d05bebe | 73,899 |
def move_images(df, label_column, current_path, destination_path):
"""
Moves images from combined folder to new folder based on data splits
df: dataframe containing image IDs to move
label_column: name of column containing labels
current_path: path to where the images are currently stored
de... | 57302f03423f3f7a78432e464c94cdd06ebeec51 | 73,900 |
def parse_conn_uri(s):
"""Split uri to parts:
sheme, use, password, host, port, path.
Absent parts replaced with None
Arguments:
s {[str]} -- [uri]
Returns:
[UriParts] -- [Parsed uri]
"""
match = RE_URI_TEMPLATE.match(s)
if not match:
raise ValueError(f"... | 0f261b5fc340b56eafd3be431054f5c3fd70a59b | 73,902 |
def calculate_PCF(coords, r_max, eu_side):
# calculate Pair Correlation Function (PCF) for evidence units represented by their coordinates
"""
Compute the two-dimensional pair correlation function, also known
as the radial distribution function, for a set of circular particles
contained in a square region of a ... | f18fdd1deac7cd09a7f72b8756c81d427fdeb301 | 73,903 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.