content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_original_dword(*args):
"""
get_original_dword(ea) -> uint64
Get original dword (that was before patching) This function works for
wide byte processors too. This function takes into account order of
bytes specified in \inf{is_be()}
@param ea (C++: ea_t)
"""
return _ida_bytes.get_original_dwo... | 7edbc0dfbd42d14c199be76ce2f99cfdc22aad45 | 60,800 |
def within_refresh_interval(now, last_info_pull):
"""
This is so we don't flood the server with overly frequent HTTP traffic
"""
return now - last_info_pull < INFO_REFRESH_INTERVAL | e4e98311bc6178c7fe9cebf12890ea86aab62ce1 | 60,801 |
def polar2rect(mag, phase_angle):
"""Convert polar-form complex number to its rectangular form."""
mag = tf.complex(mag, tf.convert_to_tensor(0.0, dtype=mag.dtype))
phase = tf.complex(tf.cos(phase_angle), tf.sin(phase_angle))
return mag * phase | 303673654125d1de94428db6e0afddd92a92d746 | 60,802 |
def gen_explicit_map_one_delta(params_pt, args_pt, k_ms, k_pt):
"""
Generate explicit_map for which include mapping relationship is `1 - k_ms = k_pt`.
Args:
params_pt (dict): Params for APIPt.
args_pt (dict): Args for APIPt.
Returns:
dict, map between frames.
"""
value ... | 841d81c0095dadf7e62c32fca5a3d9e6007b6032 | 60,803 |
from typing import Any
from contextlib import suppress
def catch_timeout_error(return_value: Any = False):
"""
This decorator will catch TimeoutException and return `return_value`.
"""
@wrapt.decorator
def wrapper(wrapped, _, args, kwargs) -> Any:
with suppress(TimeoutException):
... | fd758f93f97f41a40d9bbad6659e8740676aaaf5 | 60,804 |
def calc_uniform_log_prob(spec):
"""Given an action spec, calculate the uniform log prob.
Args:
spec (BoundedTensorSpec): action spec must be a bounded spec
Returns:
The uniform log probability
"""
assert isinstance(spec, BoundedTensorSpec)
zeros = np.zeros(spec.shape)
min_... | 0af627357e2fa598ceaa2adc1211a4259c533d7e | 60,805 |
import os
import pickle
def generate_cosine_similarity_score(stb_df, ref_df, input_folder_path):
"""
Given corpus and limiter to differentiate stb sentences from ref sentences, generate cosine similarity score for
each sentence pair across stb and ref df
:param stb_df: dataframe consisting of stb sent... | 0a55831b037b177b46cc4534c3320f9ba5c6a382 | 60,806 |
def reward_qvals(rewards, discount):
"""
Same as qvals but accepts traces of observed rewards.
"""
all_qvals = []
for reward_trajectory in rewards:
# numerically stable cumulative reward sum
path_qvals = np.empty_like(reward_trajectory, dtype=np.float64)
future_qval = 0
... | 8b7cc893858221a2503e65f92bab66345a93c9ca | 60,807 |
def strip_comments(l: str) -> str:
"""
Strip any ``#`` comments from a line.
:param str l: A string line, which may contain ``#`` comments
:return str clean_line: The line ``l`` - stripped of any comments and excess whitespace.
"""
return l.split('#', 1)[0].strip() | 0587cb5e2a986c9d0bb4c610c289186b8c184942 | 60,808 |
def shengbte_code(aiida_local_code_factory):
"""Get a shengbte code.
"""
shengbte_code = aiida_local_code_factory(executable='diff',
entry_point='shengbte')
return shengbte_code | de9f6bba763c4bfe7f6a1153927f73542a83dc6a | 60,809 |
import mimetypes
def get_content_type(content, name):
"""
Checks if the content_type is already set. Otherwise uses the mimetypes
library to guess.
"""
if hasattr(content.file, "content_type"):
return content.file.content_type
else:
mime_type, encoding = mimetypes.guess_type(na... | 838d11c2660e0d76c813961498ab0ebcc25c1f3c | 60,810 |
def switch_backend(*args, **kwargs):
"""
Call `matplotlib.pyplot.switch_backend`.
%(ui.pyplot)s
Parameters
----------
*args, **kwargs
Passed to `matplotlib.pyplot.switch_backend`.
"""
return plt.switch_backend(*args, **kwargs) | be925a389cc795d2db0e2b48103823f0310391ef | 60,811 |
def parse_content(content):
"""
:param content:
:return: converted text
"""
try:
text = convert_text(content, settings.TO_FORMAT_EXT, format='html',
extra_args=["+RTS", settings.HEAP, "-RTS"])
except:
text = 'too big'
return text | 824cac81497ddfe6eeac488ce6af881c4f8a9dcb | 60,812 |
from pathlib import Path
def combine_cfgs(path_cfg_data: Path=None, path_cfg_override: Path=None):
"""
An internal facing routine thaat combined CFG in the order provided.
:param path_output: path to output files
:param path_cfg_data: path to path_cfg_data files
:param path_cfg_override: path to p... | 8ce12f970d6c06a3b86cc9144c761b44d5ec2832 | 60,813 |
import socket
from typing import cast
def find_available_port() -> int:
"""Finds a local random unoccupied TCP port."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
_, port = s.getsockname()
return cast(int, port) | 53d98f1a9e6c98d7ad608af53600007bc93f2af8 | 60,814 |
def in_or_none(x, L):
"""Check if item is in list of list is None."""
return (L is None) or (x in L) | bc3e4ef5a8daf7669e7430940e361d4c7ec1a240 | 60,815 |
def recoverDoc(cur):
"""parse an XML in-memory document and build a tree. In the
case the document is not Well Formed, a attempt to build a
tree is tried anyway """
ret = libxml2mod.xmlRecoverDoc(cur)
if ret is None:raise treeError('xmlRecoverDoc() failed')
return xmlDoc(_obj=ret) | 14a8b5031e6f8b3e64730452095656ebc7855a4b | 60,816 |
async def list_keys(request: web.Request) -> web.Response:
"""List keys in the authorized_keys file.
GET /server/ssh_keys
-> 200 OK {"public_keys": [{"key_md5": md5 hex digest, "key": key string}]}
(or 403 if not from the link-local connection)
"""
return web.json_response(
{
... | 0dd5e23b1ef128f436bb61559f5c77420bc2a2f2 | 60,817 |
def score(results, in_label, out_labels, w=1.0, col="probability", neg_only=False):
"""Score kmer from kmer family probabilities.
The scoring method used is as follows:
Score = P(in family) - (w_out * P(out of family)) - P(bg)
Parameters
----------
results : dict or pandas.DataFrame
... | e182d1c0ebd7f8cff7f6e6d982412d549f3a670a | 60,818 |
def patch_forces(patch_ids, forces):
"""
Return a list containing patch forces
"""
return np.bincount(patch_ids.reshape((-1,)),
weights=forces.reshape((-1,)))[1:] | 3aa7b1238216cd35e683b36fdddb94844b28a2d3 | 60,819 |
from typing import List
import subprocess
def run_mypy(directory: str) -> List[str]:
"""Run mypy to identify functions with type hint violations.
Flags:
--ignore-missing-imports: Omitting for simplicity's sake (https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports)
--disallo... | c7a4dcae187dc5490aa3e47ca9a3ce1b7f3c106e | 60,820 |
def get_vaccine_general_summary():
"""Returns DataFrame with a synthesis of COVID-19 vaccines deliveries and administrations in Italy.
Parameters
----------
None
Raises
------
ItaCovidLibConnectionError
Raised when there are issues with Internet connection.
Returns... | 5bf64105648685653941d76a30bed6338b2651e6 | 60,821 |
import time
import sys
import os
from io import StringIO
import gzip
def deploy_to_s3(conn, frozen_path, bucket_name, no_delete, overwrite_all):
""" Deploy a frozen app to S3, semi-intelligently. """
print('*** Preparing to deploy in: %s' % bucket_name)
time.sleep(1)
# Get our bucket
bucket = co... | 0d888bf5e0eebe93271f6949655a4db74e156ba7 | 60,822 |
def r_array_register(line_str, line_pos, line_num):
"""
Read an array of registers.
Args:
line_str (str): The code line.
line_pos (int): The code line position to start reading.
line_num (int): The code line number in the parsed text file.
Returns:
label_array (str): Th... | 6248f51209491889b1356b29a014296200d16a65 | 60,823 |
from .exceptions import error_for
def requires_app_credentials(func):
"""Require client_id and client_secret to be associated.
This is used to note and enforce which methods require a client_id and
client_secret to be used.
"""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
cl... | 2d43115aba27c8dfb9f210025d6bcdae24504835 | 60,824 |
def reverse_causal(effective_kernel_size: int):
"""Post-padding such that output has no dependence on the past."""
return [0, effective_kernel_size - 1] | 9a09069304376efe72f4e72a2f18b9c0e5d62b1c | 60,825 |
def long_text_filter(row, column, user_data=None):
"""
Uses the format_long_text helper function to trim and prettify some text.
"""
text = row[column]
cols = user_data["cols"]
if text:
text = rabbitvcs.util.helper.format_long_text(text, cols)
return text | 353388dc5614942f74e544de2bc5a9e33a617c99 | 60,826 |
def inceptionresnetv1(**kwargs):
"""
InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 4b924256e21096a785d913cce820baeca8209841 | 60,827 |
import os
def valid_loss_calc(data_dir, model_path, city):
"""
write outdata into each submission folder structure at out_path, cloning
filenames in corresponding folder structure at input_path.
"""
test_indices = utcPlus3
if city == "Berlin":
test_indices = utcPlus2
model = ... | 5ad1c3873d50325a8d64a94e910f6aa48d8eac27 | 60,828 |
def _is_pixel_list(data):
"""
Returns True if data is a pixel list, False otherwise.
A pixel list is a 1-dimensional list of pixels where a pixel is a tuple
of 3 ints in the range 0..255
Parameter data: The data to check
Precondition: NONE (data can be anything)
"""
if type(data) != li... | 821fdb166e467a483290312d8bebd22d8cb95922 | 60,829 |
import base64
import warnings
import google
def implements(request_type, response_type):
"""
A decorator for making an AWS Lambda implement a gRPC server
:param request_type: The expected request type
:param response_type: The expected response type
:return: The decorated function
"""
# TO... | bb525045a112718f636f7d1def1ae8c321e7a2b4 | 60,830 |
import os
def save_image_to_upload_dir(filestrorage_obj, _filename=None):
"""
Save the filestorage object as a file in the upload directory
The file is saved with a random filename. The private `_filename` argument
can be used during testing to force the file being saved with a defined
filename.
... | e7b0c81f849e59d458a5bfcd7c9419c816ad7e87 | 60,831 |
def _clean_timeformat(text):
"""returns an ISO date format from a funny calibre date format"""
if text.endswith("+00:00"):
text = text[:-6] + "+0000"
if text[10] == " ":
text = text.replace(" ", "T", 1)
return text | 03f908e8cc85485496d627248e9dfce2e2ab08f2 | 60,832 |
def count_macro_cycles(smiles_list, smarts_list, tot, probs):
"""
Args:
smiles_list: list of SMILES
smarts_list: list of SMARTS
tot: counter of ... TODO: why is this passed?
probs: OrderedDict of {SMARTS: counts}
Returns:
"""
# probs = collections.OrderedDict()
... | ea0177484459893457a52ea8c9c627fd2753f102 | 60,833 |
def SETATTR(x, y, ATTR=None, INK=None, PAPER=None, BRIGHT=None, FLASH=None):
"""Sets the attribute at a given text position. The attribute is an 8-bit value. The lowest three bits
specify the ink colour, the next three bits specify the paper, the next bit specifies brightness,
and the highest bit specified ... | ab3ebb39961bd4c7e9d66bc3b27d658ccc506eb4 | 60,834 |
def statistic_color(color_array):
"""
主要是获取box内的hsv值中h的方差
:param color_array: box对应的矩阵
:return: 返回box的hsv值中h的方差
"""
h_value = color_array[:, :, 0]
s_value = color_array[:, :, 1]
variance = np.var(h_value) + np.var(s_value)
return variance | a6652d56f91bc7b59808cfe00ccb0b662ca46f20 | 60,835 |
import itertools
import json
def create_resources(key_combination, values):
"""
key_combination: a tuple containing a key names' combination (e.g. ('name',) or ('description',) or ('name', 'description'))
values = a list of values which will be combined against key_combination's items (e.g. ['null', '[]']... | 7563cb1eb9758e0ea57494974561192e6c6eef9b | 60,836 |
def build_scheduler(
optimizer: Optimizer,
iters_per_epoch: int,
cfg: CN,
) -> Scheduler:
"""Build learning rate scheduler.
Parameters
----------
optimizer : Optimizer
Target optimizer
iters_per_epoch : int
Number of iterations per epoch
cfg : CN
Global con... | 1c56211504a6573cc19ed772d8370568e87f2bfc | 60,837 |
def resnext50d_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Constructs a ResNeXt50d-32x4d model. ResNext50 w/ deep stem & avg pool downsample"""
default_cfg = default_cfgs["resnext50d_32x4d"]
model = ResNet(
Bottleneck,
[3, 4, 6, 3],
cardinality=32,
bas... | a934cd6947b5efbb53607ac46363894261623693 | 60,838 |
def color_text(text, color_name, bold=False):
"""
This command can be used to colorify command line output. If the shell
doesn't support this or the --disable-colors options has been set, it just
returns the plain text.
Usage:
print "%s" % color_text("This text is red", "RED")
"""
if... | 69f2f4ae7cb07e0bd6e5b99e0adecedf164c49b2 | 60,839 |
def get_previous_non_blank_line(clean_lines, line_number):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
line_number: The number of the line to check.
Returns:
A tuple with two elements. The first ... | 90d29a9bf6914babc69757a9809174e9c4bb6bae | 60,840 |
import sys
from typing import Generator
def minimize(mofun,
nobj,
ncon,
bounds,
popsize = 64,
max_evaluations = 100000,
workers = 1,
f = 0.5,
cr = 0.9,
pro_c = 1.0,
dis_c = 20.0,
... | 8fb420c3ae4cbd98d94f33e9be432e0f32dd445b | 60,841 |
def get_ssid() -> str:
"""Gets SSID of the network connected.
Returns:
str:
WiFi or Ethernet SSID.
"""
process = Popen(
['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-I'],
stdout=PIPE)
out, err = process.communicate()
... | d9c158fa5daf5c4c3e327bd9791ccf0448ddce4c | 60,842 |
import tasks as user_invoke
import fabfile as user_fabric
import sys
import os
def get_user_tasks():
"""Get tasks defined in a user's tasks.py and fabric.py file which is
assumed to be in the current working directory.
:returns: tuple invoke_tasks, fabric_tasks
"""
try:
sys.path.insert(0,... | 7761c5531786c271b52be9fcdcce4450c63fdaab | 60,843 |
def asn_query():
"""Query data from database, plot them and return figure."""
# Query asn and print the most frequent ones
query = """
SELECT speedtest.asn, country, COUNT(speedtest.asn) as count
FROM speedtest, asn WHERE speedtest.asn = asn.asn
GROUP BY speedtest.asn, as... | 92f8db0a858f3d158cf2b2c7785e4735401e44e9 | 60,844 |
def logout():
"""管理人员退出"""
response=make_response(redirect(UrlManager.buildUrl("/login/")))
response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
return response | 94700cb0c5050c033cc9fb35f5917e03faea1bf4 | 60,845 |
import os
def generate_paths(dataset, arg):
""" Generate paths for either Sintel or Kitti
Requires the following environment variables to be set:
- SINTEL_HOME
- KITTI_HOME
- MRFLOW_SINTEL_INIT
- MRFLOW_KITTI_INIT
"""
if dataset == 'sintel':
testtrain, pas, seq, frame = arg.sp... | 52c331159cd555b2781c02c38f62df0787c6c30d | 60,846 |
def convert_gdml_volume(volume, position):
"""Convert an arbitrary GDML volume to MCNP surfaces"""
if position is not None:
placement = convert_gdml_position(position)
else:
placement = 3 * (0.,)
# Check for a binary volume
tag = volume[0]
if tag == "intersection":
tran... | 7cefa22cd5cc715fbabc4ce74695d6f54da88abd | 60,847 |
def _GetMaxOutlinedIndex(sym_dict):
"""Find the largest index of an outlined functions.
See _OUTLINED_FUNCTION_RE for the definition of the index. In practice the
maximum index equals the total number of outlined functions. This function
asserts that the index is near the total number of outlined functions.
... | 126a05dd9b04894abf8568ee71f5b20b8b8ee4bb | 60,848 |
def evaluate(test_labels, preds, n_decimals=2, binary=True):
"""
Code to evaluate the predictions of our model.
:param test_labels (list): The labels list of our testing set.
:param preds (list): The predicitions (given by our model) of our testing set.
:param n_decimals (float): The number of deci... | 97989610605a6dc3fe35075ed84210baf5e730ea | 60,849 |
import json
def get_users():
"""
Read all the users from the dynamo database.
"""
response = _users_table.scan(Select="ALL_ATTRIBUTES")
return [json.loads(record["user_obj"]) for record in response.get("Items", [])] | f7c120ac405a891e3d713f691c57549f83362d9c | 60,850 |
def get_grid_values(radar):
"""
Return the values specific to a grid for mapping the radar data to
Cartesian coordinates.
"""
return _DEFAULT_GRID_VALUES[radar].copy() | 5759a891863a8bed8782e83bd85214d24d9601fc | 60,851 |
def comment_modify_question(request, comment_id):
"""
pybo 질문댓글수정
"""
comment = get_object_or_404(Comment, pk=comment_id)
if request.user != comment.author:
messages.error(request, '댓글수정권한이 없습니다')
return redirect('pybo:detail', question_id=comment.question.id)
if request.method ... | 393cf49c24f4469a474d2b1835d42947554ea29b | 60,852 |
def sort_by_date(xinfo, data, time_index, max_days=30, max_years=2):
"""
Sorts images by nearest date to reference
Args:
xinfo (object): The data object.
data (3d array): The data to slice and sort.
time_index (int): The current time reference.
max_days (Optional[int]): The... | aa51d5143359d67bb972bcc942d975feb003fbc5 | 60,853 |
from io import StringIO
def image2str(img):
"""Converts PIL Image object to binary data.
@param img: PIL Image object
@return: binary data
"""
f = StringIO()
img.save(f, "JPEG")
return f.getvalue() | 0ba3958475018f30ccc25a23d80f384dd75552c7 | 60,854 |
import random
def experiment(doors, strategy, choice_func, correct):
"""
Function that runs the actual experiment.
A selection is first chosen at random. Then, whilst there are at
least 3 doors remaining, the host reveals one incorrect door that
is not the door most recently selected. Then the co... | f5ffc84a08612d4f6aecd027edc1363b7b4279fa | 60,855 |
def plot_graph_folium(
G,
graph_map=None,
popup_attribute=None,
tiles="cartodbpositron",
zoom=1,
fit_bounds=True,
**kwargs,
):
"""
Plot a graph as an interactive Leaflet web map.
Note that anything larger than a small city can produce a large web map
file that is slow to ren... | b9947e0adf36c4b76a4fbf7980d10f9258f0f38d | 60,856 |
def length_validator(min_len=0, max_len=None):
"""Create a function that checks the length.
The type of the checked values must support the
:func:`len` function.
:param int min_len: the minimum length
:param max_len: the maximum length (``None`` means no limit)
:type max_len: int or None
:... | 6bb6448d5cbe457f93c39e2e5109ba60e67033e1 | 60,857 |
def parse_query(query):
"""
Parses grammar output to ETL JSON.
:param query: Str. DSL query.
:returns: JSON. ETL JSON.
"""
prsd = parser.parseString(query)
match_pattern = prsd["match_pattern"]
nodes = [{"node": node.asDict()} for node in match_pattern["nodes"]]
edges = [{"edge": ed... | 7d7594f796906dc8a2852a63b60e6e086e09288e | 60,858 |
def calc_iou(bbox_1, bbox_2):
"""Calculate the IOU (Intersection Over Union) given two set of bbox coordinates
All coordinates are in the order of (ymin, xmin, ymax, xmax), following the convention in `tf_example_decoder.py`
Args:
bbox_1: coordinates of bbox1
bbox_2: coordinates of bbox2
... | e6adbee50230187b20be287e8eb14b724e0367a6 | 60,859 |
def apply(R,point):
"""Applies the rotation to a point"""
return (R[0]*point[0]+R[3]*point[1]+R[6]*point[2],
R[1]*point[0]+R[4]*point[1]+R[7]*point[2],
R[2]*point[0]+R[5]*point[1]+R[8]*point[2]) | f6f4e5431e92dac9711f80da9ca0dc75bae793fb | 60,860 |
def svn_wc_has_binary_prop(*args):
"""svn_wc_has_binary_prop(char const * path, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t"""
return _wc.svn_wc_has_binary_prop(*args) | 1f6ec4e4b9c786be461e8070c99200e62f46fd32 | 60,861 |
def from_header(header: header.Header, data: hints.Buffer = b'') -> Message: # pylint: disable=redefined-outer-name
"""
Create a new :class:`~adbwp.message.Message` instance from an existing :class:`~adbwp.header.Header`.
:param header: Message header
:type header: :class:`~adbwp.header.Header`
:p... | b56e20aef5e928ec9a56503f4e56a747f5a28837 | 60,862 |
from typing import List
from typing import Dict
def process_records(records: List[Dict], shard_id: str, fh_d_stream: str):
"""Process the given records from the underlying Kinesis stream"""
return put_records(fh_d_stream, records) | 1b78f3227ea40ef059d53176d4d2ec18b4087672 | 60,863 |
def linexp_min(xx, h=p0['linexp'][0], a0=p0['linexp'][1], k=p0['linexp'][2]):
""" Calculates the minimum phase angle/P degree from given parameters.
"""
b = h*a0/(1 - (1 + k*a0)*np.exp(-k*a0))
c = h + k*b*np.exp(-k*a0)
amin = 1/k * np.log(k*b/c)
return (amin, _nb_linexp(amin, h=h, a0=a0, k=k)) | dbfaf2ff405826d19e681aaaffe73ca1d4e6f417 | 60,864 |
def decode_auth_token(auth_token):
"""
Decodes the auth token
:param auth_token:
:throws jwt.ExpiredSignatureError or jwt.InvalidTokenError
:return: integer|string
"""
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
return payload['sub'] | da8afe59a6006a496bc5c6aed84e0547b1098ff5 | 60,865 |
def _minimum_cone_(U, rs):
"""Calculate the minimum cone.
Computes the angle and center of the minimum cone, with its point
in the origin, enclosing the vectors in A.
Parameters
----------
U : np.array, ndim=2
The vectors that will be enclosed.
rs : RandomState
A RandomSta... | 27df12c40d3e882271e0ca4a56aedcefd74b877e | 60,866 |
from typing import Union
from typing import Optional
async def asyncio(
*,
client: AuthenticatedClient,
format_: Union[Unset, SchemaRetrieveFormat] = UNSET,
) -> Optional[SchemaRetrieveResponse200]:
"""OpenApi3 schema for this API. Format can be selected via content negotiation.
- YAML: applicati... | 1a61ade94a3b6600ad54fac249dd182b5c6f723c | 60,867 |
import re
import string
def PreProcessSentence(w, sentencepiece, lang):
"""
Preprocess a sentence by cleaning it, making everything
lower case etc.
If sentencepiece is being used then don't make spaces
between punctuations and words, as it has it's own
tokenizer.
:param lang: Language of sentence
:typ... | 5334a17ccc7f77ba514c3d4af94b778c01932eb1 | 60,868 |
def mode_off(comp_ent: Entity, ent: Entity) -> str:
"""Return the offset from the ent to the reference."""
scale = conv_float(comp_ent['const'], 1.0)
offset = Vec.from_str(ent['origin']) - Vec.from_str(comp_ent['origin'])
return vs_vec(offset * scale) | 5bb649db4f700b20d5b1b9f4409f9003a4e42dbd | 60,869 |
def fro_norm(a: np.array) -> float:
"""Calculate Froberius norm for an array."""
assert a.ndim == 1, "Check that 'fro_norm' receives a 1D array."
return np.linalg.norm(a) | 0aeadf52af040b0ba35216c7123f1e0e338545b2 | 60,870 |
def create_recipe():
""" Allows a user to add a new recipe """
if logged_in:
if request.values.get('category_id'):
category_id = int(request.values.get('category_id'))
category = None
for category in categories:
if category.user_id == session_user['us... | ce9f08f4c92358bbce83e0270880395207b3bde6 | 60,871 |
def get_measurement_meta():
"""Get metadata on one measurement by measurement_id + input
---
parameters:
- name: report_id
in: query
type: string
description: The report_id to search measurements for
- name: input
in: query
type: string
minLength: ... | 0e7c9f400e360a64a53a6b0499b295b2a0c5f2c2 | 60,872 |
def _auxiliary_graph(G, Features):
"""
prepare a graph with twice the number of vertices
this graph will contain the connectivity information
along the merges.
"""
K = WeightedGraph(2 * G.V - 1)
K.E = G.E
K.edges = G.edges.copy()
K.weights = np.ones(K.E)
K.symmeterize()
if K.... | 200c0ccb01a8777031e435d6fec3c96545441668 | 60,873 |
def get_translation(lang, country, key, plural):
"""
:type lang: str
:type country: str
:type key: str
:type plural: int or None
:rtype: str or None
"""
return _get_translation(
lang, country or None, key, "%" if plural is None else 'x',
plural) | 839c1befc7255df0329ef879f987f871fd7565a1 | 60,874 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding `MediaFile` object is updated
with new file.
"""
if not instance.pk:
return False | 903224f8070f61055e4068843eed0bb3360c94b6 | 60,875 |
def get_image(filename, patch_size):
"""Get image from filename.
Args:
filename: String filename of an image.
patch_size: Integer length to which the square image will be
resized.
Returns:
TensorFlow tensor containing the decoded and resized image with
type float32 and values in [0, 1).
... | 54d5ecf22fc7e05a43b31be88f5121a41673862f | 60,876 |
import sys
def safe_delete_from_backend(uri, context, image_id, **kwargs):
"""Given a uri, delete an image from the store."""
try:
return delete_from_backend(context, uri, **kwargs)
except exception.NotFound:
msg = _('Failed to delete image in store at URI: %s')
LOG.warn(msg % uri)... | 2c4acd833b7fe16dd26fe6a01f875d17d49d5693 | 60,877 |
def applyRuleTwo(f):
"""Apply Rule 2 to the formula f.
Args:
f (str): string representing a formula in binAd
Returns:
set of str: Set of formulas that can be produced by applying
Rule 2 to f. This will be empty if f is not well formed.
"""
result = set()
if n... | 5340a1dbdb91d60b07fcf0ef0fc3f8e14b581d06 | 60,878 |
def update_cholcov_with_measurement_error(shocks_cholesky, meas_sds, n_wages):
"""Make a Kalman covariance updated for all possible cases.
We use a square-root implementation of the Kalman filter to avoid taking any
Cholesky decompositions which could fail due to numerical error.
Parameters
------... | 6ad8df1c63f5ffc826fb123e0cd3ff528b2f9763 | 60,879 |
def system_balance_constraint_rule(backend_model, carrier, node, timestep):
"""
System balance ensures that, within each location, the production and
consumption of each carrier is balanced.
.. container:: scrolling-wrapper
.. math::
\\sum_{loc::tech::carrier_{prod} \\in loc::carr... | a63961e3d8ed3def40d692684b5d95d5ddc40bfb | 60,880 |
def deserialize_request_string(string, app):
"""Deserialize request string using in_protocol in application definition.
Returns the corresponding native python object.
"""
server = ServerBase(app)
initial_ctx = MethodContext(server, MethodContext.SERVER)
initial_ctx.in_string = [string]
ct... | ec8de227e54d29ca03d1411a71fb472d33f22cc5 | 60,881 |
def update_sub(orig_df, pivot_col=None, pivot_val=None, new_col=None, new_val=None):
"""
update a subset of DataFrame based on fixed boolean matching.
"""
out_df = orig_df.copy()
out_df.loc[out_df[pivot_col] == pivot_val, new_col] = new_val
return out_df | ee52c8bbc9c25e5198093e9f8435725acfb98170 | 60,882 |
import os
def read(eff_t, surf_g, met, abund, D = '3D', a = 1.5, v = 1, data_path = None):
"""Reads in the flux data for the specified dimension and stellar parameters.
Parameters
----------
eff_t : Real
The temperature closest to the real temperature of the model. This input should to be les... | e424d24cf10b7ebce81fe4f901ef3490e2e9f8e9 | 60,883 |
def buffer(ft):
"""
Buffer an input feature by 10km
"""
return ft.buffer(10000).bounds(5) | 2eb4eeadbbd47b2527c9ac63f64e21ae3593560c | 60,884 |
from typing import Optional
from typing import Union
def check_conf(
c: invoke.Context, value: Optional[str], conf_key: str, should_raise: bool = True
) -> Optional[Union[invoke.Context, str]]:
"""Ensure a value is provided from CLI flag value or config."""
if value is not None:
return value
... | 482950b69c56098cffc18b43273e09b9d1634e7f | 60,885 |
import torch
def i2t(images, sentences, nreps=1, npts=None, return_ranks=False, order=False, use_gpu=False):
"""
Images->Text (Image Annotation)
Images: (nreps*N, K) matrix of images
Captions: (nreps*N, K) matrix of sentences
"""
if use_gpu:
assert not order, 'Order embedding not supported in GPU mode... | 9ad2183da0b5640a43230999e61313d741da44bd | 60,886 |
def alpha_jacobian(**opts):
"""The jacobian of the change of variables
between virtuality and the alpha parameter of the rescaling collinear mapping.
"""
Q = opts['Q']
pC = opts['pC']
qC = opts['qC']
return Q.dot(qC)/Q.dot(pC) | ce83140c2266dcfdacc9753dde6d9aca5fae53f2 | 60,887 |
def has_new_triggerword(predictions, chunk_duration, feed_duration, threshold=0.5):
"""
Function to detect new trigger word in the latest chunk of input audio.
It is looking for the rising edge of the predictions data belongs to the
last/latest chunk.
Argument:
predictions -- predicted labels f... | 4a3d7b82e94fac7ee26b18dd848da4ef79378d30 | 60,888 |
import typing
from datetime import datetime
def tryparse_datetime(s: str, formats: typing.List[str]) -> datetime:
"""
Tries to parse the given string with any of the formats listed.
If all formats fail, returns None.
"""
for fmt in formats:
try:
return datetime.datetime.strpti... | c3cc3f02ac9c33865535feb79458ddbcfd7e204e | 60,889 |
def get_or_create_bucket_iam_binding(iam_policy, role):
"""Get or create the binding matching a role."""
binding = get_bucket_iam_binding(iam_policy, role)
if not binding:
binding = {'role': role, 'members': []}
iam_policy['bindings'].append(binding)
return binding | 30a961553f1c30d2508cc104229f55a18ea3bac8 | 60,890 |
from ..models.functor import BaseFunctor
from typing import Union
from typing import Iterable
from typing import List
def extract_extended_pdfs(pdfs: Union[Iterable[ZfitPDF], ZfitPDF]) -> List[ZfitPDF]:
"""Return all extended pdfs that are daughters.
Args:
pdfs:
Returns:
List[pdfs]:
... | 3774e5c8c751f15b10267ce9a5f6744dd58f1ff6 | 60,891 |
def create_monitor_api_client(access_token):
"""Create API client and construct API headers"""
api_client = ApiClient(host=DS_CONFIG["monitor_api_client_host"])
api_client.set_default_header(
header_name="Authorization",
header_value=f"Bearer {access_token}"
)
return api_client | 0e7d90611245ad090182c1ebacecfa08708ed317 | 60,892 |
def compute_nce_loss(img_embed, text_embed, temp=0.07, return_acc=False):
"""
Symmetrized NCE loss for paired image/text embeddings
"""
N = img_embed.shape[0]
img_norm = tf.nn.l2_normalize(img_embed, 1)
text_norm = tf.nn.l2_normalize(text_embed, 1)
# NOTE this is different from what's descri... | f52aa49c995dab2d6319a863a8bb076dc5fde2a4 | 60,893 |
def mean_field_ccppo_process(policy, sample_batch, other_agent_batches, odim, adim, other_info_dim):
"""Average the neighbors' observations"""
for index in range(sample_batch.count):
neighbours = sample_batch.data['infos'][index]["neighbours"]
neighbours_distance = sample_batch.data['infos'][ind... | ae34c43f9f43d7f12d90686a151db7d67b5970ff | 60,894 |
def _password_repr(val: str) -> str:
"""Change representation of password to hide its content."""
del val
return "'********'" | f7e5d653e874b023888d2f13502fc2ff9d894161 | 60,895 |
def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None):
"""pkcs#5 password-based key derivation v2.0 using HMAC + arbitrary digest.
:arg digest:
digest name or constructor.
:arg secret:
passphrase to use to generate key.
may be :class:`!bytes` or :class:`unicode` (encoded using... | 35cdd3af4201b29b9990817b905ecc26145f49b1 | 60,896 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
with Configurator(settings=settings) as config:
# static file for service description
config.add_static_view('static', 'static')
# X-road services
config.add_route('services_he... | a4e72ebce045ae83e9ae952d1b6a7f83f3da6ad9 | 60,897 |
def filtered_descendants(glob):
"""Returns glob-matching filenames under the current directory, but skips
some irrelevant paths."""
return find('.', glob, ['third_party', 'external', 'build*', 'out*',
'CompilerIdCXX', '.venv', 'glslang']) | 0ff601d756950dfa93b91dcdd212ab659645dba6 | 60,898 |
def Home(request):
"""
首页
:param request:
:return:
"""
recommend = Recommend.objects.filter(is_recommend=True)[:10]
qq = QQ.objects.all()
links = link.objects.all()
try:
page = request.GET.get('page', 1)
if page == '':
page = 1
except PageNotAnIntege... | 46f716d80ecc6bda3adb5893adcf5ac08d5f3b88 | 60,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.