content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _sp_expm(qo):
"""
Sparse matrix exponential of a quantum operator.
Called by the Qobj expm method.
"""
A = qo.data.tocsc() # extract Qobj data (sparse matrix)
m_vals = np.array([3, 5, 7, 9, 13])
theta = np.array([0.01495585217958292, 0.2539398330063230,
0.950417899... | be890480357be3ff1abd005a111f215eaf2f466d | 60,123 |
def conv_adj_list(links):
"""
convert a bi-direction link list to a adj_list
:param links: list(int:src_dpid, int:dst_dpid, str:attr) bi-direction
"""
graph = dict()
for link in links:
src_node = link[0]
dst_node = link[1]
ava_bandwidth = float(link[2])
if not gr... | 08d771361fa4c1614771704398004a856fe4ce29 | 60,124 |
def home():
"""홈 페이지."""
return 'home' | fa5b419e66fbfa0193e9ff87b38697006fc06ae4 | 60,125 |
import pickle
def load_solution(filepath):
"""Load BlitzMLSolution from disk.
Parameters
----------
filepath : string
Path to saved solution.
Returns
-------
solution : BlitzMLSolution.
"""
with open(filepath) as f:
solution = pickle.load(f)
return solution | 66f2fab622baadbf0d2c8867711912e2a49099ff | 60,127 |
def arc(t, data, rho_min=0.8, Ntrends=None, denoise=arc_emd, Nkeep=10):
"""Identify systematic trends in the data.
Parameters
----------
t : 1D array-like
The independent data, generally time.
data : 2D array-like
The data (e.g. lightcurves). Should have shape NxM where there are
... | a30437e8cbedebeb2d22ebd95bce85c9e52e01be | 60,128 |
def fit(core_radius, gamma, x, y, x_real, y_real, u_data, v_data, u_advection, v_advection, i):
"""
Fitting of the Lamb-Oseen Vortex
:param core_radius: core radius of the vortex
:param gamma: circulation contained in the vortex
:param x: x position
:param y: y position
:param x_real: x po... | 2b5c62d25a7aad3f3af38f558a6bc4ba9540c0ae | 60,129 |
def mergeSort(array):
"""Apply merge sort to an array. Returns a sorted array."""
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
mergeSort(left)
mergeSort(right)
i = 0
j = 0
k = 0
while i < len(left) and j <... | 5f69d6697c92086adce36a054fbefaaea423c2ae | 60,131 |
def _request_get_required(*keys):
"""Verify existence of request data and return values"""
if request.method == 'POST':
obj = request.form
else:
obj = request.args
values = []
for k in keys:
v = obj.get(k)
if not v:
raise Exception('Expected "%s" parameter... | ec0665886760c60ae542f9b75a81cf52371fd5c2 | 60,132 |
import numpy as np
def haversine(radius, lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon... | 6c38f2657b31756a66d25d8b2d84c5e75fc2621e | 60,133 |
def create_hdf5_data_reader(
train_path, val_path, test_path, num_responses=4):
"""Create a data reader for CosmoFlow.
Args:
{train, val, test}_path (str): Path to the corresponding dataset.
num_responses (int): The number of parameters to predict.
"""
reader_args = [
{... | 5651df1e752474483db43880fd84ea3a15450799 | 60,135 |
def JS_divergence(p1, p2, weights, mode='normalized'):
"""Calculate JS divergence between two distributions
Parameters
----------
p1 : numpy array
The first distribution, 1D array
p2 : numpy array
The second distribution, 1D array
weights: numpy array
1D array of SEM we... | d37e1b0de5e67b5a9c9fdf666112d6a3400150fd | 60,136 |
def format_response(event):
"""Determine what response to provide based upon event data.
Args:
event: A dictionary with the event data.
"""
event_type = event['type']
text = ""
senderName = event['user']['displayName']
# Case 1: The bot was added to a room
if event_type == 'AD... | f253b3cc60351b4cac266fc34c92732f63519605 | 60,139 |
def local_includes(path):
"""Returns a list of copts that act like a `local_includes` attribute.
Args:
path: A `string` of the directory to add to local `includes`.
Returns:
A `list` of copts.
"""
repo_name = native.repository_name()[1:]
package_name = native.package_name()
... | 39e498e15bf78e6b738844c3601e6605a0d9b7d8 | 60,140 |
def imageurl(value): # Only one argument.
"""Converts a string into all lowercase"""
value.split(" ")
return value.lower() | dfc1243a4286d3c0b7370c8821ed2c08e8cb4328 | 60,141 |
import html
import unicodedata
import re
def preprocess_html(text_str, plain_text=True, remove_newlines=True, remove_tabs=True, remove_tables=False):
"""
Pre-process html string by cleaning anomalies and optionally removing newlines, tabs, and html tables
Args:
text_str (string):
... | 3b22defd1c1ba8ff47e8f0c0eee1cefa09a2e58d | 60,142 |
def load_ko_associations_by_id(id):
"""Retrieve a KO mutation by id"""
doc = es.get('aragwas', id, doc_type='ko_associations', _source=['overPermutation','overBonferroni','maf','mac','score', 'gene', 'study'], realtime=False)
if not doc['found']:
raise Exception('Associations with ID %s not found' %... | bd184d26565e3d4ceeae081bc623a9a1565128b5 | 60,143 |
def find_ports(port_range, num_ports = 2):
""" Find available ports in the given range
Args:
port_range: The range of possible ports to use.
num_ports: The number of ports that must be found and returned.
Returns:
An integer of the first available port or False if all ports are in ... | 3a6666b456714e4c30c9c7c05b498906c28192c8 | 60,144 |
import torch
def warp_affine3d(src, M, dsize, mode='bilinear', padding_mode='zeros', align_corners=True):
"""
Applies a projective transformation a to 3d tensor.
"""
assert len(src.shape) == 5, src.shape
assert len(M.shape) == 3 and M.shape[-2:] == (3, 4), M.shape
assert len(dsize) == 3, d... | ace8ac2ff73accb4746dce0902f4076974c0c61b | 60,145 |
def trace(layer, inputs, feed_names=None, fetch_names=None):
"""
Trace dygraph network into a :code:`Program`. The returned :code:`Program`
can be run in static graph mode. This method would simply record all
operators in the network with :code:`inputs` . Users should guarantee that
the traced dygra... | 56957276b239beed6c7f5f2ba9b5d973fd2a8d28 | 60,146 |
import requests
def delete_sr(product_name, version_number):
"""
Delete Software Release
:param product_name:
:param version_number:
:return:
"""
req_data = {'product_name': str(product_name),
'version_number': str(version_number)}
url = SERVER_URL + '/srdelete'
re... | 70277aacd849540c540c4319f8bb5e8a949f855d | 60,147 |
def get_affiliation_name(graph, id):
"""Given database and id returns the display name"""
# Compute the paper count first
query = """
MATCH (a:Affiliations)
WHERE a.AffiliationId="%d"
return a.NormalizedName
""" % (
id,
)
df = graph.run(query).data()
df = df[0]['a.Norm... | 31638297b0267db837424b6dde7a4f546f0f3bc9 | 60,148 |
def plot_point_grid(model, coordinates=(-1, 1, .1), show_var=False):
"""
Description
----------
Function to plot a point grid for a two dimensional guassian process
regressor.
Parameters
----------
Model: gaussian process regression model object
A gaussian process regression (gp... | 3714adaa22e3c9c19bdc5ae8b7d5687c6838c3ef | 60,149 |
def one_to_one_self(model_class, fk):
"""
Declare a one-to-one relationship property. The property value would be an instance of the same
model.
You will need an associated foreign key to our own table.
*This utility method should only be used during class creation.*
:param model_class: class... | cd8fe9de785047eafae558e7e003298e33903204 | 60,150 |
def escape_html(message):
"""Escapes HTML characters in the given message."""
# Only the following characters need to be escaped
# (https://wiki.ubuntu.com/NotificationDevelopmentGuidelines).
message = message.replace('&', '&')
message = message.replace('<', '<')
message = message.replace... | 1fdbfa9b972ad6057e97967c61644b1c2e0994d0 | 60,151 |
def check_workspace_deleted(ws_id):
"""
Since the DELETE_WORKSPACE event can correspond to workspace undeletion as well as deletion,
we make sure that the workspace is deleted. This is done by making sure we get an excpetion
with the word 'delete' in the error body.
"""
try:
config()['ws... | 576e008b14bd2768b8cd2c9a404a072e8012f33a | 60,152 |
def loadVtkImageXML(name):
"""
load a VTK Image (.vti) into a vtkImageData (vtkStructuredPoints)
"""
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(name)
reader.Update()
return reader.GetOutput() | 5ee82e810f607ebf86bfeac13233a367e294f155 | 60,154 |
def food(f,num):
"""jfehfiehfioe i fihiohghi"""
tip=0.1*f
f=f+tip
return f/num | 848e43233a0a4cbc504971437fcc6f6df1667c4b | 60,155 |
import json
import re
def get_data_from_request(request):
"""
Because data might be in bad JSON form, might be in a string...
need to return an object, always
"""
try:
try:
if len(request.POST) > 0:
if '_content_type' in request.POST:
data = ... | 84b18fdbc79a1b8f0bc4781dadb3ea325b615327 | 60,156 |
from re import X
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
p = player(board)
# If empty board is provided as input, return corner.
if board == [[EMPTY]*3]*3:
return (0,0)
if p == X:
v = float("-inf")
selected_actio... | e862af9c8991e7796672857350fba983048e2806 | 60,157 |
def lyrics_language(update: Update, context: CallbackContext) -> int:
"""Sets lyrics language or displays options"""
language = context.user_data["bot_lang"]
text = context.bot_data["texts"][language]["lyrics_language"]
ud = context.user_data
chat_id = update.effective_chat.id
# command
if ... | a13d37d4de8d5cf2b9da6d955c50c1581ef9e129 | 60,158 |
def example_group_validate_enrolled_event() -> bool:
"""
Example validating against the enrollment group containing created in
enrollment_examples.py
Returns:
A boolean denoting whether or not the validation was successful
"""
audio_service: AudioService = helpers.get_audio_service()
... | c8df59db0b5e93885eba0bc8f401e9f37c342f4d | 60,160 |
from typing import Tuple
def handle_different_values(
dim: str, df_1: pd.DataFrame, df_2: pd.DataFrame
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Check if the dataframes have differing values in the `columns`
or the `index`, depending on the passed dimension. If so, output a
warning and list the respe... | 1632a14972ae6dcc66b421dcd7a971e41b2a3c70 | 60,161 |
def get_vertices_per_edge(mesh_v, mesh_f):
"""Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. If output of get_faces_per_edge is provided, this is used to
avoid call to get_vert_connectivity()"""
vc = sp.coo_matri... | 878eae6b3c7755dafdfc05a77784cbaf38f63e4f | 60,162 |
import re
def read_tsp(filename):
"""
Read a file in .tsp format into a pandas DataFrame
"""
with open(filename) as file:
cities = []
flag = False
for line in file.readlines()[0:-1]:
if line.startswith('EOF'):
break
if line.startswith('NO... | bf59fd6d755102b26dc0871cf44342a9fd84ad87 | 60,163 |
def qvsl(tt, pp):
"""saturation specific humidity over the liquid phase"""
return rd / rv * esatl(tt) / (pp - (1.0 - rd / rv) * esatl(tt)) | 1cb4b37a60f36204443db48bca464160df694766 | 60,164 |
import time
import logging
import math
def evaluate(mod, data_iter, epoch, log_interval):
""" Run evaluation on cpu. """
start = time.time()
total_L = 0.0
nbatch = 0
mod.set_states(value=0)
for batch in data_iter:
mod.forward(batch, is_train=False)
outputs = mod.get_outputs(mer... | ecfa801c403b4d5ac5703a08d6d0733d06134639 | 60,165 |
def crop_image(img, ymin, ymax, xmin, xmax):
"""Crop image with given size
Args:
img: image as numpy array
ymin: start cropping position along height in pixels
ymax: end cropping position along height in pixels
xmin: end cropping position along width in pixels
xmax: end ... | 929be89de22b5aa129f17459d53f34b335803813 | 60,166 |
def get_attributes_g(context, selector, only_visible=True):
"""
Return the attributes for the element that is obtained
from the selector as a dictionary object.
:param context:
:param selector:
:param only_visible:
:return:
"""
germanium = find_germanium_object(context)
if isins... | 65c39263ef811fca3a730032952b42901bae3943 | 60,167 |
def charge(payment_information: PaymentData, connection_params) -> GatewayResponse:
"""Performs Authorize and Capture transactions in a single run."""
auth_resp = authorize(payment_information, connection_params)
if not auth_resp.is_success:
return auth_resp
return capture(payment_information, c... | 0a259ae4601fcbc4c4b57d732c7f47afe8085b45 | 60,168 |
import tqdm
def get_feature_combination_df(
feature_combination: list,
df: pd.DataFrame,
index_levels: list,
column_value: str = "value",
verbose: bool = False
):
"""
For each feature combination in ``feature_combinations``, a DataFrame is created that holds the
cal... | 1b4b15ff7de2485324915e9530b1c6cac371efce | 60,169 |
def tags_to_oset(tags):
"""Parse a ``tags`` argument into an ordered set.
"""
if tags is None:
return oset()
elif isinstance(tags, (str, int)):
return oset((tags,))
elif isinstance(tags, oset):
return tags.copy()
else:
return oset(tags) | 30cf87915aa248677d89d9ed54a0ffcfa91b57bd | 60,170 |
def join_dtype_arrays(a1, a2, target_dtype):
"""
Initializes a new array with dtype target_dtype, and copies matching fields from a1 and a2 to the new array.
Args:
a1:
a2:
target_dtype:
Returns:
"""
new_ar = np.zeros(shape=(), dtype=target_dtype)
fields1 = a1 if is... | 002381f066fc6f50db03fd2afcef371e49863890 | 60,171 |
import textwrap
def prettyprint(annots, outlines, outfile, do_group, sections, wrapcol):
"""
Pretty-print the extracted annotations according to the output options.
annots List of extracted annotations, in the order they appear
outlines List of outlines
outfile Output file handle to print to
... | db61c5434c390f058349bc01b4b7f48cce15c0f5 | 60,172 |
def create_mesh(verts, faces, name='new-mesh'):
"""Creates a mesh from vertices and faces.
Args:
verts (array_like): Local coordinates of the vertices, of shape
N-by-3.
faces (list(tuple)): Faces specified by ordered vertex indices.
name (str, optional): Mesh name.
Retu... | 1dc2124d436288745a62a98b97dc8ef71e5984ae | 60,173 |
import torch
def so3_rotation_angle(R, eps: float = 1e-4):
"""
Calculates angles (in radians) of a batch of rotation matrices `R` with
:math: `\\phi = \text{acos}\frac{\text{Trace}(R)-1}{2}`. The trace of the
input matrices is checked to be in the valid range [-1-`eps`,3+`eps`].
The `eps` argument... | 2786c3cd0173b3b894427d2402aef3ebf7471b4d | 60,174 |
def eq_lvar(x, y):
"""Perform an equality check that considers all logic variables equal."""
return meta_diff(x, y, ne_fn=lvar_ignore_ne) is None | adfd0b18335e5b8f57f490c63eb738e6e83f9420 | 60,175 |
import bisect
def binary_search(elements, value):
"""Returns the index of the element closest to value.
Args:
elements (List): A sorted list.
"""
if not elements:
return -1
closest_index = bisect.bisect_left(elements, value, 0, len(elements) - 1)
element = elements[closest_ind... | 0463f69c1edc627b3b67ea0cbd646e560734703c | 60,176 |
def mv2musig(m, v):
"""
Convert mean and variance of log-normal distribution into mean and stdev of underlying normal distribution
Parameters
----------
m: float
Mean of log-normal distribution.
v: float
Variance of log-normal distribution.
Returns
-------
mu: float
... | efd77306741fd1e8b4294402d1fdb79c4806ee5c | 60,177 |
def smallest_prime_factor(n):
"""
:param n:
:return: the smallest factor of n, which is in the range [2, n]. The result is always prime.
"""
assert n >= 2
for i in range(2, eulerlib.sqrt(n) + 1):
if n % i == 0:
return i
return n | e56d1d26f3de6e92e2f2182c50be20ce52c809fe | 60,178 |
def cutoff_wavenumber(a, b=None, m=1, n=0):
"""Calculate cutoff wavenumber of TEmn or TMmn waveguide mode.
Args:
a: broad dimension of waveguide, in units [m]
b: narrow dimension of waveguide, in units [m]
m: mode number m
n: mode number n
Returns:
float: cutoff wav... | 49b45c9c46a37a021995c0e65aaa89aaf1d830d4 | 60,179 |
def df_empty(columns, dtypes, index=None):
"""Creates an empty DataFrame with initial column names and types."""
assert len(columns)==len(dtypes)
df = pd.DataFrame(index=index)
for c, d in zip(columns, dtypes):
df[c] = pd.Series(dtype=d)
return df | 6807aeff2b8f2195ad661779a880d03ce85becc3 | 60,180 |
def csv2pandas(data_info):
"""
Usage example:
data_dict = {
'skinny': {
'path': '/home/sebastian/Documents/PhD/data/skinnydip/skinnyDipData_8.csv',
'read_csv_kwargs': {},
'columns2keep': ['V2', 'V3', 'V4'],
'rename_columns': {'V2': 'f1', 'V3': 'f2', 'V... | 35e6f3588fc1f19bb6d288f8c9f1e8ff1b6e9eda | 60,181 |
from typing import List
def training_size_curve(model: ModelType, x_train: np.ndarray,
y_train: np.ndarray, x_val: np.ndarray,
y_val: np.ndarray, sizes: List[float],
title: str) -> go.Figure:
"""Produces a training curve with respect to train... | e6cab20822241e96e044d8d4d5cd27a8c8f9b7e0 | 60,182 |
def gs_filter(img, sigma):
""" Step 1: Gaussian filter
Args:
img: Numpy ndarray of image
sigma: Smoothing parameter
Returns:
Numpy ndarray of smoothed image
"""
if type(img) != np.ndarray:
raise TypeError('input image must be of type ndarray')
else:
retu... | e44063895a22b4ee9a1e759126a166ce054b7b63 | 60,183 |
def make_keys_into_plays(lookup_table: dict) -> dict:
"""Returns a dict where all keys are Plays."""
new_table = lookup_table.copy()
if any(not isinstance(key, Plays) for key in new_table):
new_table = {Plays(*key): value for key, value in new_table.items()}
return new_table | 82e70a756312b7884a50447538d16315a147d837 | 60,184 |
def noto_fonts(default=''):
"""Local path to noto-font git repo"""
return values.get('noto_fonts', default) | 78c53cc18994f95d7633024c202935f1929202ed | 60,186 |
def to_utf8(string):
"""
Args:
string: A string que vai ser filtrada
Returns:
str: A string inicial apenas com caracteres utf-8
"""
return ''.join(filter(lambda x: str(x) in string_lib.printable, list(str(string)))) | abf0e914e13b2598a6225f67542fd6fb48b94b92 | 60,187 |
def rect_overlap(r1, r2):
"""Return the area of the intersection of two rectangles.
Args:
r1: an object with attributes left, top, width, height
r2: an object with attributes left, top, width, height
Returns:
float
"""
left = float(max(r1.left, r2.left))
right = float(mi... | cba6c109fe7e9cdc3532781ebb9abbae7088754d | 60,188 |
import math
def rrange(series_key, start, stop):
"""Generate Renard values in a range inclusive of the start and stop values.
Args:
series_key: The RenardSeriesKey to use.
start: The beginning of the range. The yielded values may include this value.
stop: The end of the range. The yie... | 50f6609a933deb6523588fd12dd69d9492f82e77 | 60,189 |
from typing import Dict
from typing import Set
import itertools
def get_map_of_unbound_references(
comp: building_blocks.ComputationBuildingBlock
) -> Dict[building_blocks.ComputationBuildingBlock, Set[str]]:
"""Gets a Python `dict` of unbound references in `comp`, keyed by Python `id`.
Compuations that are ... | 861cd01f3c43d3de334582c350b5423bb3822106 | 60,191 |
def is_available():
"""Returns a boolean to indicate the availability of a OpenCL GPU.
This will initialize the driver if it hasn't been initialized.
"""
return driver.is_available | 793b83b8c69d10e2a548c41973111de75f9e44db | 60,192 |
def load_dset(dfile, R_cut=None, z_cut=None):
"""
Read saved .npz dataset, keeping only stars within specified cuts.
Parameters
----------
dfile : str
Path to .npz file containing dataset, e.g. files in /data directory.
R_cut : float, optional
Keep only stars within `R_cut` of 8... | d8786a83b871ce0fff017796b3546baea6254004 | 60,193 |
def test_for_numeric_line(
d: deque,
# func_deque: bool = False
) -> bool:
"""
Returns True if 'd' appears to be a calculation in
consisting entirely of numerals, operators, and functions.
In other words, the calculation has no "variables" in it,
whatsoever.
"""
bool_acc = []
fun... | 6d27968ac3f74d16e2be7bd2cba2215edc074f30 | 60,194 |
def attack(length):
"""
This function start with an empty string and starts to fill it (until its length it is equal
to the param length) with the characters guessed by the guess_letter function.
:param length: It is the guessed length of the password, generated by the function guess_length.
:return... | dfae0000b0f313bbf91a731732b4b4dc06382ca3 | 60,195 |
from typing import Tuple
import random
def deal_card() -> Tuple[dict, dict, dict, dict]:
"""
"""
card_string = _card_to_str(CARDS)
card_list = list(card_string)
random.shuffle(card_list)
return (
_str_to_card("".join(card_list[:17])),
_str_to_card("".join(card_list[17:3... | 35bc5c5f2d0ced5dbbe1fd14121d2d0b2feb7a7b | 60,196 |
import torch
def accuracy(gt_S, pred_S):
"""
Get the accuracy of the model.
Args:
gt_S : Ground truth.
pred_S : Prediction.
Returns:
Accuracy classification score.
"""
_, alp = torch.max(torch.from_numpy(pred_S), 1)
return accuracy_score(gt_S, np.asarray(alp)) | 1b2aec51118e8006ff6d6568bcc5ab013e7ef97a | 60,197 |
def upper_to_lower(upper, lower):
""" return new symm matrix with upper tri copied to lower tri"""
return upper, upper | ad178d0442e0242fd4818df90324e9022da96e94 | 60,199 |
def resolve(bears):
"""
Collects all dependencies of the given bears. This will also remove
duplicates.
:param bears: The given bears. Will not be modified.
:return: The new list of bears, sorted so that it can be executed
sequentially without dependency issues.
"""
r... | f71ddec693e533c64104f7d13ac15d8bca7f1a78 | 60,200 |
from datetime import datetime
def unshare_post(post_id):
"""Remove a share from a given post."""
username = get_jwt_identity()
login = Login.query.filter_by(username=username).first()
if login is None:
raise APIError(400, "User {username} does not exist on this server".format(username=userna... | c088d8806fa83ae522b149d988545d5743dbf641 | 60,201 |
from typing import Sequence
import copy
def one_individual_per_error_vector(population: Population) -> Sequence[Individual]:
"""Preselect one individual per distinct error vector.
Crucial for avoiding the worst case runtime of lexicase selection but
does not impact the behavior of which individual gets s... | 22f401f05fd07f6d8f06f972191079ea24a476d7 | 60,204 |
def delete_app_release(repo, tag_name, media_type, models_ref):
""" Terminate a Tag/media-type couple
It find the corresponding tag/manifest and remove from the manifestlistmanifest the manifest
1. it terminates the current tag (in all-cases)
2. if the new manifestlist is not empty, it creates a new tag for it
... | 08482ea7163a574fa8a8a71b6ab5f4d3188f38b5 | 60,206 |
import six
def ensure_str(value):
"""
Ensure value is string.
"""
if isinstance(value, six.string_types):
return value
else:
return six.text_type(value) | 524a9f46e97856894779492805dd4dc100bb79be | 60,207 |
from typing import Union
from typing import BinaryIO
def parse_binary_string_on_buffer(buffer: Union[BinaryIO, BytesIO]) -> str:
"""
Strings ends with \0.
We parse until we reach that.
"""
result = b''
tmp = buffer.read(1)
while unpack('<b', tmp)[0] != 0:
result = result + tmp
... | 870a476b3602a5bdf94669bdebe9ee1e3eecc9fa | 60,208 |
from typing import Any
def query_2(author: str, year: str, db: Graph = Depends(get_db)) -> Any:
"""Find the co-authors of an author (name, number of co-authorships) for a particular year.
"""
query = "MATCH (a1:Author{name: $name})-[r1:CONTRIBUTED]->(n{year: $year})<-[r2:CONTRIBUTED]-(a2:Author)" \
... | ea4c34469595c4ee93308fa1e66f7d12e98c7a8f | 60,209 |
def write_before_line(to_write):
"""To write ``to_write`` at the beginning of the line.
``write_before_line`` uses ``0`` from the command mode to move
the cursor to the beginning of the current line. ``to_write`` is
then written before the cursor's position using the ``i``
command.
Usage:
... | 029f35dc16de53bf3f65416836f864a676fbbbfd | 60,210 |
def multiply(x, y):
"""
This returns the result of a multiplation of the inputs
"""
some_global_var = 'this is actually a local variable...'
result = x* y
return result
if result == 777:
print("jackpot!") | 04b0b57bce75e5523151bdcc85d81743a8eba573 | 60,211 |
def sanitise_coords(rectlist, width, height):
"""Treat negative numbers as the outer bound."""
def sanitise(rect):
rect.x0 = max(rect.x0, 0)
rect.y0 = max(rect.y0, 0)
if rect.x1 < 0:
rect.x1 = width
if rect.y1 < 0:
rect.y1 = height
if rect.x0 > wid... | 3d9895cff7b0616af55a246ccbbc555ec9641e24 | 60,212 |
def word_similarity(word_list, text_list):
"""
Computes the similarity between word and text
word_list: a list containing all possible translations of a single word
text_list: a list of lists containing all possible translations for a set of words
"""
max_sim_wordnet = 0
max_sim_yago = 0... | 3bf4f954d2e49b685af0076b8a3b1f83f4219307 | 60,213 |
def humanize_duration(seconds):
"""Format specified time duration into human readable text.
Parameters
----------
seconds : int | float
Number of seconds, as the time duration.
Returns
-------
str
The formatted time duration.
"""
if seconds < 0:
seconds = -s... | 0c168dab1df75bb624e4e740c4467a1c66bf05f2 | 60,214 |
def Date(year, month, day):
"""Constuct an object holding a date value.
This function is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:rtype: :class:`datetime.date`
"""
return date(year, month, day) | 46a17af69d72b9ba24991e29db5be07bb5bae0f0 | 60,215 |
def show_iface(iface_name=None, is_verbose=False, use_html=False):
"""enable the given interface by calling ifup."""
theResult = str("""UNKNOWN""")
if is_verbose is True:
theResult = str(get_iface_status_raw(iface_name))
else:
try:
if use_html:
format_pattern = str("""{}{}{}{}""")
else:
format_pat... | c1838b6a04550433f38ee31a896e27ebf9d5d521 | 60,216 |
def create_harmonic_hparams(hparams_string=None, verbose=False):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = tf.contrib.training.HParams(
type=0,
layers=3,
blocks=2,
dilation_channels=130,
residual_channels=130,
skip_channels... | 55d07c4f2df65a3b18d342fa3ec623f23ab40e6e | 60,217 |
def get_fnames_from_meta_dict(wp_info):
"""
docstring
"""
fnames = []
meeting = wp_info['Meeting_type'] + wp_info['Meeting_number']
pnum = wp_info['Abbreviation'] + str(wp_info['Number']).zfill(3) # zero pad
if wp_info['Revision'] > 0: # a 'rev#' included in filename iff revisions
... | c529de7e7bd54f56dd627ccc82bdd5680c33b440 | 60,219 |
def is_title_case(line):
"""Determine if a line is title-case (i.e. the first letter of every
word is upper-case. More readable than the equivalent all([]) form."""
for word in line.split(u' '):
if len(word) > 0 and len(word) > 3 and word[0] != word[0].upper():
return False
return Tr... | e769d589d0f84030768c901a5b5b2285788bdc97 | 60,220 |
def setOpenTreeDict(tree):
"""
This function creates a list of myOpenTree objects
as well as the dict of list for all the childrens
"""
openTreeDict = {}
for node in transverseTree(tree):
if node.children != None:
openTreeDict[node.name] = [child.name for child in node.... | 8a6be1883fc67d29dff251c5223bbc858eb78d9a | 60,221 |
def page_list(parent=None):
"""
Generate and return list of help pages for being displayed.
"""
help_images_list = [
["Level 1", resource_filename("help1.png")],
["Level 2", resource_filename("help2.png")],
["Level 3", resource_filename("help3.png")],
["Level 4", resource... | 3491c6594ef591d0814902785c99395b3bc40be4 | 60,222 |
def _is_stack_frame(conscious: 'Conscious') -> bool:
"""
info: Checks if item on top of Stack is StackFrame.
:param conscious: Conscious
:return: bool
"""
return conscious[WORK_STACK].peak() is stack.StackFrame | b228cd3b5602e20f1f1301031d03064511746e59 | 60,223 |
def gen_base_class(schema: UxsdSchema) -> str:
"""Generate a C++ base class of a root element."""
out = ""
root = schema.root_element
class_name = utils.to_pascalcase(root.name)
out += "struct Default{pname}ContextTypes {{\n".format(pname=class_name)
out += "\n\t".join("using {}ReadContext = void *;".format(utils... | 9d383d975c3348a7a75ab08b4980a1560c0c90b7 | 60,225 |
def padded_cross_entropy(logits,
labels,
label_smoothing,
weights_fn=weights_nonzero,
reduce_sum=True):
"""Compute cross-entropy assuming 0s are padding.
Computes a loss numerator (the sum of losses), and loss denom... | fc859a75c7c817450324a0e6c65e1adce2043241 | 60,226 |
import torch
import tqdm
def train(model, train_loader, valid_loader, args):
"""Trainer function
"""
# Set device
assert args.cuda < 0 or torch.cuda.is_available()
device_tag = "cpu" if args.cuda == -1 else "cuda:%d"%args.cuda
device = torch.device(device_tag)
# Set model and label weigh... | 3db937ff6dc085dac5a866e41a3ae6929d71bc8e | 60,227 |
def hanging_node(
pred_tactics, predprob_tactics, pred_techniques, predprob_techniques, c, d
):
"""
Modify prediction of techniques depending on techniques and related tactics confidence score on a
threshold basis.
"""
predprob_techniques_corrected = pred_techniques
for i in range(len(pred_t... | 18b06fb4cccf518ac59923ae766d526edd4e642b | 60,229 |
def zero(x_i: np.ndarray, L: float = 2 * np.pi, gamma: float = 0.1) -> np.ndarray:
"""No interaction between particles"""
return np.zeros_like(x_i) | 59c995f48d2c2a665af90f6f66e0e9d177826172 | 60,230 |
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
"""Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
"""
_, block_index = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) = ... | cf120ee128326c409cae8c0a97da8108165ffaee | 60,231 |
import configparser
def parse_config(config_path):
"""
Parses the config present at config_path.
Parameters
----------
config_path : string
The path pointing to the location where the config file is stored.
Returns
-------
configparser.SectionProxy
Returns the DEFAULT... | 479abb217c26a48e67e83e8cff8fcd0dd76229bf | 60,232 |
def sinusoidal(params):
"""
returns lxml nodes that contain projection parameters for fgdc
Sinusoidal projection
longcm = Longitude of Central Meridian
feast = False Easting
fnorth - False Northing
Parameters
----------
params : dictionary
geospatial parameters returned... | 9d229e036b26ca8e5ede8a78ae64616d19f71d4c | 60,233 |
from numpy import array
def k_Wa92(wind_second_moment, temp_C):
"""
Calculates the gas transfer coeffcient for CO2 using the formulation
of Wanninkhof (1992)
Note:
This is an old parameterization and we recommend using updated
parameterisations that are calculated based on the wind pr... | a4d3a502c8aac16e45b09e359d43ca53a6810e22 | 60,234 |
def _get_x_y_from_training_validation(logger, training, validation, predictors, target):
"""Returns X & Y for training & validation data"""
if training is not None:
training_X, training_Y = _get_x_y_from_data(
logger, training, predictors, target
)
if validation is not None:
... | dae15a97fbaa57c3dbdaecbfe59918f90bd9682d | 60,235 |
def PI_alpha_allspace(gp, alpha, idx_to_explore, X_to_minimize,
X_to_explore, bounds = None, nrestart = 10, PI = True):
""" alpha-Probability of improvement for each value in X_explore (U)
"""
total_grid = np.empty([len(X_to_explore), len(X_to_minimize)])
for index, x_fix in enumer... | 0485871981362f134b1e2f61261511068ee66f45 | 60,236 |
from typing import Optional
from typing import Sequence
from typing import Tuple
import requests
def attempt_connect_test_nodes(
chain: SubstrateChain,
timeout: int = NODE_CONNECTION_TIMEOUT,
node_names: Optional[Sequence[NodeName]] = None,
) -> DictNodeNameNodeAttributes:
"""Attempt to co... | 731898d2f32628ffbf9938a73ce9b4012fd000b9 | 60,237 |
def load_config(config_dir):
"""Opens the config file, doesn't check for creds."""
config_path = config_module.find_config_file(config_dir)
config = config_module.load_from_file(config_path)
return config | b067fd7b0a030fccd00dc21dd793f55fd67f3f11 | 60,238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.