content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_cases_by_project_exc_2(client):
""" Verify calling ``client.cases(Project, 'asdf')`` when the project
is a suite_mode of 2 raises an exception
"""
PROJECT_ID = 15
PROJECT_DICT = {'id': PROJECT_ID, 'suite_mode': 2}
client.api.project_by_id.return_value = PROJECT_DICT
client.api.... | 5,296,600 |
def _default_function(l, default, i):
"""
EXAMPLES::
sage: from sage.combinat.integer_vector import _default_function
sage: import functools
sage: f = functools.partial(_default_function, [1,2,3], 99)
sage: f(-1)
99
sage: f(0)
1
sage: f(1)
... | 5,296,601 |
def parse_id_token(token: str) -> GoogleUserInfo:
"""Parse the base64 encoded id token."""
parts = token.split(".")
if len(parts) != 3:
raise RuntimeError("Received Invalid ID Token")
payload = parts[1]
padded = payload + ("=" * (4 - len(payload) % 4))
decoded = base64.b64decode(padded)... | 5,296,602 |
def writeCommands(commandsObject, fileName):
""" Outputs the junit commands to a file
Parameters
----------
commandsObject : list of str
Description of parameter `commandsObject`.
fileName : str
The file to write the commands to
"""
with open(fileName, "w") as f:
f.... | 5,296,603 |
def _parse_apple(data):
"""Parse an AppleSingle or AppleDouble file."""
header = _APPLE_HEADER.from_bytes(data)
if header.magic == _APPLESINGLE_MAGIC:
container = 'AppleSingle'
elif header.magic == _APPLEDOUBLE_MAGIC:
container = 'AppleDouble'
else:
raise ValueError('Not an A... | 5,296,604 |
def write_mol_to_fingerprint_file(
mol: oechem.OEMol,
properties: [danceprops.DanceProperties],
select_output_dir: str,
select_bin_size: float,
wiberg_precision: float,
):
"""Writes a molecule to its appropriate SMILES fingerprint file"""
# Some of the molecules coming ... | 5,296,605 |
def set_seed(seed):
"""
Set the seed to be used in any random generator. This is used to produce deterministic results.
Note:
This set_seed function sets the seed in the Python random library and numpy.random library
for deterministic Python augmentations using randomness. This set_seed fun... | 5,296,606 |
def convert_headers_str(_str):
"""
convert headers str to dict
"""
_list = [i.strip() for i in _str.split('\n')]
headers_dict = dict()
for i in _list:
k, v = i.split(':', 1)
headers_dict[k.strip()] = v.strip()
return headers_dict | 5,296,607 |
def set_log(config_name):
"""配置日志"""
# 设置日志的记录等级
logging.basicConfig(level=config[config_name].LOG_LEVEL) # 调试debug级
# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
# 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
... | 5,296,608 |
def make_expand_dims_tests(options):
"""Make a set of tests to do expand_dims."""
test_parameters = [{
"input_type": [tf.float32, tf.int32],
"input_shape": [[5, 4], [1, 5, 4]],
"axis_value": [0, 1, 2, -1, -2, -3],
"constant_axis": [True, False],
"fully_quantize": [False],
}, {
... | 5,296,609 |
def eliminate_from_neighbors(csp, var) :
"""Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduced, re... | 5,296,610 |
def cross(a, b):
"""Cross Product function
Given vectors a and b, calculate the cross product.
Parameters
----------
a : list
First 3D vector.
b : list
Second 3D vector.
Returns
-------
c : list
The cross product of vector a and vector b.
... | 5,296,611 |
def add_multiply(x, y, z):
"""Add two numbers and multiply it with a third."""
addition = add(x, y)
product = multiply(addition, z)
return product | 5,296,612 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the media_source component."""
hass.data[DOMAIN] = {}
hass.components.websocket_api.async_register_command(websocket_browse_media)
hass.components.websocket_api.async_register_command(websocket_resolve_media)
hass.components.fronten... | 5,296,613 |
def rand_sampling(ratio, stop, start=1) :
"""
random sampling from close interval [start, stop]
Args :
ratio (float): percentage of sampling
stop (int): upper bound of sampling interval
start (int): lower bound of sampling interval
Returns :
A random sampling list
... | 5,296,614 |
def runit():
"""Runs the task."""
parse_creds = get_credentials(PARSE_CRYPTOKEY, PARSE_API_FILE)
json = fetch_parse(parse_creds) # noqa: E221
csv_data = make_csv(json)
write_data_to_gcs(csv_data) | 5,296,615 |
def open_webpage(url):
"""some webpages block the user agent 'python'"""
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
req = urllib.request.Request(url, headers=hdr)
return urllib.request.urlopen(req) | 5,296,616 |
def compare_from_file(filename, disable_tokenizers=None, verbose=True,
additional_tokenizers=None):
"""
Method to compare the tokenizers from an input text.
This function outputs information about the execution environment
and data and comparison results.
Parameters
-----... | 5,296,617 |
def humanbool(name, value):
"""
Determine human boolean value
:Parameters:
`name` : ``str``
The config key (used for error message)
`value` : ``str``
The config value
:Return: The boolean value
:Rtype: ``bool``
:Exceptions:
- `ValueError` : The value could n... | 5,296,618 |
def xlsx_to_array(url, sheetname='Data', skiprows=1, **kwds):
"""
Convert xlsx to numpy 2D array of objects
Parameters
---------
url: string or io
Can either be a path or and io object
sheetname: str
The sheet name for the sheet in the xlsx file wanted
Default: 'Data'
... | 5,296,619 |
def run():
"""Execution function
:return: None
"""
obj = ListSpecial()
obj.print_info() | 5,296,620 |
def inner_join_indexer_float64(*args, **kwargs): # real signature unknown
""" Two-pass algorithm for monotonic indexes. Handles many-to-one merges """
pass | 5,296,621 |
def test_transform_data():
"""
Testing the transformation of the data from raw data to functions
used for fitting a function.
"""
# We start with actual data. We test here just that reading the data in
# different ways ultimately generates the same arrays.
from matplotlib import mlab
or... | 5,296,622 |
async def filter_record(record_a, record_b, filter_fields=None):
"""
Filters a record for unique information.
Args:
record_a (``dictionary``): New airtable record.
record_b (``dictionary``): Old airtable record (This will be dictate the ``id``)
Kwargs:
filter_fields (``list``, o... | 5,296,623 |
def mask_tokens_evenly(tokens, gap, min_token_lengths, mask_token, gap_mask=1):
"""Produce several maskings for the given tokens where each masking is created by masking every
"gap" tokens, as long as the token is large enough according to min_token_lengths.
Args:
tokens (List[str]): a sequence of ... | 5,296,624 |
def cal_acc(cm):
"""
基于混淆矩阵计算每类的精确度、召回率
"""
n = len(cm)
acc_cnt = 0 # 分类正确的数量
all_cnt = 0 # 所有样本数
for c in range(n):
acc_cnt += cm[c][c]
all_cnt += sum(cm[c])
acc_rate = acc_cnt / float(all_cnt)
print('准确率: ', acc_rate)
for i in range(len(cm[0])):
... | 5,296,625 |
async def async_setup(hass, config):
"""Set up the Polar component."""
conf = config.get(DOMAIN)
hass.data[DOMAIN] = conf or {}
if conf is not None:
_LOGGER.debug('Setting up Polar config flow from configuration data')
hass.async_create_task(
hass.config_entries.flow.async... | 5,296,626 |
def run(env, q_func, session, model_path,
replay_buffer_size=1000000, frame_history_len=4, max_episode_count=500,
render=False):
"""Run Deep Q-learning algorithm.
You can specify your own convnet using q_func.
All schedules are w.r.t. total number of steps taken in the environment.
Parameters
... | 5,296,627 |
def valid_host(host: Host) -> Host:
""" Validation test for valid Host class
Parameters:
host (Host): Host class object
Returns:
Host: Valid Host object
"""
from .hosts import Host
if not isinstance(host, Host):
raise ex.InvalidHostError(
f'Must be Host clas... | 5,296,628 |
def build_graph(input_file):
"""Build the graph data structure from the input csv file."""
# Open the csv as dict iterator
input_file = open(input_file, 'rU')
reader = csv.DictReader(input_file)
# Create all nodes
nodes = {}
for row in reader:
name = row['NODE']
nodes[name] ... | 5,296,629 |
def build_rnn_dataset(sst_home, reader, class_func=ternary_class_func):
"""Given an SST reader, return the `class_func` version of the
dataset as (X, y) training pair.
Parameters
----------
sst_home : str
Full path to the 'trees' directory for SST.
reader : train_reader or dev_reader
... | 5,296,630 |
def iso_dt_to_datetime(t: str) -> str:
""" """
return default_datetime_repr(datetime.datetime.fromisoformat(t[:-1])) | 5,296,631 |
def no_internet(verbose=False):
"""
Temporarily disables internet access (if not already disabled).
If it was already disabled before entering the context manager
(i.e. `turn_off_internet` was called previously) then this is a no-op and
leaves internet access disabled until a manual call to `... | 5,296,632 |
def index():
"""
后台管理首页
"""
user = g.user
return render_template("admin/index.html", user=user.to_dict()) | 5,296,633 |
def test_distance(markers, verbose=True,threshold=200,size=None):
"""detect if to center is too near than seuil delet the smaller
markers : image input
verbose : if you want display process
threshold : the sqaure distance into center
size : the minimum size of area of the retai... | 5,296,634 |
def cs(dataset, pts=0.0, neg=False, **kwargs):
"""
Circular shift.
For multidimensional NDDataset,
the shift is by default performed on the last dimension.
Parameters
----------
dataset : nddataset
nddataset to be shifted
pts : int
Number of points toshift.
neg : bo... | 5,296,635 |
def _result_value_flat_to_batchable(result_value_flat, result_flat_signature):
"""Converts result_value_flat -> result_value_batchable."""
result_value_batchable = []
for (r_value, r_spec) in zip(result_value_flat, result_flat_signature):
if isinstance(r_spec, tensor_spec.TensorSpec):
result_value_batch... | 5,296,636 |
def unloadBasicAnims():
"""
Unload the default Toon anims
"""
loadPhaseAnims(0) | 5,296,637 |
def test_get_result_rpc_no_ok_but_data_xml(nce_element):
"""Test get result failed."""
nce_element.ok = False
nce_element.data_xml = "<configure></configure>"
result = get_result(nce_element, xmldict=True)
assert result["failed"]
assert "configure" in result["result"]["xml_dict"].keys() | 5,296,638 |
def sample_action(Q, state, num_actions, epsilon):
"""
Epsilon greedy action selection.
Parameters
----------
Q : numpy array of shape (N, 1)
Q function for the environment where N is the total number of states.
state : int
The current state.
num_actions : int
The ... | 5,296,639 |
def get_socket_from_cluster_id(cluster_id):
"""
Returns the socket and token/queue dict for the specified cluster id
:param cluster_id: The if of the cluster to check
:return: The websocket and dict if found or None
"""
# Iterate over the connections
for sock in CONNECTION_MAP:
# Ch... | 5,296,640 |
def save_user_giphy(user: "Users", giphy: "str") -> "Tuple[Response, int]":
""" Saves giphy to user account
Params:
user (Users): User model provided by token_required
giphy (str): Giphy ID provided by GIPHY
Returns Tuple[Response, int]
"""
results: "Dict" = Giphies.save_giphy(users... | 5,296,641 |
def contain_same_digit(a, b):
"""
This function tests whether or not numbers a and b contains the same digits.
"""
list_a = list(str(a))
list_b = list(str(b))
if len(list_a) == len(list_b):
for elt in list_a:
if elt not in list_b:
return False
return T... | 5,296,642 |
def get_names_of_packages(packages_info, without_rpmem):
"""
Returns names of packages, that should be built.
"""
packages = []
types = ['-', '-debug-', '-devel-', '-debuginfo-', '-debug-debuginfo-']
for elem in packages_info:
# checks if rpmem and rpmemd packages should be built
... | 5,296,643 |
def send_incident_update_notifications(incident: Incident, previous_incident: IncidentRead):
"""Sends notifications about incident changes."""
notification_text = "Incident Notification"
notification_type = MessageType.incident_notification
notification_template = INCIDENT_NOTIFICATION_COMMON.copy()
... | 5,296,644 |
def main(adapter_address):
"""Creation of peripheral"""
logger = logging.getLogger('localGATT')
logger.setLevel(logging.DEBUG)
# Example of the output from read_value
print('Random number representing CPU temp is {}\u00B0C.'.format(
int.from_bytes(read_value(), byteorder='little', signed=Tru... | 5,296,645 |
def test_normal_search_with_single_usage(
session, tg_context, strict_inline_search, user
):
"""Test correct score calculation for sticker set titles with a single sticker usage."""
# Simple search which should get nearly all stickers from both sets
context = Context(tg_context, "awesome", "", user)
... | 5,296,646 |
def has_nonnegative_entries(input_matrix: Union[sparse.csr_matrix, np.ndarray]) -> bool:
"""True if the array has non negative entries."""
if type(input_matrix) == sparse.csr_matrix:
return np.all(input_matrix.data >= 0)
else:
return np.all(input_matrix >= 0) | 5,296,647 |
def get_worker():
"""
Creates a redis queue worker with a retry exception handler.
To run the worker:
>> worker = get_worker()
>> worker.work(with_scheduler=True)
"""
settings = get_config()
queue = redis_queue(settings)
return Worker(
queues=[queue], connection=queue.connec... | 5,296,648 |
def save_mrc_image(im_data, output_name):
"""
im_data = needs to be np.array float32 with dimensions of the TIA image
output_name = string; name of the output file to be saved
"""
with mrcfile.new(output_name, overwrite = True) as mrc:
mrc.set_data(im_data)
mrc.update_header_... | 5,296,649 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Command Sensor."""
if config.get('command') is None:
_LOGGER.error('Missing required variable: "command"')
return False
data = CommandSensorData(config.get('command'))
add_devices([CommandBinarySensor(
... | 5,296,650 |
def error_data(code):
"""Constructs a dictionary with status and message for returning in an
error response"""
error = {
'status': code,
'message': http_status_message(code),
}
return error | 5,296,651 |
def get_logger(config: NamedTuple) -> logging.Logger:
"""
Create instance of a logger and configure it using the variables from yaml config variables
:return:
"""
try:
# create logger with app name
logger: logging.Logger = logging.getLogger(config.general.app)
logger.setLevel... | 5,296,652 |
def test_Mesh_NO6_transfinite():
"""Unittests for the mesh."""
if rAnk == mAster_rank:
print(">>> {test_Mesh_NO6_transfinite} ...... ", flush=True)
def u(t, x, y, z): return np.cos(np.pi*x) + np.sin(np.pi*y) * np.sin(np.pi*z-0.125)**2 + t/2
def v(t, x, y, z): return np.sin(np.pi*x) + np.sin(np.... | 5,296,653 |
def range_correction(series, range=None, value=np.nan):
"""Corrects issues with ranges.
Some values collected are not within the ranges. They could
also be removed using the IQR rule, but if we know the limits
we can filter them as errors instead of outliers.
.. todo: Warn if replace value is outs... | 5,296,654 |
def isPILAllowed():
"""Return true iff PIL should be used by the caller."""
global _pil_allowed
if _pil_allowed is None:
app = grailutil.get_grailapp()
_pil_allowed = (app.prefs.GetBoolean("browser", "enable-pil")
and pil_installed())
return _pil_allowed | 5,296,655 |
def read_yaml(config_path):
"""Load config files."""
with open(config_path) as file:
data = yaml.load(file, Loader=yaml.FullLoader)
return data | 5,296,656 |
def read_jsonlines(filepath: str) -> pd.DataFrame:
"""Function that reads a jsonlines file as a pandas dataframe"""
with open(filepath) as f:
lines = f.read().splitlines()
dicts = [eval(line) for line in lines]
return pd.DataFrame(dicts) | 5,296,657 |
def read_data_attention(strategy: tf.distribute.TPUStrategy,
max_len: int,
) -> Tuple[np.array, np.array, np.array, np.array, tf.data.Dataset, tf.data.Dataset, tf.data.Dataset, int]:
"""
read data from attention models
"""
logger.info('reading data for att... | 5,296,658 |
def clean(file):
"""Delete settings and configuration"""
try:
os.remove(file)
os.remove(SPLUNK_HOME_FILE)
except:
print
pass | 5,296,659 |
def cosine_sim(text1, text2):
"""
Calcuates the cosine distance between the skills
and the course description.
:param text1: Phrase 1
:param text2: Phrase 2
:return: returns the probabilistic measure of similarity.
"""
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english... | 5,296,660 |
def distinct(key_mapper=None):
"""Returns an observable sequence that contains only distinct
elements according to the key_mapper. Usage of
this operator should be considered carefully due to the maintenance
of an internal lookup structure which can grow large.
The source must be a MuxObservable.
... | 5,296,661 |
def svn_client_commit3(*args):
"""
svn_client_commit3(svn_commit_info_t commit_info_p, apr_array_header_t targets,
svn_boolean_t recurse, svn_boolean_t keep_locks,
svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_commit3, args) | 5,296,662 |
def parse_range(string):
"""
Parses IP range for args parser
:param string: formatted string X.X.X.X-Y.Y.Y.Y
:return: tuple of range
"""
ip_rng = string.split("-")
return [(ip_rng[0], ip_rng[1])] | 5,296,663 |
def WritePDB(structure, name):
"""
Takes a PDB structure and an output name and generates a .pdb file with the provided name in the output directory.
Function returns None.
"""
# declare PDBIO object
io = PDBIO()
io.set_structure(structure)
io.save(os.path.join(options.outdir, name))
... | 5,296,664 |
def panas(
data: pd.DataFrame,
columns: Optional[Union[Sequence[str], pd.Index]] = None,
language: Optional[Literal["english", "german"]] = None,
) -> pd.DataFrame:
"""Compute the **Positive and Negative Affect Schedule (PANAS)**.
The PANAS assesses *positive affect* (interested, excited, strong, e... | 5,296,665 |
def notes(l, b, i):
"""!parent-command
!c new
!d Create a new note (use \n for newline)
!a <title> <message...>
!r user
!c list
!d List all notes available
!r user
!c append
!d Append a line of text to a note
!a <title> <message...>
!r user... | 5,296,666 |
def measure_circuits_nondeterministic(allow_sampling=True):
""""Measure test circuits with non-deterministic count output."""
circuits = []
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
# Measure |++> state (sampled)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.barrier(qr... | 5,296,667 |
def process_stanford_sentiment_corpus(train_path, dev_path, test_path,
pkl_path,
unk_threshold,
unk_token= '<UNK>',
pad_token= '<PADDING>'):
"""
Input three... | 5,296,668 |
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
resp = urllib2.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif en... | 5,296,669 |
def lineno(): # pragma: no cover
"""
Returns the current line number in our script
:return:
"""
return str(' - line number: ' + str(inspect.currentframe().f_back.f_lineno)) | 5,296,670 |
def populate_args(argparser):
"""add arguments we expect """
argparser.add_argument('--kafka_topic', '-kt',
help='''kafka_topic''',
default='smmart.g2p')
argparser.add_argument('--kafka_bootstrap', '-kb',
help='''kafka host:po... | 5,296,671 |
def _require_response_200_ok(response):
"""
Accept a requests.response object.
Raise ResponseNotOK if status code is not 200.
Otherwise, return True
"""
if response.status_code != 200:
raise ResponseNotOK(
status_code=response.status_code, message=response.text
)
... | 5,296,672 |
def trial_matrix(root,iwhisker=0,ifeature=3):
""" image plot of a feature for a whisker where each row is a trial
"""
import fnmatch
import os
def gen_names(root):
for r,dirnames,filenames in os.walk(root):
for filename in fnmatch.filter(filenames,'*.measurements'):
yield os.path.join(r,fi... | 5,296,673 |
def adjustion(path_img):
"""
Processing the images by interaction, include rotation, clip,
:param path_img: the path of image files, eg. r'../input_img/'img/.
:return:
"""
fig, ax = pylab.subplots(figsize=(10, 7)) # setting the window size.
if not os.path.exists(path_img + 'adjust'):... | 5,296,674 |
def pf_index(grid: Grid, grid_params: GridParams) -> PFIndex:
"""Ordered buses and mappings to admittances and slack factors."""
pv_idx = pv_buses(grid, grid_params)
pq_idx = pq_buses(grid, grid_params)
s_idx = slack_factors(grid, grid_params)
y_idx = admittances(grid, grid_params)
ret... | 5,296,675 |
def read_rdump(filename: str) -> dict:
"""
Read data formatted using the R dump format.
"""
contents = open(filename).read().strip()
names = [name.strip() for name in re.findall(r'^(\w+) <-', contents,
re.MULTILINE)]
values = [value.strip() for value in re.split(r'\w+ +<-', contents... | 5,296,676 |
def selectYear(update: Update, context: CallbackContext):
"""
Select the yaer for which to list expenses
"""
year = update.message.text
context.user_data['inputYear'] = year
text = ("Received '"+year+"' as the selected year"
+"\nSelect from below the month for which you'd like to list exp... | 5,296,677 |
def create_fleet(ai_settings, screen, ship, aliens):
"""Cria uma frota completa de alienigenas"""
# Cria um alien e calcula o número de aliens em uma linha
# O espaçamento entre os aliens é igual à largura de um alienigena
alien = Alien(ai_settings, screen)
number_aliens_x = get_number_aliens_x(ai_s... | 5,296,678 |
def test_constants_named():
""" This test demonstrates the possibility to create constants """
from mini_lambda import x, _, C
from math import e
E = C(e, 'e')
assert str(_(x + e)) == 'x + 2.718281828459045'
assert str(_(x + E)) == 'x + e'
assert str(_(E + E)) == 'e + e' | 5,296,679 |
def cleanup(home=None, files=_files):
"""Cleanup application files"""
if not home:
import state
home = state.appdata
for pfile in files:
try:
os.remove(os.path.join(home, pfile))
except OSError:
pass | 5,296,680 |
def sort_by_field(boxlist, field, order=SortOrder.descend, scope=None):
"""Sort boxes and associated fields according to a scalar field.
A common use case is reordering the boxes according to descending scores.
Args:
boxlist: BoxList holding N boxes.
field: A BoxList field for sorting and reordering the... | 5,296,681 |
def process_frame(frame_data, d_width, d_height, features_file, images_dir, min_trajectory_len):
"""Save faces + features from a frame, and creating face embeddings.
"""
# Filter to faces with a valid trajectory (len > MIN)
valid_faces = [
face for face in frame_data["faces"]
if multi_tr... | 5,296,682 |
def minimal_polynomial(ex, x=None, **args):
"""
Computes the minimal polynomial of an algebraic element.
Parameters
==========
ex : algebraic element expression
x : independent variable of the minimal polynomial
Options
=======
compose : if ``True`` ``_minpoly_compose`` is used, ... | 5,296,683 |
def listSpectra():
"""listSpectra()
List the spectra in the Spectrum List and their Jython alias. Same as ls()"""
ls() | 5,296,684 |
def init_compress_timepix_data(
pos, t, binstep, filename, mask=None, md=None, nobytes=2, with_pickle=True
):
"""YG.Dev@CHX Nov 19, 2017 with optimal algorithm by using complex index techniques
Compress the timepixeldata, in a format of x, y, t
x: pos_x in pixel
y: pos_y in pixel
timepix3 det s... | 5,296,685 |
def calc_dihedral(v1, v2, v3, v4, x_idx=None, y_idx=None, eps=1e-6):
"""
Calculate the dihedral angle between 4 vectors.
v1, v2, v3, v4: shape (..., 3)
x_idx, y_idx: shape (...), additional information of vectors.
return: (x_idx, y_idy, dihedral)
"""
x = v2 - v1
y = v3 - v2
z = v4 - ... | 5,296,686 |
def _cartesian(n, k):
"""Cartesian product.
Generator producing the all the length n vectors
with values [0,...k - 1].
"""
if n == 0:
yield []
return
for i in range(k):
for ass0 in _cartesian(n - 1, k):
yield [ i ] + ass0 | 5,296,687 |
def init_python():
"""
Installs all basic packages for Ubuntu
"""
print(_yellow("...Initialising Python Packages..."))
if not is_sudo():
mode_sudo()
python_package_ensure('django-storages')
python_package_ensure('boto')
python_package_ensure('django-celery')
python_package_... | 5,296,688 |
def set_convert_inputs(flag):
""" This function is a temporary workaround for reducing the overhead of operator
invocations. The function `convert_inputs` is disabled if the global state
`_enable_convert_inputs` is set to `False`, otherwise enabled. This function is for
internal use only, and should be ... | 5,296,689 |
def encode_flush():
"""
Flush the encoding buffers and return final frames (if any).
"""
_lib.lame_encode_flush.argtypes = [
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
_lib.lame_encode_flush.restype = ctypes.c_int
mp3buffer = (ctypes.c_char * 7200)()
mp3buffer_used = _lib.lame_e... | 5,296,690 |
def database_tenant_delete(tenant_uuid):
"""
Delete a tenant object from the database
"""
db = database_get()
session = db.session()
query = session.query(model.Tenant)
query.filter(model.Tenant.uuid == tenant_uuid).delete()
session.commit() | 5,296,691 |
async def test_create_time_event_adapter_fails(
client: _TestClient, mocker: MockFixture, token: MockFixture, new_time_event: dict
) -> None:
"""Should return 400 HTTPBadRequest."""
mocker.patch(
"race_service.services.time_events_service.create_id",
return_value=None,
)
mocker.patch... | 5,296,692 |
def writeVar(varName: str, val: str, file) -> None:
"""Formatter File wrapper
Args:
varName (str): environment variable to be exported
val (str): value to be assigned to
file (FileObject): file we are writing to
"""
alloc = f"export {varName}={val}\n"
file.write(alloc) | 5,296,693 |
def _migrateAddressbook(inAddressbook, outAddressbook, getComponent):
"""
Copy all addressbook objects and properties in the given input addressbook
to the given output addressbook.
@param inAddressbook: the L{IAddressbook} to retrieve addressbook objects
from.
@param outAddressbook: the L{... | 5,296,694 |
def test_struct_time(conn, db_parameters):
"""
Binds struct_time object for updating timestamp
"""
tzstr = 'America/New_York'
os.environ['TZ'] = tzstr
if not IS_WINDOWS:
time.tzset()
test_time = time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S")
with conn() as cnx:
... | 5,296,695 |
async def format_stream(member: discord.Member, osu_score: dict, beatmap: dict):
""" Format the stream url and a VOD button when possible. """
stream_url = None
for activity in member.activities:
if activity and activity.type == discord.ActivityType.streaming and hasattr(activity, "platform") \
... | 5,296,696 |
def parse_city_state_zip(city_state_zip):
""" Parses city_state_zip into a dict """
city_state_zip = normalize(city_state_zip.replace(",", ", ").replace(".", ". ").strip())
if city_state_zip:
# normalize commas
_m = " ,"
while _m in city_state_zip:
city_state_zip =... | 5,296,697 |
def flows_from_sff(flows):
"""lines is sff file lines.
"""
if isinstance(flows, str):
flows = flows.splitlines()
flows, head = parse_sff(flows)
return flows_from_generic(flows) | 5,296,698 |
def clear_screen():
"""
Clears Python Interpreter Terminal Window Screen
"""
loader.clear_screen() | 5,296,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.