content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bspline_to_bezier(ctrl_points, degree, knot_vector=None):
"""Extraction of the Constituent Bezier Curves using Boehm's Algorithm.
This implementation only works for cubic B-Splines.
Derivation is based on the algorithm described in Sederberg's "Computer Aided
Geometric Design", on "Extracting Bezie... | 66,300 |
def find_experiment_export(app_id):
"""Attempt to find a zipped export of an experiment with the ID provided
and return its path. Returns None if not found.
Search order:
1. local "data" subdirectory
2. user S3 bucket
3. Dallinger S3 bucket
"""
# Check locally first
cwd... | 66,301 |
def save_predict_package(predict_config):
"""Save a zip file with stuff needed to make predictions.
Save a zip file containing model (model file), stats.json (output of
compute_raster_stats command), and predict-config.json
(predict command config file). This can be used by the predict_package
... | 66,302 |
def get_cmd_line_args():
"""
Parse the command line arguments and return a dict mapping
<argument name> -> <value>.
"""
parser = argparse.ArgumentParser(description=DOC)
dhelp = ("Path to directory where to download and convert the 1000 "
"Genomes phase3 reference panel.")
par... | 66,303 |
def is_private(prefix, base):
"""prefix, base -> true iff name prefix + "." + base is "private".
Prefix may be an empty string, and base does not contain a period.
Prefix is ignored (although functions you write conforming to this
protocol may make use of it).
Return true iff base begins with an (a... | 66,304 |
def probability_move(M, current_vertex):
"""get moving probabilities for current vertex"""
# get current vertex id
v_idx = ext.get_python_idx(current_vertex)
n = len(M[v_idx])
prob_move = []
my_vertices = []
for col in range(0, n):
prob_v = M[v_idx][col]
# if target can move... | 66,305 |
def SqrtISwapXEBOptions(*args, **kwargs):
"""Options for calibrating a sqrt(ISWAP) gate using XEB."""
return XEBPhasedFSimCharacterizationOptions(*args, **kwargs).with_defaults_from_gate(SQRT_ISWAP) | 66,306 |
def _set_location(hass, data, location_name):
"""Fire HA event to set location."""
device = _device_name(data)
async_dispatcher_send(
hass, TRACKER_UPDATE, device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), location_name, data)
return web.Response(
text="Setting location for ... | 66,307 |
def create_decision_per_leafs(tree):
"""
Create a decision path matrix for leaf nodes - relative to all nodes of
single tree
Argument:
---------
tree : sklearn style tree object (has attribute .tree_)
generated tree to create decision path matricies from
Returns:
--------
v_... | 66,308 |
def load_genre(fhandle: TextIO) -> str:
"""Load genre data from a file
Args:
path (str): path to metadata annotation file
Returns:
str: loaded genre data
"""
annotation = jams.load(fhandle)
return annotation.search(namespace="tag_open")[0]["data"][0].value | 66,309 |
def generate_input_files(kmesh, encut, functional, aexx, systype, ismear, sigma, sym, algo, prec, computer, ncore, kpar):
""" Generates input files for convergence tests
(encut is the cutoff used for all kmesh conv_tests)
(kmesh is the kpoints mesh used for all cutoff conv_tests)
"""
... | 66,310 |
def _find_resources(graph, types):
"""Build up cache of type=>[resource=>localname]]"""
resources=collections.defaultdict(dict)
for t in types:
resources[t]={}
for x in graph.subjects(RDF.type, t):
resources[t][x]=_quote(localname(x))
resources[RDFS.Class].update(types.co... | 66,311 |
def test_packages_are_ordered():
"""Packages of pyproject.toml files should be in order."""
packages = [p["include"] for p in pyproject_toml()["tool"]["poetry"]["packages"]]
assert packages == sorted(packages) | 66,312 |
def vocab_parallel_KLDivLoss(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon=1e-12):
"""Helper function for the cross entropy."""
return _VocabParallelKLDivLoss.apply(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon) | 66,313 |
def test_entangled_state():
"""Entangled state of dimension 2 will violate PPT criterion."""
rho = bell(2) * bell(2).conj().T
np.testing.assert_equal(is_ppt(rho), False) | 66,314 |
def get_email_list():
"""
Returns an array of files parsed into an actual array (as opposed to an object)
:return: array of strings
"""
email_file_list = []
pending_email_list = aws_list_files()
for email_file in pending_email_list:
email_file_list.append(email_file)
# Remove th... | 66,315 |
def mu_central(components, observation=None, method='centroid', zeropoint=27.0, pixel_scale=0.168, weight_order=0):
"""
Determine the central surface brightness, by calculating the average of 9 pixels around the centroid
Parameters
----------
components: a list of `scarlet.Component` or `scarlet.Co... | 66,316 |
def num_available_gpus() -> int:
"""Returns the number of available GPUs, 0 if not a gpu node"""
async def async_num_available_gpus() -> int:
num_gpus = 0
container: Optional[DockerContainer] = None
async with aiodocker.Docker() as docker:
spec_config = {
"Cm... | 66,317 |
def cli(text="", items=None, wraplen=80, header=None, border=None, hchar="/"):
"""
Provide a standardized look to the SeisFlows command line interface messages
The look we are after is something like:
$ seisflows cmd
=======================
HEADER
//////
... | 66,318 |
def resnext56_8x8d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrai... | 66,319 |
def _unit_fun(x):
"""unit function"""
return x | 66,320 |
def get_nose_runner(report_folder, parallel=True, process_timeout=600, process_restart=True,
xunit_report=False, exclude_integration=True, code_coverage=False):
"""Create a nose execution method"""
def _run_nose(name, working_dir):
import nose
import os.path
if not ... | 66,321 |
def get_roi_scores(img, d, params):
"""Return array of all scores for each possible ROI of given dimension."""
shape = [img.shape[i]-d[i]+1 for i in range(3)] + [len(params)]
scores = np.empty(shape, dtype=np.float32)
for z, y, x, i in np.ndindex(scores.shape):
roi = img[z:z+d[0], y:y+d[1], x:x+... | 66,322 |
def dump_grid(grid: Grid) -> str:
"""
Dump a grid to JSON
Args:
grid: The grid.
Returns:
A json string
"""
return json.dumps(_dump_grid_to_hayson(grid)) | 66,323 |
def abstract_connected_regions(sample_list, aspect='rim', show=False, batch_size_cpu=32, batch_size_gpu=64, outer=False):
"""
:param sample_list: each sample should be a 2d binary numpy array with one semantic, 0 indicate not this semantic
and 1 means positive. If a sample has many semantics, you should sli... | 66,324 |
def simple_collectd_alarm_generators(update_vals=None):
"""A function for returning Collectd alarm event generators.
Returns generators for a given number of Collectd alarms.
:param update_vals: preset values for ALL update events
:return: generators for alarms as specified
"""
test_entity_sp... | 66,325 |
def sample_distribution(
p: np.ndarray,
random: np.random.RandomState,
) -> int:
"""Samples an integer with probabilities given by p."""
return random.choice(np.arange(len(p)), p=p) | 66,326 |
def update_confusion_matrix_training_dash(n_clicks, value, n_intervals):
"""
Function that just calls the update_confusion_matrix_training function. This
function is decorated by the Dash Application decorator. Such an arrangement
is used as unit testing decorated functions is complex.
"""
fi... | 66,327 |
def _get_average_da(streams_da: dict) -> dict:
"""Calculate average data availability among all data streams"""
total_results = {}
for k, v in streams_da.items():
for i, j in v.items():
if i not in total_results:
total_results[i] = []
total_results[i].append(j... | 66,328 |
def preview_string(graved):
"""
Creates preview string of the given graved content.
Parameters
----------
graved : `None` or `list` of (`str`, ``Grave``) elements
Returns
------
content : `None` or `str`
"""
if graved is None:
return None
words = []
for element... | 66,329 |
def show(edge, style='indented'):
"""Displays a representation of the edge in the notebook.
Keyword arguments:
style -- render style ('indented', 'line')
(default: 'indented')
"""
edge = hedge(edge)
html = _edge2html_show(edge, style=style)[0]
display(HTML(html)) | 66,330 |
def _get_text_for_grounding(stmt, agent_text):
"""Get text context for Adeft disambiguation
If the INDRA database is available, attempts to get the fulltext from
which the statement was extracted. If the fulltext is not available, the
abstract is returned. If the indra database is not available, uses t... | 66,331 |
def get_pycon_speaker_first_names(soup=None):
"""Parse the PYCON_HTML using BeautifulSoup, extracting all
speakers (class "speaker"). Note that some items contain
multiple speakers so you need to extract them.
Return a list of first names
"""
if soup is None:
soup = _get_soup(PY... | 66,332 |
def read_trec_res_file(file_name):
"""
Assuming data is in trec format results file with 6 columns, 'Qid entropy cross_entropy Score
'"""
data_df = pd.read_csv(file_name, delim_whitespace=True, header=None, index_col=0,
names=['qid', 'Q0', 'docNo', 'docRank', 'docScore', 'ind']... | 66,333 |
def bboxes_iou(boxes1, boxes2):
"""
boxes: [xmin, ymin, xmax, ymax, score, class] format coordinates.
"""
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) *... | 66,334 |
def loss_fn(outputs, labels):
"""
Compute the binary cross entropy loss given outputs and labels.
Args:
outputs: (Tensor) dimension batch_size x 1 - output of the model
labels: (Tensor) dimension batch_size, where each element is a value in [0, 1]
Returns:
loss (Tensor): cross ... | 66,335 |
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found.
o(n) runtime, based off the length of the text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a st... | 66,336 |
def test_transform_column_with_dest(dataframe):
"""Test creating a new destination column."""
expected_df = dataframe.assign(a_log10=np.log10(dataframe["a"]))
df = dataframe.copy().transform_column(
"a", np.log10, dest_column_name="a_log10"
)
assert_frame_equal(df, expected_df) | 66,337 |
def enable_debugging_msgs(filename=None):
"""
Enable output of debugging messages.
If filename is None messages will be sent to stderr.
"""
logging.root.setLevel(logging.DEBUG)
if filename is not None:
# Remove other handlers
for h in logging.root.handlers:
logging.... | 66,338 |
def _candidate_to_package_info_artefact(candidate: InstallationCandidate) -> Dict[str, str]:
""" Provide artifact metadata """
loc = candidate.link
artefact = {
'filename': loc.filename,
'hash': '{}:{}'.format(loc.hash_name, loc.hash),
'url': loc.url,
}
return artefact | 66,339 |
def test_assert004_assert004_v2_xml(mode, save_output, output_format):
"""
Constraints at more than one level Imposes constraints at two levels
of the same tree; also tests that constraints at the inner level are
rooted at the node being validated.
"""
assert_bindings(
schema="saxonData/... | 66,340 |
def test_merge_user_and_local_config(optmanager, config_finder):
"""Verify merging of parsed user and local config files."""
optmanager.add_option('--exclude', parse_from_config=True,
comma_separated_list=True,
normalize_paths=True)
optmanager.add_option('... | 66,341 |
def main():
"""Get integers and add them together"""
args = get_args()
INT = args.INT
num = len(INT)
Total = 0
trk = num
numbers = ''
for trk in range(num):
try:
not type(int(INT[trk])) is int
except:
print ("usage: Only Integers Allo... | 66,342 |
def get_namespace_pkg_types(ns_pkg_name, preferred='egg', print_msg=True,
use_env=None):
"""Determine how namespace packages are installed.
Parameters:
ns_pkg_name (string): The name of the namespace package to inspect.
preferred='egg' (string): The preferred format.... | 66,343 |
def compute_boundary(cpumap, cpulist):
"""
I think the name is misleading...
"""
bound = np.searchsorted(cpumap, cpulist)
return np.concatenate([bound, [cpumap.size]]) | 66,344 |
def basename(fullname):
"""os.path.basename"""
return os.path.basename(fullname) | 66,345 |
def create_db():
"""Create database for tests."""
db.create_all()
user = User('test_1@example.com', 'password')
user2 = User('test_3@example.com', 'other_password')
db.session.add(user)
db.session.add(user2)
db.session.add(Invitation('test_4@example.com', 'invite_code'))
db.session.add(R... | 66,346 |
def _add_shade(shade, ax, **plt_kwargs):
"""Add vertical shading to a plot axis.
Parameters
----------
shade : list of float
Region of the plot to shade in.
ax : Axes, optional
Axis object upon which to plot.
plt_kwargs
Additional arguments to pass into the plot function... | 66,347 |
def _compute_element_mse(data_a, data_b):
"""Compute MSE (Mean Squared Error).
:param data_a: Data for element a
:param data_b: Data for element b
:returns: The MSE value
"""
return np.mean(np.square(np.subtract(data_a, data_b, dtype=np.double))) | 66,348 |
def sg(P):
""" Specific entropy [kJ / kg K]
of saturated vapor"""
return region4.sg(P) | 66,349 |
def example(request):
""" Returns a finished home page to the user """
return render(request, 'page_gen/example.html') | 66,350 |
def to_pdg(ddg: DataDependenceGraph) -> ProgramDependenceGraph:
"""
Convert the Data Dependence Graph into a Program Dependence Graph.
New graph will contain same nodes as in the original one so that
any changes made after converting in the original graph's statements will affect the converted one.
... | 66,351 |
def fonctionOk():
"""raise"""
raise OkException('hop') | 66,352 |
def initial_data_processor(Irwin_FP, pretraining=True, from_disk=True):
"""
"Simple" utility function to clean the Irwin fire data
"""
if from_disk:
file = gpd.GeoDataFrame(
pd.read_pickle(
"/home/connor/Desktop/MassCrop/OutputFolder/tabular/tabular_fixed_effects.p... | 66,353 |
def cached(method=None, name=None, ignore_args=False):
"""A decorator allowing for specifying the name of a cache, allowing it to be modified elsewhere."""
if ignore_args:
return _cached_ignore_args(method=method, name=name)
else:
return _cached(method=method, name=name) | 66,354 |
def example_audio_file(index=0):
""" Get path to an example audio file
Parameters
----------
index : int, default=0
Index of the audio file
Returns
-------
path : str
Path to the example audio file
"""
data_path = os.path.dirname(__file__)
data_path = os.path.a... | 66,355 |
def scan_dir(target: str, ports: List[int], wordlist: str,
extensions: str,
threads: int = 50,
status_codes: str = "200,204,301,302,307,401,403",
status_codes_blacklist: str = "",
skip_ssl: bool = False,
cookies: str = "",
wildca... | 66,356 |
def bias_reduced_delta(Y, Ygrid, X, m, num_resamples, conf_level, fy=None, xr=None):
"""Plischke et al. 2013 bias reduction technique (eqn 30)"""
d_hat = calc_delta(Y, Ygrid, X, m, fy=fy, xr=xr)
if num_resamples > 0:
d = np.zeros(num_resamples)
N = len(Y)
r = np.random.randint(N, s... | 66,357 |
def _CreateRecipe(messages, agent_rule, os_type, prev_recipes):
"""Create a recipe for one agent rule in guest policy.
Args:
messages: os config guest policy api messages.
agent_rule: ops agent policy agent rule.
os_type: ops agent policy os type.
prev_recipes: a list of original SoftwareRecipe.
... | 66,358 |
def fixture_extended():
"""Return a /forecast/extended/pollen/<ZIP> response."""
return {
"Type": "pollen",
"ForecastDate": "2018-06-12T00:00:00-04:00",
"Location": {
"ZIP": "80238",
"City": "DENVER",
"State": "CO",
"periods": [
... | 66,359 |
def is_sequencing(lane_info):
"""
Determine if we are just sequencing and not doing any follow-up analysis
"""
if lane_info['experiment_type'] in ('De Novo','Whole Genome'):
return True
else:
return False | 66,360 |
def chunks(values, chunk_size):
"""Yield successive n-sized chunks from l."""
for index in range(0, len(values), chunk_size):
yield values[index : index + chunk_size] | 66,361 |
def parula_map():
"""Generate a color map similar to Matlab's Parula for use in NeXpy.
The color map data are from the 'fake_parula' function provided by
Ander Biguri, "Perceptually uniform colormaps"
MATLAB Central File Exchange (2020).
"""
from matplotlib.colors import LinearSegmentedColormap... | 66,362 |
def frame_data_to_non_herm_hoff(fname, channel, start=None, stop=None, TDlen=0,
window_shape=0., verbose=True,deltaT=None):
"""
Function to read in data in the frame format
and convert it to a COMPLEX16FrequencySeries
h(f) = FFT[ h(t) ]
Create complex FD data that does not assume Hermitiani... | 66,363 |
def concat_data(years):
"""
Convert to long format, add 'Year' and concatenate into one DataFrame
"""
lookup = pd.read_csv("lookup.csv", index_col=0)
data = []
for year in years:
filename = lookup.loc["Filename", str(year)]
sheet_name = lookup.loc["Institutional", str(year)]
... | 66,364 |
def hidden_media_dialog(media_key):
"""Ask the user for permission, then create a folder with a single media entry"""
dialog = xbmcgui.Dialog()
if dialog.yesno(getstr(30013), getstr(30014)):
url = 'https://data.jw-api.org/mediator/v1/media-items/' + language + '/' + media_key
data = get_jso... | 66,365 |
def get_session_data(transaction, session_id):
""" Looks up (or creates) the session with the given session_id.
Creates a random session_id if none is provided. Increments
the number of views in this session. Updates are done in a
transaction to make sure no saved increments are overwritten.... | 66,366 |
def write_submission(config, targetid, yr1, mn1, yr2, mn2, edge, runmonthid, outdir, runid):
"""
Builds a command to run like this:
python tracking_qc.py -id 51514 -yr1 2004 -mn1 5 -yr2 2006 -mn2 1 -edge start_edge_case -runmonthid 198501-201412
and submits it to the scheduler to run. It will submit a m... | 66,367 |
def _perform_trotter_step(qubits: Sequence[cirq.Qid],
time: float,
order: int,
trotter_step: TrotterStep,
control_qubit: Optional[cirq.Qid]
) -> cirq.OP_TREE:
"""Perform a Trotter step."... | 66,368 |
def list_examples():
"""Return names of all the local examples"""
for __, __, file_names in os.walk(example_file()):
return [os.path.splitext(f)[0] for f in file_names] | 66,369 |
def default_executor(**kwargs):
"""
Initialize and return an executor object.
:param config: Settings passed in here will override those in `pywren_config`. Default None.
:param job_max_runtime: Max time per lambda. Default 200
:return `executor` object.
Usage
>>> import pywren
>>>... | 66,370 |
def test_wmd():
"""Is the wmd calculated correctly?"""
model_embedding = [{0: 1, 1: 1}]
real_embedding = [{1: 1}]
context = np.array([[1, 4], [5, 1]])
# calculate Euclidean distance matrix
distance_matrix = calc_euclidean(context)
# calc d for embeddings
vocab_len = len(context)
d_... | 66,371 |
def _split_punc(source):
"""Split leading or trailing punctuation."""
tokens = source.split(" ")
new_tokens = []
for token in tokens:
if all(char in string.punctuation for char in token):
new_tokens.append(token)
continue
leading_punc = None
for punc in string.punctuation:
if toke... | 66,372 |
def _ValidateDurationUs(arg_internal_name, arg_value):
"""Validates an argument which should have Duration value in microseconds."""
try:
if isinstance(arg_value, six.string_types):
return TIMEOUT_PARSER_US(arg_value)
elif isinstance(arg_value, int):
return TIMEOUT_PARSER_US(str(arg_value))
ex... | 66,373 |
def get_saved_cities(uid):
"""
Gets the weather information for all the locations listed in the Places
List of the user's database record.
Args:
uid (string) -- the user's key
Returns:
None if the user doesn't exist in the database.
List of weather information (see get_weather())
... | 66,374 |
async def ratio(ctx):
"""command for personalised profile picture, input a color (RGB or HEX) output a reply with the profile picture"""
await pefiBot.ratio(ctx) | 66,375 |
def shr2shc(omega_real):
"""
Convert from real to complex spherical harmonics.
(See https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form)
Parameters
----------
omega_real: ndarray(shape=(N**2,), dtype=float)
Returns
-------
omega_complex: ndarray(shape=(N**2,), dtype=complex... | 66,376 |
def get_cluster_name(tags):
"""
Get the cluster name from the list of specified tags
:param tags: tags
:type tags: [str]
:returns: cluster name
:rtype: str
"""
for tag in tags:
if tag.startswith("storm.cluster.name:"):
return tag.replace("storm.cluster.name:", "")
... | 66,377 |
async def send_message_to_user(sender_id, recipient_id, message):
"""Send message to specific user."""
async with get_pool().acquire() as connection:
await connection.execute('''
INSERT INTO messages (sender_id, recipient_id, message)
VALUES ($1, $2, $3)
''', sender_id, r... | 66,378 |
def fixture_two_chunk_plain_wav() -> BinaryIO:
"""Creates a fixture WAVE file with two distinct sections.
The audio is 100Hz mono. Each section 10 samples long. Samples in the first
alternate between +/-(1 << 5) and in the second between +/-(1 << 10).
Returns:
File-like object with the bytes of the fixtur... | 66,379 |
def convert_hash(fp, hash_func=md5_hash):
""" into metadata [byte-read][bytes] format.
Args:
fp: str filepath
hash_func: function for calculating hash of file
Returns:
tuple (int, hash)
int: byte length of the hash
"""
fn_hash = hash_func(fp)
return util.byte_l... | 66,380 |
def warning(*msgs):
"""Print the supplied msgs to stderr as a warning"""
print("WARNING: ", *msgs, file=sys.stderr) | 66,381 |
def kepffi(ffifile, kepid, ra, dec, aperfile, imin, imax, iscale, cmap, npix,
verbose=False, logfile='kepffi.log'):
"""
kepffi -- Display a portion of a Full Frame Image (FFI) and define custom
target apertures
Parameters
----------
ffifile : str
The name of a MAST standard f... | 66,382 |
def staircase(A, B, C, compute_T=False, form='c', invert=False,
block_indices=False):
"""
Given a state model data A, B, C, Returns the so-called staircase form
State realization to assess the controllability/observability properties.
If observer-form is requested, internally the system i... | 66,383 |
def adjacency_dict(graph):
"""
Returns the adjacency list representation
of the graph.
"""
adj = {node: [] for node in graph.nodes}
for edge in graph.edges:
node1, node2 = edge[0], edge[1]
adj[node1].append(node2)
if not graph.is_directed:
adj[node2].append(no... | 66,384 |
def _detailed_parse_choice(choice):
"""Return Selected Choice's Full Name string as per its codename. Choices are based as per our server.
:param choice: str
The code name of the choice
:return: str
Return Selected Choice's Full Name string as per its codename
"""
... | 66,385 |
def np_exponential_moving_average(source: np.ndarray, window_size: int):
"""
Compute an exponential moving average from a source list.
Arguments:
source: The source list of data from which to compute the moving average.
window_size: The size of the moving average to compute.
Ret... | 66,386 |
async def migrate_files(db):
"""
Make all files unreserved. This is only called when the server first starts.
:param db:
"""
logger.info(" • files")
await db.files.update_many({}, {
"$set": {
"reserved": False
}
}, silent=True) | 66,387 |
def _subgraph_isomorphism_matcher(digraph, nxpattern, node_pred, edge_pred):
""" Match based on the VF2 algorithm for general SI. """
graph_matcher = iso.DiGraphMatcher(digraph,
nxpattern,
node_match=node_pred,
... | 66,388 |
def get_body(content_dict):
"""
Get the content item body or caption, whatever it's called
"""
content_item = find_content_item(content_dict)
if content_item.get('body', False):
body = content_item['body'] or ''
elif content_item.get('caption', False):
body = content_item['capti... | 66,389 |
def assert_same(actual, expected):
"""Assert actual payload items refers to expected entities."""
actual_ids = {item["id"] for item in actual}
expected_ids = {entity.id for entity in expected}
assert actual_ids == expected_ids
assert len(actual) == len(expected) | 66,390 |
def compute_mass_list(dialog_idx, sen_idx):
"""
Most confusing step...
dialog_idx = [41, 81, 134, ...]
means the first dialogue of the subtitle is plain_text[0:41]
the second dialogue of the subtitle is plain_text[41:81]
the third dialogue of the subtitle is plain_text[81:134]
... | 66,391 |
def svn_node_kind_from_word(*args):
"""svn_node_kind_from_word(char word) -> svn_node_kind_t"""
return _core.svn_node_kind_from_word(*args) | 66,392 |
def rm_files(fldr: os.PathLike, filters_list: List[str], ext_list: List[str]):
"""Remove all files with specific filetype(s) from directory.
Parameters
----------
fldr: Directory from which to remove files
ext_list: List of file types to remove files
filters_list: List of fil... | 66,393 |
def rotate(th):
"""Return the matrix to rotate a 2-D point about the origin by ``angle``.
The angle is measured in radians. To Point a point about a point other
then the origin, translate the Point, do the rotation, and
translate it back:
>>> from sympy.geometry.entity import rotate, translate
... | 66,394 |
def get_table_unique_keys(table):
"""Get columns that correspond to jointly unique keys"""
# Read rows and append column name and data type to main container
template_path = os.path.join(os.environ['MYSQL_TABLE_TEMPLATES_DIR'], f'{table}.csv')
with open(template_path, newline='') as f:
templat... | 66,395 |
def autocor(y):
"""Autocorrelation of array y""" #Formula from: https://www.itl.nist.gov/div898/handbook/eda/section3/eda35c.htm
autocorarr = []
counter = 0
denom = sumdenomeq(y)
for i in range (len(y)-1):
autocorarr.append((sumnomeq(y,i)/denom))
counter += 1
print(f"Progress... | 66,396 |
def run(command: str, timeout: int = 1) -> RunResult:
"""Run the command and record the result.
:param str command:
:param int timeout: # timeout
:returns: result of the run
:rtype: tuple(int, str, str, str)
"""
cmd = shlex.split(command)
try:
output = subprocess.run( # nosec
... | 66,397 |
def get_jenkins_auth_handler(jenkinsuser, jenkinspass, jenkinsurl):
"""
Get a basic authentification handler for jenkins
:param jenkinsuser: jenkins username, str
:param jenkinspass: jenkins password, str
:param jenkinsurl: jenkins base url, str
:return: a list of handlers
"""
for param ... | 66,398 |
def edit(context, revision='current', directory='migrations'):
"""Upgrade to a later version"""
if alembic_version >= (0, 8, 0):
config = _get_config(directory)
command.edit(config, revision)
else:
raise RuntimeError('Alembic 0.8.0 or greater is required') | 66,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.