content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment_id
The id of the comment the user is flagging.
"""
comment = get_object_or_404(
get_comment_model(),
... | 99f445fadcd088071651837e1d9fda9fea2b0d22 | 3,626,285 |
def decodeGsm7(encodedText):
""" GSM-7 text decoding algorithm
Decodes the specified GSM-7-encoded string into a plaintext string.
@param encodedText: the text string to encode
@type encodedText: bytearray or str
@return: A string containing the decoded text
@rtype: str
"""
... | 28ca699a8f1637637a76e375056b1f48d8807e9f | 3,626,286 |
def Setup_Meta():
"""Setup_Meta() -> MetaObject"""
return _DataModel.Setup_Meta() | cc66b9e0e8e95ecaa1dd0211fd260ed4755d20a0 | 3,626,287 |
def get_types_dict():
"""
:return: type name read in as string to type method mapping
"""
return {"str": str, "float": float, "int": int} | 7a386fa63cba73e35672b15c31bc8b2c59361f24 | 3,626,288 |
def key_pressed(key):
"""
Takes a key, that's either a keycode or a character,
and says if it was pressed down this frame.
"""
keycode = _to_keycode(key)
return (keycode in current_frame_held_buttons) and \
(keycode not in last_frame_held_buttons) | 26d1716cdfcb187a661418b77114611a8945e7b3 | 3,626,289 |
def makeDir(path, name):
""" create dir for the generation process"""
print "path", path
print "name",name
dirname = path + os.sep + name
try:
os.makedirs(dirname)
return dirname
except:
print "makeDir> ERROR creating dir [%s]: %s" % (dirname, exc_info()[1])
retur... | 1874d52e00e31aa3a2d1b67cb791af622a879438 | 3,626,290 |
def load_gp(param_file=None, **kwargs):
"""Return two Gaussian Processes objects, either using BSFH's internal GP
objects or George.
:returns gp_spec:
The gaussian process object to use for the spectroscopy.
:returns gp_phot:
The gaussian process object to use for the photometry.
"... | e216001c0942e2efacc2631c52d2c6dd42a0caed | 3,626,291 |
from pydantic import BaseModel # noqa: E0611
def monte_carlo(model, num, qobs=None, **kwargs):
"""Perform Monte-Carlo-Simulation.
This function performs a Monte-Carlo-Simulation for any given hydrological
model of this repository.
Args:
model: Any instance of a hydrological model of this re... | 95e29fa77535733214d6f5bee293fa4dfdf361c2 | 3,626,292 |
def create_class_hierarchy_dict(cls):
"""Returns the dictionary with all members of the class ``cls`` and its superclasses."""
dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class
attrs_dict = {}
for base_class in dict_extension_order:
attrs_dict.update(vars(... | 0378fb3243a48964fcec42fddb38c0664a338ee4 | 3,626,294 |
def get_column_selection(summary_set):
"""
Given a analysis_settings summary definition, return either
1. the set of OED columns requested to group by
2. If no information key 'oed_fields', then group all outputs into a single summary_set
:param summary_set: summary group dictionary from th... | 2cdb9a74a65cb9a217f2296a7e8ce22557095314 | 3,626,295 |
from typing import List
from typing import Optional
def randomForestSearch(
operations: OperatorSet,
output: List[Individual],
start_candidates: List[Individual],
max_evaluations: Optional[int] = None,
) -> List[Individual]:
""" Perform random search over all possible pipelines.
Parameters
... | 74197bfdd7b993db24a03f0f247a5eae40696859 | 3,626,296 |
from datetime import datetime
def month_to_date(month):
"""
Convert month to date format.
Keyword arguments:
month -- the month to convert to date format
"""
month = datetime.strptime(month, '%Y-%m')
date = month.strftime('%Y-%m-%d') # eg 2018-02-01
date = datetime.strptime(date, '... | e417eefa63430e422a53bd194fbb1e0d5e453c7b | 3,626,297 |
from datetime import datetime
def exact_cftime_datetime_difference(a, b):
"""Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds asso... | f05c6cdd7cb9c211fb50fc493f1bac25dce15b92 | 3,626,298 |
def encode(string):
"""Encode some critical characters to html entities."""
return string.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>') \
.replace(' ', ' ') \
.replace('\n', ... | faea4b2f2e032b5e05e2c99bc56a1cf35e60b85d | 3,626,299 |
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a) | 22b421c090970810f9aa4d55ff5a700e1301c0b8 | 3,626,300 |
def update_movie(movie_id):
"""Route handler for endpoint updating a single movie.
Args:
movie_id: An int representing the identifier for the movie to update
Returns:
response: A json object representing info about the updated movie
"""
movie = Movie.query.get(movie_id)
if mov... | e4062f327a077341e71e95d7b589f3bb4c36da5a | 3,626,301 |
def note_list(request):
"""Notes list view
"""
notes = NoteTable(Note.objects.all())
RequestConfig(request).configure(notes)
return render(request, 'note_list.html', {'notes': notes}) | 89c4537712f51ad9559ed04b74fcd774a7774a6a | 3,626,302 |
from datetime import datetime
def getDateTimeFromLocalTimeStamp(ts):
"""
Get a datetime structure from a timestamp.
"""
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
return st | 8282c16f50b34db9ac446fde4da020c614e6ac7f | 3,626,303 |
def c_roots(n, mu=False):
"""Gauss-Chebyshev (first kind) quadrature
Computes the sample points and weights for Gauss-Chebyshev quadrature.
The sample points are the roots of the `n`th degree Chebyshev polynomial of
the first kind, :math:`C_n(x)`. These sample points and weights correctly
integrat... | 0b70b09bdcaffdcd4857af1caaa96512c0720dc9 | 3,626,304 |
def find_instance_nested(item, instances, match_key=None):
"""
Recursively find instances from lists, dicts, tuples.
`instances` should be a tuple of valid instances
If match_key is given the key must match for an instance to be added to the list of found instances.
"""
matches = []
def v... | 6ee2e7d936c162dcbdde40ca4b58a141568009d4 | 3,626,307 |
def get_filer_image(image_name="test_file.jpg", name="", original_filename=True):
"""
Creates and stores an image to filer and returns it
:param image_name: the name for the file (default "test_file.jpg")
:returns: filer image instance
"""
image = get_image(image_name)
filename = None
i... | 7446eeedd7078bd606006b1605b5406c0f230670 | 3,626,308 |
def import_table(file, sep = ","):
"""[Import table (csv or xlsx) into memory]
Args:
file ([string]): [file path]
sep (str, optional): [separator character that should be used]. Defaults to ",".
Returns:
[dataframe]: [the table imported]
"""
file_path = path_checker(file)
... | e821ac5bc6d22d21454525b91cfdf73f2b14ca0e | 3,626,310 |
def unixtime(tz = None):
"""
:param tz: [optional] tzinfo
:return: int
"""
return int(dt.datetime.now(tz).strftime('%s')) | 360b7e23fefe27d730224ac8fb59f46a59eab4be | 3,626,311 |
def demo7(response):
"""在每次请求后运行"""
# eg:修改响应头
print(response)
print('=========== after func run =============')
# response.headers['Content-Type'] = 'application/json;charset=utf-8;'
return response | 86991057bb48f1da33b3417387009d98744d2d94 | 3,626,312 |
def build_distance_layers(cyt_coord, nuc_coord, rna_coord, normalized=True):
"""Compute distance layers as input for the model.
Parameters
----------
cyt_coord : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
nuc_coord : np.ndarray, np.int64
... | 1b2b3cfd8edb43c8d294fcebd262244391ab8500 | 3,626,313 |
def one_hot_encode(arr, classes=None):
"""
One-hot encode a 1D array.
Based on this StackOverflow answer: https://stackoverflow.com/a/29831596/5863503
Parameters:
-----------
arr : array-like
An array to be one-hot encoded. Must contain only non-negative integers
classes : int or No... | 75d3db88a7ff6c590b3f5862ca2d6d59be149d0d | 3,626,314 |
def identity(value):
"""
Node returning the input value.
"""
return value | e1af1346b11bc36a4426ad3c557dc01045657de8 | 3,626,317 |
import asyncio
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
if CONFIG_MAIN_API_KEY in entry.data:
target_domain = "sensor"
elif CONFIG_TARGET_NAME in entry.data:
target_domain = "binary_sensor"
unload_ok = all(
await asyncio.gather(
*[hass.co... | 5f847cc9d2518b0b6d73568fe246ef1917ce6da8 | 3,626,318 |
import re
def strip(input_file_name):
"""
Remove all leading and trailing white-spaces, from 'input_file_name'.
And output result into into current directory.
Args:
input_file_name (str): path to input file
Returns:
int : number of modified lines.
"""
modified_lines = 0
p... | 203211f3ff7ee20a3417b1202b919dacd8291ef7 | 3,626,319 |
def render_post_ioc_init_elements(ioc: IOC) -> str:
"""
Render all of the post-iocInit elements for a given IOC instance
"""
return render_elements(ioc, "render_post_ioc_init") | 07f62ccca8e1325e8266dc7cb2e7cb71b8e83699 | 3,626,320 |
def getZnProjectors(xform_op, n_xforms, print_results=False):
"""
Returns operators which project on to symmetry subspaces associated with a given
symmetry transformation if the symmetry group is a cyclic group. Examples of appropriate
symmetries are translational or pure rotational symmetry.
Repre... | aa745c68393475203e3adb54e748495511fa06be | 3,626,321 |
def small_caves_multigraph():
"""
For each `big_cave` in `big_caves` and for each u, v in the neighborhood of `big_cave`,
add an edge (u, v) to `caves`. Afterwards, remove all big caves. The remaining
edges between the small caves now have multiplicity that can be used to count paths.
"""
caves... | d1c5ca007b2623c8d004d723d3022f89116be692 | 3,626,322 |
import logging
def train_model():
"""Train for a fixed number of steps and decode during training."""
rng = jax.random.PRNGKey(0)
model = create_model(rng)
optimizer = create_optimizer(model, FLAGS.learning_rate)
for step in range(FLAGS.num_train_steps):
batch = get_batch(FLAGS.batch_size)
optimize... | 1d91302b5b66c23e06db786091bf7657db8b4ba4 | 3,626,323 |
def rescale(arr, low=0, high=1, axis=None):
"""Return rescaled array, with values scaled between ``low`` and ``high``
Parameters
----------
arr : ndarray
numpy array to be rescaled
low : float (array scalar) or ndarray, optional
specifies the lower value(s) of the rescaled array
... | 198790b50ebd989ed99e26d68ebf399cc1c687ec | 3,626,324 |
import re
def named_numbers(token_vector):
""" Function to remove numbers out of an array of sentences.
Args:
token_vector (array): Array containing tokenized, lowercased sentence.
Returns:
array: Array containing tokenized sentence removed numbers.
"""
retur... | 6438e329af01e9da28f65f07f0e852096fead5f5 | 3,626,325 |
import re
def parse_members_for_workspace(toml_path):
"""Parse members from Cargo.toml of the worksapce"""
with open(toml_path, mode='rb') as f:
data = f.read()
manifest = data.decode('utf8')
regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M)
members_block = regex.findall(manif... | 63926ac1eaadc360e2407f2fff5f41b7667e52b4 | 3,626,326 |
from typing import Union
from typing import Optional
from typing import Dict
from typing import Any
def _get(
parser: Union[Optional[ConfigParser], SectionProxy], key: str, overrides: Optional[Dict[str, Any]], defaults: Dict[str, Any]
) -> Any:
"""Get a value from a parser, overriding or setting a default as ... | 6ac806f5852c007ea56ca38ced726e47bf8a03e6 | 3,626,327 |
import time
def get_rate(net_card):
"""
统计每秒接收到的数据大小
:parma net_card: 网卡名字
:return : 返回未格式化的信息
"""
net_cards = []
old = [0, 0, 0, 0]
new = [0, 0, 0, 0]
if net_card is None: # 抓取全部网卡的速度
net_cards = net_io_counters(pernic=True).keys()
else:
net_cards.append(net_c... | d0dab4308c25e020a30a1172db91082b926ecfed | 3,626,328 |
def get_application(rawEvent):
"""Return application details."""
application = dict()
application["external_ip"] = rawEvent["details"]["browser"]["address"]
# Process user agent string.
userAgent = rawEvent["details"]["browser"]["user-agent"]
application["name"] = httpagentparser.detect(userAg... | 3e6cc7436a9b8abe7751590c1a1e3e1c40f2ea3a | 3,626,329 |
import torch
def steering(taus, n_fft):
""" This function computes a steering vector by using the time differences
of arrival for each channel (in samples) and the number of bins (n_fft).
The result has the following format: (batch, time_step, n_fft/2 + 1, 2, n_mics).
Arguments:
----------
ta... | c33264516e6903d22533c9f23585739438aa5d75 | 3,626,330 |
import numpy as np
def shoot(lon, lat, azimuth, maxdist=None):
"""Shooter Function
Original javascript on http://williams.best.vwh.net/gccalc.htm
Translated to python by Thomas Lecocq
"""
glat1 = lat * np.pi / 180.
glon1 = lon * np.pi / 180.
s = maxdist / 1.852
faz = azimuth * np.pi / ... | 732571c61b797c5018243b1aaa86f89d055566af | 3,626,331 |
from typing import Dict
def subsitute(clause: Clause, transformation: Dict[Argument, Argument]) -> Clause:
"""Applies given transformations to the clause.
Example: X -> a for P(X) will result in P(a)
"""
for t in transformation:
clause = Clause(
frozenset([substitute_literal(l, t,... | 04becf153a0f9138aeb73708d3cd2fc983dab9b7 | 3,626,332 |
def get_loss_fn_v2(loss_factor=1.0):
"""Gets a loss function for squadv2.0 task"""
def _loss_fn(labels, model_outputs):
start_positions = labels['start_positions']
end_positions = labels['end_positions']
is_impossible = labels['is_impossible']
_, start_logits, end_logits, cls_log... | b409a05462e745b907f891d92365e1d0e61ffbb1 | 3,626,333 |
def decodeXMLName(name):
"""
Decodes an XML (namespace, localname) pair from an ASCII string as encoded
by encodeXMLName().
"""
if name[0] is not "{": return (None, name.decode("utf-8"))
index = name.find("}")
if (index is -1 or not len(name) > index):
raise ValueError("Invalid enc... | 28a81aed2477b444ac061b21ca838912ee2bf24b | 3,626,335 |
def get_windowing(data):
"""
Retrieves windowing data from dicom metadata
Arguments:
data {pydicom data obj} -- object returned from pydicom dcmread()
Attribution: This code comes from Richard McKinley's Kaggle kernel
"""
dicom_fields = [data.WindowCenter,
data.Windo... | bfb7588126770c5b7403291f991351d18f23b2fd | 3,626,336 |
from typing import List
from typing import Tuple
def convert_mat_non_zero_to_inv_mat(n: int, non_zero_idx_pairs: List[Tuple[int,int]], mat_non_zero: np.array) -> np.array:
"""Convert list of matrice's non-zero elements into the matrice's inverse
Args:
n (int): Size of matrix
non_zero_idx_pai... | c580ff8a0ee79f3b434da58454670985e34b9567 | 3,626,337 |
def Logger_stringToLevel(str):
"""
Logger.stringToLevel(s)
parses a string and returns a Logger::Level
:param str s: the string to parse.
"""
return _roadrunner.Logger_stringToLevel(str) | 7fe5da5f6a7b59e436f2d6b6b7d277673db5a8c8 | 3,626,338 |
def get_time_index(path,f):
"""Calculate the number and mass of objects around the centre of mass fro a fixed bubble size.
Parameters
----------
path
Location of hdf5 file from NBODY.
f
hdf5 file
Returns
-------
hdf_index
The index in hdf5 file corresponding t... | 04b155ff4254721399f3e3150914c63a0f055f87 | 3,626,341 |
def save_perm_score(perm_scores, fn, output_folder):
"""
Save the permutation scores to a NumPy array file.
"""
fn = fn + '.npy'
output_path = join(output_folder, fn)
np.save(output_path, perm_scores)
return output_path | 2b28ece5749212d8856dfd3dc6d48a27a5731c83 | 3,626,342 |
def htmlencode(text):
"""Use HTML entities to encode special characters in the given text."""
text = text.replace('&', '&')
text = text.replace('"', '"')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text | a8d26fc21966c64b0daf1f9cbbdbcd2d2a7b9cf2 | 3,626,343 |
def append_entries(
log: list[Entry],
*,
previous_index: int,
previous_term: int,
entries: list[Entry],
) -> bool:
"""Append entries to the log.
This is both idempotent and destructive. If an entry is identical to
the entry that already exists at the index, it, along with any
subseq... | 2db32100fd67bf1b8de93994409bdf571868b7e2 | 3,626,344 |
def request(file_path):
"""Request file by the file path."""
try:
data = read_file(file_path)
mime_type = get_mime_type(file_path)
return data, mime_type, STATUS_CODES['success']
except Exception:
return server_error() | c18be5632ee7eb58c009a1e1ad74faff9bd243eb | 3,626,345 |
def v_include_complex_type(ctx, stmt):
"""Loads complex-types from a submodule.
Checks for complex-type collisions in a submodule.
"""
includes = stmt.search('include')
def get_module(i):
# check if the module to import is already added
modulename = i.arg
r = i.search_one('r... | 585cf6b98f9f8f3873705647288f8ca258506e6d | 3,626,346 |
def fix_roots(poles, fix_roots="incr", fix_mode="reflect"):
"""
Fix (stabilize) LP roots.
Parameters
----------
poles : ndarray
Array of LP roots (poles).
fix_roots : {'incr', 'decr'}
Type of roots which to consider bad and to stabilize. Either those
with increasing sig... | 52a11f4ba991530d077332c11143b39813bac596 | 3,626,347 |
from typing import Iterable
from typing import Dict
def parse_keyword_args(keywords: Iterable[str], args: str) -> (Dict[str, str], str):
"""
:param keywords: Valid keywords
:param args: String argument to parse
:return: (Dict of kwargs, remaining part of args)
"""
kwargs = {}
matches = _KW... | f8e4ecf3856ace099652b8bd04d62d05e16344f6 | 3,626,348 |
def is_lambda(fun):
"""
Check whether the given function is a lambda function.
>>> def not_lambda_fun():
... return None
...
>>> lambda_fun = lambda: None
...
>>> print(
... is_lambda(not_lambda_fun),
... is_lambda(lambda_fun)
... | 7ba75e47fee5f0eac5665ae790c4245a3118e183 | 3,626,349 |
import struct
def _read_gaussian_container(g_file):
"""Read a gaussian container in a binary format"""
# gaussian container
chk = g_file.read(8) # read string of 8bytes
if chk != "GAUSSVEC":
raise Exception("Error: the gaussian container" +
" is not of GAUSSVEC kind %... | 271a2d50d203d2925cd0b4aa4895314f904a3cbe | 3,626,350 |
def voigt_kernel(k, beta,gammaL):
"""Fourier Kernel of the Voigt Profile
Args:
k: conjugated of wavenumber
beta: Gaussian standard deviation
gammaL: Lorentian Half Width
Returns:
kernel (N_x,N_beta,N_gammaL)
Note:
Conversions to the (full) width... | 01e21bcd77f6db8ceb95d3b0425db2f39ad2acf3 | 3,626,351 |
def BOPTools_AlgoTools_GetEdgeOff(*args):
"""
* Returns True if the face theFace contains the edge theEdge but with opposite orientation. If the method returns True theEdgeOff is the edge founded
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theFace:
:type theFace: TopoDS_Face &
:param ... | c121ee4b66cf55ec1eb5d3773a025bcab39e27cb | 3,626,352 |
def get_voc( df, fit_window = 20 ):
"""
Get open circuit voltage.
:param df: A Pandas DataFrame containing JV sweeps, indexed by voltage.
:param fit_window: Window size to extrapolate if needed. [Default: 20]
:returns: A Pandas Series of open circuit voltages.
"""
df = df.sort_index()
... | 9640f83e807e0bba386a8ac3b270908e1959dfbc | 3,626,354 |
def calc_Rrup( Rx, Ztor, W, dip, azimuth, Rjb=None ):
"""
Compute the closest distance from site the the surface the fault
"""
if Ztor < 0:
print 'Ztor should be larger than 0'
raise ValueError
if W <= 0:
print 'Fault width should be larger than 0'
raise ValueError
if dip<=0 or dip > 90:
pr... | 2be536211aec6ed5f42406a04a7cf717d53fd931 | 3,626,355 |
def not_equal(a, b):
#pdb.set_trace()
""" return 1 if True, else 0 """
name = "not_equal"
a2, b2 = COPY(a), COPY(b)
c = saferound(a2, sigfigs) != saferound(b2, sigfigs)
get_hashes(c, a, b)
return(bound(c)) | a58ac00d97cdf7777f731f6f42455992ff8f3031 | 3,626,358 |
def confidence_interval(A, axis=None, alpha=.05, metric=np.mean,
numResamples=1000, interpolate=True):
"""
Bootstrap confidence interval.
Return the bootstrap confidence interval of an array or along an axis
ignoring NaNs and masked elements.
Parameters
----------
A... | 83b4eddc7bcc5ede30ef5dedce7fd81ac83b5a79 | 3,626,359 |
def read_audio_record(audio_record, output_to_file=None):
"""
#https://stackoverflow.com/questions/42703849/audioset-and-tensorflow-understanding
"""
vid_ids = []
labels = []
start_time_seconds = [] # in secondes
end_time_seconds = []
feat_audio = []
count = 0
with tf.device("/c... | 0383904dacdb776187f36a6b3c0af2ef3d3413f1 | 3,626,360 |
import json
import logging
def _remove_source_ip_ubt_v1(vrf_name, **kwargs):
"""
Perform GET and PUT calls to remove the source IP address for UBT on a VRF.
:param vrf_name: Alphanumeric name of VRF
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: ... | 9200a878988ce45f2d56266af6dd94cc4ed0f84d | 3,626,361 |
from typing import Dict
from typing import Any
from typing import List
import copy
def move_to_location(
object_instance: Dict[str, Any],
location: Dict[str, Any],
object_bounds: List[Dict[str, float]],
previous_object: Dict[str, Any]
) -> Dict[str, Any]:
"""Move the given object to a new location... | 079f7367d04d732a93aa2ac18a1255a061e00243 | 3,626,364 |
from matlab import engine
from typing import Any
def start_engine() -> Any:
""" """
global MATLAB_ENGINE
if not MATLAB_ENGINE:
print("Starting Matlab")
if True:
MATLAB_ENGINE = engine.start_matlab()
else:
future = engine.start_matlab(background=True)
... | fb191a41a01e0731fe7ae2c397b30e2958b84ced | 3,626,366 |
def format_seq(seq,stop=False):
"""
Takes an amino acid sequence, returns a list of integers in the codex of the babbler.
Here, the default is to strip the stop symbol (stop=False) which would have
otherwise been added to the end of the sequence. If you are trying to generate
a rep, do not include t... | 3c553dcac989fe2bf649633842bb563a13325bbf | 3,626,367 |
def parser_maximum_bitrate_Descriptor(data,i,length,end):
"""\
parser_maximum_bitrate_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "maximum_bitrate", "contents" : unparsed_descriptor_contents }
... | a53ff1ce3f0c93aa37e78bd0f9af2a3b47f6df99 | 3,626,368 |
import warnings
def VACFtraj(traj, dt=1):
"""
Calculate/give velocity autocorrelation for a single trajectory.
The result of the calculation is stored in ``traj.meta['VACF']`` and
``traj.meta['VACFmeta']``. This function checks whether the corresponding
fields exist and if not calculates them. It... | f59689b6238f5a7ae6743b71d9f91f5a73b85621 | 3,626,369 |
import json
def status(request):
"""
Returns a simple HttpResponse
"""
response = "<h1>%s</h1>" % getattr(settings, 'PING_DEFAULT_RESPONSE', PING_DEFAULT_RESPONSE)
content_type = getattr(settings, 'PING_DEFAULT_CONTENT_TYPE', PING_DEFAULT_CONTENT_TYPE)
if request.GET.get('checks') == 'true':... | f35f4aaa0fc1fba11a35fcec69ca436022d5c807 | 3,626,370 |
def get_healthcare_py_str():
"""
Get the code str for the adult_easy pipeline
"""
with open(HEALTHCARE_PY) as file:
test_code = file.read()
return test_code | 16b5c5c7287a8e080367a2772b9d3f9b66670d99 | 3,626,371 |
def create_cluster_metadata(topic_partitions):
"""Create ClusterMetada out of a dict structure for easier mocking.
topic_partitions should be in the format of {'topic1': [partition1, partition2], 'topic2': [partition3]...}
"""
cluster_metadata = ClusterMetadata()
topics_dict = {}
for topic in t... | c4ea6fc43c23c0dc7a77a18c2d6c5921758873f4 | 3,626,372 |
async def custom_request_validation_exception_handler(
request: Request,
exception: RequestValidationError
) -> JSONResponse:
"""Custom handling of fastapi request validation errors"""
log.error(f'{request.method} {request.url.path} : {str(exception)}')
if route_has_tag(request, constants.V1_TAG):
... | 98113a251134f77c03703be3448ddcc8fddbf57c | 3,626,373 |
def complete_line(base_coord, targ_coord, word_len, row_length, column_length):
"""Return list of tuple coordinates which correspond to a straight line inside the matrix.
Args:
base_coord (tuple): A coordinate tuple of the starting position.
targ_coord (tuple): A coordinate tuple of the target ... | 127537093b47b686e284eb3c9585d891863a2af5 | 3,626,374 |
def decompose(data_with_size: bytes) -> list:
"""
Deserialize a byte string into a list of byte strings.
"""
(buf, size) = extract_size(data_with_size)
if size < 0:
raise BadFile()
xs = []
for i in range(size):
(buf2, chunk_size) = extract_size(buf)
chunk = buf2[:chu... | 179cc1d7d1c077c7bd04fe57c53c538218c61a95 | 3,626,375 |
def find_stars (ra_cat, dec_cat, ra, dec, dist, search='box',
sort=False):
"""find entries in [ra_cat] and [dec_cat] within [dist] of [ra] and
[dec]; all in degrees
"""
# make a big cut in arrays ra_cat and dec_cat to speed up
index_cut = np.nonzero(np.abs(dec_cat-dec)<=dist... | 4a55d69d06be270f7da257f5fa214292d5773445 | 3,626,377 |
import requests
from bs4 import BeautifulSoup
def pgatour_statistic(url):
"""Get data on give pgatour statistic
Args:
url (str) : pgatour statistic url
Returns:
data of pgatour statistic
"""
with requests.Session() as session:
page = session.get(url)
... | 09a878a3f76999c9efd1963f52aadd52ef68c14e | 3,626,378 |
from typing import Iterable
def open_uniform_bspline(control_points: Iterable['Vertex'], order: int = 4,
weights: Iterable[float] = None) -> BSpline:
""" Creates an open uniform (periodic) `B-spline`_ curve (`open curve`_).
This is an unclamped curve, which means the curve passes non... | 4f73622a7fadfc158ee8ab1204fd21544cbbf430 | 3,626,380 |
import optparse
def parse_args():
"""
Parse command line options into variables
"""
parser = optparse.OptionParser(usage="Usage: %prog [options]")
parser.add_option("--film-urls",
type="string",
dest="urls",
help=("Film URLs to pick from, separated by commas")
)
... | e618915c8c6a6211e208b3bca662ad951c46a507 | 3,626,381 |
import re
def get_services(path_obj):
"""
Return a list of GATT Service UUIDs for a given Bluetooth device D-Bus path
:param path_obj: D-Bus path for remote Bluetooth device
:return: List of GATT Service UUIDs
"""
found_services = []
valid_structure = re.match(r'/org/bluez/hci\d+/dev(_([0... | 91d4ba979fd40522d18b46873e70cda4fc0e4628 | 3,626,382 |
def get_env_generating_function(environment_config: EnvironmentConfig) -> t.Callable:
"""Returns a function that generates a Doom environment wrapper."""
return lambda: create_env(environment_config) | 37124d6a44053c69103e5437be6c9bbea3559b61 | 3,626,383 |
def normalize_error(error: str, error_types: set[str]) -> str:
"""Translate any "bad" error types to something more usable."""
error = app.config["OAUTH_FETCH_ERROR_TYPES"].get(error, error)
if error not in error_types:
return errors.SERVER_ERROR
else:
return error | aae5c5e9aceda765d8e26fa343ddc98468d6db07 | 3,626,384 |
def inf_get_af2(*args):
"""
inf_get_af2() -> uint32
"""
return _ida_ida.inf_get_af2(*args) | 09acc8ea8b8bb2a6f624799af8445f27ba96d5e7 | 3,626,386 |
def plural(items_or_count,
singular: str,
count_format='',
these: bool = False,
number: bool = True,
are: bool = False) -> str:
"""Returns the singular or plural form of a word based on a count."""
try:
count = len(items_or_count)
except TypeEr... | 01f397579b60538f25710566507973bdc6422874 | 3,626,387 |
def Jaccrad(str1, str2):
"""
S2a,S2b计算
:param str1:
:param str2:
:return:
"""
if (len(str1.split('=')) == 1)|(len(str2.split('=')) == 1):
return 0, 0
# elif (str1 == 'None=str;1') | (str2 == 'None=str;1'):
# return 0, 0
elif (len(str1.split(';')) == 1)|(len(str2.split... | ccecba56bc2f9fcab0f37ebc5abbbc2ac68f9b45 | 3,626,388 |
import sqlite3
def db_setup(db_name):
"""Database setup."""
cxn = sqlite3.connect(db_name, timeout=30.0)
cxn.execute('PRAGMA page_size = {}'.format(2 ** 16))
cxn.execute("PRAGMA journal_mode = WAL")
return cxn | 55092a98aed1e0a42ebf004a116913cfbecfb5f9 | 3,626,391 |
def _dstack_product(x, y):
"""Returns the cartesian product of the elements of x and y vectors.
Args:
x: 1d array
y: 1d array of the same dtype as x.
Returns:
a 2D array containing the elements of [x]x[y].
Example:
x = jnp.array([1, 2, 3])
y = jnp.array([4, 5]
_dstack_product(x,y)
... | f42525ab82f530e0be3446d6f868fc30a03b8671 | 3,626,392 |
from loopy.kernel.data import temp_var_scope
from loopy.kernel.tools import DomainChanger
from pymbolic.primitives import Subscript, Variable
from loopy.kernel.data import Assignment
def restore_and_save_temporaries(kernel):
"""
Add code that loads / spills the temporaries in the kernel which are
live acr... | 844edaa801c42e800fab6ce4f315537f7f5a1a12 | 3,626,393 |
def readMIG():
"""Reads the Mitutoyo profilometry gauges from HOST:PORT,
returning the values as a list of strings. Bad gauge(es) are
indicated by the string "MIG Error" instead of a value.
"""
# Open the network connection
try:
tn = Telnet(HOST, PORT)
except:
print('Telne... | 1f35735f6f0150a50cf1e9b3700be24a02edb7a4 | 3,626,395 |
def role_object_factory(role_name='role.test_role'):
"""Cook up a fake role."""
role = {
'nameI18n': role_name[:32],
'active': 1
}
return role | e79e7b22a83d9da721b074d32878eabeca4054cd | 3,626,396 |
def get_business_or_personal_relationship():
"""Saves as (B) or (P). This is the relationship type the user has to the contact"""
business_or_personal_relationship = input("Business or Personal | Enter Your Relationship to the Contact (enter B for business) or (enter P for personal), Then Press Enter: ")
i... | 0480dac7163c5a1f71209dff6a444254e6bba4b1 | 3,626,399 |
from typing import Any
from typing import Type
from typing import cast
def create(
name: str,
/,
**fields: Field[Any],
) -> Type[Structure]:
"""
Functional API for creating structure.
:param name: structure type name
:param fields: structure fields
"""
cls = cast(StructureMeta, ... | 1c543e86a45ae8758ac6923eaf75a48942707600 | 3,626,401 |
from typing import Optional
def from_pretty_midi(
midi: PrettyMIDI,
resolution: int = DEFAULT_RESOLUTION,
mode: str = "max",
algorithm: str = "normal",
collect_onsets_only: bool = False,
first_beat_time: Optional[float] = None,
) -> Multitrack:
"""Return a Multitrack object converted from ... | bdf0c1f1c85f5a2ca8f9818e050b64a51e87ddf5 | 3,626,402 |
def assign_role():
"""
This API assigns one role to the user in the request
"""
user_id = request.json.get('user_id', None)
role = request.json.get('role', None)
user = query_validated_user(user_id)
if user:
user.role = role
db.session.add(user)
db.session.commit()
... | 688e01369653115866c34fe8969f15410d066ddc | 3,626,403 |
def segment(image):
""" Segment the image -- return the scores.
:param image: An image with shape 3 x 360 x 480 (sized to match the net)
:return: The output scores (len(LABELS) x 512 x 512)
"""
assert image.shape == (3, 360, 480)
net().blobs['data'].data[...] = np.array([image])
results =... | ff93d246ae63fb7a273a24adc95e6e4666c0797e | 3,626,405 |
def get_reg_name(*args):
"""
get_reg_name(int reg, size_t width, char buf, int reghi=-1) -> ssize_t
get_reg_name(int reg, size_t width, char buf) -> ssize_t
"""
return _idaapi.get_reg_name(*args) | 21c0085f11efe7de93e89dc047165cd8235da184 | 3,626,406 |
def ast_for_factor(factor: 'Ast', ctx: 'ReferenceDict'):
"""
factor ::= [unaryOp] invExp [suffix];
"""
assert factor.name is UNameEnum.factor
unary_op: 'Tokenizer' = None
suffix: 'Tokenizer' = None
n = len(factor)
if n is 3:
unary_op, inv, suffix = factor
elif n is 2:
... | 1b25b144f72adea6e4e5fb6f2bb2c9ee9a69515f | 3,626,407 |
def spherical_to_cartesian_4d(thetas, r=1.0):
"""
Converts points on the hypersphere S^3 in R^4 given in
spherical coordinates to their cartesian value.
:param thetas: [N, 3]
thetas = [theta_1 | theta_2 | theta_3], with theta_i [N, 1]
0 <= theta_1 < 2 * pi and
0 <= theta_2 < pi
... | b8624b7c546ca61ab6b4aa17ab191aaa40331d4e | 3,626,408 |
def sheets_get_ranges(spreadsheet_id, sheet_ranges):
""" Returns a Value Ranges for the input ranges.
See Sheets API Documnetation for rangee syntax
Sample: ['Sheet1', 'Sheet2] returns all values on these sheets
"""
service = get_sheets_service()
response = service.spreadsheets().value... | 5586b3d6566d8106b5a154b82b550bade4b3a354 | 3,626,409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.