content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_postagging_with_nagisa():
"""Test nagisa tokenizer."""
try:
tokenizer = WordTokenizer(tokenizer="nagisa", with_postag=True)
except ImportError:
pytest.skip("nagisa is not installed.")
expect = [Token(**kwargs) for kwargs in nagisa_tokens_list]
result = tokenizer.tokenize("吾... | 5,301,500 |
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gradient of weight by l2... | 5,301,501 |
def financial_info(index):
""" get the company financial info for index
:param index: stock index
:return: data frame containing financial data by season
"""
from china_stock_data_api import netease
return netease.NeteaseStockInfo.latest(index) | 5,301,502 |
def handle_response(response, display=False):
"""
Dispatch response based on scripting response or event.
"""
def handle_script_response(response, display=False):
if display:
sys.stderr.write(
u'Scripting request submitted with request id: {}\n'.format(
... | 5,301,503 |
def presto_fft(eventfile,segment_length,demod,PI1,PI2,t1,t2):
"""
Obtain the FFT files that were generated from PRESTO
eventfile - path to the event file. Will extract ObsID from this for the NICER files.
segment_length - length of the segments
demod - whether we're dealing with demodulated data or... | 5,301,504 |
def p_statement_to_identifier(p: yacc.YaccProduction) -> yacc.YaccProduction:
"""
safe_code_expression : IDENTIFIER
"""
p[0] = ast.IdentifierNode([p[1]]) | 5,301,505 |
def hostname():
"""
Check the system's hostname
:rtype: str
:return: system hostname
"""
return socket.gethostname().split('.')[0] | 5,301,506 |
def test_agent_info():
"""Test the agent_info custom type."""
agents_info = OefSearchMessage.AgentsInfo(
{
"agent_address_1": {"key_1": b"value_1", "key_2": b"value_2"},
"agent_address_2": {"key_3": b"value_3", "key_4": b"value_4"},
}
)
assert agents_info.get_info... | 5,301,507 |
def run_optimizers(args):
"""Optimize each of an iterable of PySource objects."""
sources = tuple(load_path(args.source))
for source in sources:
utils.execute(args, source.node)
return sources | 5,301,508 |
def import_data(file):
"""
Imports instruction data from a .csv file, at the specified filepath
:param file: file
File object, to be read by the CSV reader
:return: list
A list of dictionaries, per row in the file, with the keys specified in the headers list
below
"""
... | 5,301,509 |
def test_metrics_logger_log_metric(mlflow_log_metric_mock):
""" Tests MetricsLogger().log_metric() """
metrics_logger = MetricsLogger()
metrics_logger.open()
metrics_logger.log_metric("foo", "bar", step=16)
metrics_logger.close()
mlflow_log_metric_mock.assert_called_with(
"foo", "bar", ... | 5,301,510 |
def recipe_footpod_symmetry(
df_footpods, df_music, df_phone_activity, df_sessions, sections=None
):
"""
Recipe for extracting statistical symmetry information per song for
valid bouts of running of the real-time footpod data.
Parameters
----------
df_footpods : pandas.DataFrame
Dat... | 5,301,511 |
def ingest_jstor():
"""
Ingest JSTOR texts.
"""
Text.ingest_jstor() | 5,301,512 |
def _set_random_states(estimator, random_state=None):
"""Sets fixed random_state parameters for an estimator
Finds all parameters ending ``random_state`` and sets them to integers
derived from ``random_state``.
Parameters
----------
estimator : estimator supporting get/set_params
Esti... | 5,301,513 |
def get_authed_registries():
"""Reads the local Docker client config for the current user
and returns all registries to which the user may be logged in.
This is intended to be run client-side, not by the daemon."""
result = set()
if not os.path.exists(constants.DOCKER_CONFIG_PATH):
return re... | 5,301,514 |
def filter_data(data_frame):
"""
Process string value
:param data_frame: raw data in data frame type
:return: data frame
"""
data_frame[data_frame.columns[len(data_frame.columns) - 2]] = \
data_frame[data_frame.columns[len(data_frame.columns) - 2]].apply(lambda x: int("".join(re.findall(... | 5,301,515 |
def setup_module():
"""Change me"""
pass | 5,301,516 |
def test_update_output_div_test():
""""Test update user input"""
input_value = 'hello'
assert update_output_div(input_value) == '{}'.format(input_value) | 5,301,517 |
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
""" get timezone as tz_offset """
tz_offset = datetime_to_timezone(
datetime.now(), tz=tz_from).strftime('%z')
tz_offset = tz_offset[:3] + ':' + tz_offset[3:]
date = parse_date(str(date_str) + tz_offset)
if tz_from != tz_to:
... | 5,301,518 |
def _extract_bracket_params(meta_type: str) -> Tuple[str, List[Any]]:
"""
Gets parameters from the string representation of the type
Args:
meta_type (str): The string name of the metadata type
Returns:
Tuple[str, List[Any]]: A tuple, first arg is a string of the type
name only ... | 5,301,519 |
def make_classification_df(
seed: int,
n_samples: int = 10_000,
n_features: int = 25,
n_informative: int = 10,
n_redundant: int = 10,
n_repeated: int = 5,
class_sep: float = 0.2,
flip_y: float = 0.1,
target_col: str = "target",
) -> pd.DataFrame:
"""Source of default values: http... | 5,301,520 |
def create_view_ID(img):
"""
Generates 12-digit ID of image to make sure each image has a unique identifier. When saving and reading
image features, two images with the same filename will have unique identifiers.
:param img: image to create an ID for.
:return viewID: a unique viewId based on im... | 5,301,521 |
def readList(flist, list_type='array',sep='\s+'):
"""
Function to read a key files and performs checks for required columns parameters
Parameters:
flist: str or pandas dataframe
A path to the key file or DataFrame itself
list_type: str
"array" for array list, "event" for earthquake list, "coda" for coda st... | 5,301,522 |
def calc_local_file_md5_sum(path):
"""
Calculate and return the MD5 checksum of a local file
Arguments:
path(str): The path to the file
Returns:
str: The MD5 checksum
"""
with open(path, "rb") as file_to_hash:
file_as_bytes = file_to_hash.read()
return hashlib.md5(... | 5,301,523 |
def test_calculate_delta_H(): # pylint: disable=invalid-name
"""test calcfunction calculate_delta
make sure space in string is striped."""
calculate_delta = CalculationFactory('sssp_workflow.calculate_delta')
inputs = {
'element': orm.Str('H'),
'V0': orm.Float(17.3883),
'B0': o... | 5,301,524 |
def news_keywords() -> str:
"""[Fetches the keywords used to gather news articles]
Returns:
str: [A string of the keywords searched for by the news API]
"""
with open("config.json", encoding="UTF-8") as config:
config_data = json.load(config)
news_kw = config_data["Varia... | 5,301,525 |
def default_weapon_type_option(
description: str = "Restrict the weapon type. Default: All types", required: bool = False
) -> Any:
"""
Decorator that replaces @slash_option()
Call with `@default_weapon_type_option()`
"""
def wrapper(func):
return slash_option(
name="weapon... | 5,301,526 |
async def get_patrol_id(request: Request):
""" 获取当前order id,已经加 1 的了 """
_date_str = datetime.now().strftime('%Y%m')
patrol_id = await request.app['redis'].get(f'it:patrolID:{_date_str}')
if patrol_id is None:
async with request.app['mysql'].acquire() as conn:
async with conn.cursor(... | 5,301,527 |
def parse(
response_text: str, *, batch: bool, validate_against_schema: bool = True
) -> Union[JSONRPCResponse, List[JSONRPCResponse]]:
"""
Parses response text, returning JSONRPCResponse objects.
Args:
response_text: JSON-RPC response string.
batch: If the response_text is an empty str... | 5,301,528 |
def install_client(request):
"""Displays an agreement that the user must agree to before they can download the MDM Client installer"""
context = {}
if request.method == 'POST':
form = ClientForm(request.POST)
if form.is_valid():
installer = os.path.join(settings.MEDIA_ROOT, "soft... | 5,301,529 |
def test_inheritance() -> None:
"""
One interesting thing about attrs is how inheritance works.
This makes handling DI for inheriting classes a breeze.
"""
@dc.dataclass()
class BaseHandler:
request: HttpRequest
@dc.dataclass()
class MyHandler(BaseHandler):
fs: IFileSy... | 5,301,530 |
def test_sync_attachments_offset(sync_attachments, session):
"""
Sync only 4 attachments by using an offset
"""
result = sync_attachments(["--offset", "6"])
assert "4 inserts" in result.stdout
assert session.query(MuseumAttachment).count() == 4 | 5,301,531 |
def get_ping_ip():
# TODO: convert return to json object
"""
Get ips for network testing.
@return: HTML containing a list of IPs
"""
config = request.form['config']
peers = g.cur.execute("SELECT id, name, allowed_ip, endpoint FROM " + config).fetchall()
html = ""
for i in peers:
... | 5,301,532 |
def compute_warped_image_multiNC(
I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True
):
"""Warps image.
:param I0: image to warp, image size BxCxXxYxZ
:param phi: map for the warping, size BxdimxXxYxZ
:param spacing: image spacing [dx,dy,dz]
:return: returns the warped image ... | 5,301,533 |
def get_day(days: int = 0):
"""
返回的日期格式 %Y-%m-%d
:param days: 距离今天的天数
:return: 格式 %Y-%m-%d
"""
return (datetime.datetime.now() + datetime.timedelta(days=days)).strftime("%Y-%m-%d") | 5,301,534 |
def emit_compare(field_name, value, session, model):
"""Emit a comparison operation comparing the value of ``field_name`` on ``model`` to ``value``."""
property = getattr(model, field_name)
return property == value | 5,301,535 |
def line_loglog(x, m, n):
"""a straight line in loglog-space"""
return x ** m * np.e ** n | 5,301,536 |
def hist_compare(condition, label1, label2, df):
"""Compare histograms of SalePrice of 2 groups. The condition is applied on group 1 and !condition is applied
on group 2."""
df_c = df[condition][COL_Y]
df_nc = df[~condition][COL_Y]
print("{}: {} | {}: {}".format(label1, len(df_c), label2, len(df_nc)... | 5,301,537 |
def plot_statistical_uncertainty(response_matrix, filename=None, **kwargs):
"""Plot the maximum sqrt(statistical variance) of each truth bin.
This plots will contain the minimum, maximum, and median marginalization of
these maximum numbers.
Parameters
----------
response_matrix : ResponseMatr... | 5,301,538 |
def milcshake_a ( dt, bond, r_old, r, v ):
"""First part of velocity Verlet algorithm with constraints."""
# This subroutine iteratively adjusts the positions stored in the array r
# and the velocities stored in the array v, to satisfy the bond constraints
# using a tri-diagonal solver
# See AG Bai... | 5,301,539 |
def test_list_boolean_pattern_3_nistxml_sv_iv_list_boolean_pattern_4_1(mode, save_output, output_format):
"""
Type list/boolean is restricted by facet pattern with value [1]{1}
false [0]{1} true true [0]{1}.
"""
assert_bindings(
schema="nistData/list/boolean/Schema+Instance/NISTSchema-SV-IV-... | 5,301,540 |
def parse_LDI_ins(tokens):
"""Attempts to parse a LDI instruction."""
failure = None
assert len(tokens) > 0
token1 = tokens[0]
op = token1.text
if op.upper() != 'LDI':
return failure
statement = Obj()
statement.type = 'STATEMENT'
statement.statement_type = 'INSTRUCTION'
s... | 5,301,541 |
def mad(a, axis=None):
"""
Compute *Median Absolute Deviation* of an array along given axis.
"""
# Median along given axis, but *keeping* the reduced axis so that result can still broadcast against a.
med = np.nanmedian(a, axis=axis, keepdims=True)
mad = np.nanmedian(np.absolute(a - med), axis=a... | 5,301,542 |
def test_matplotlib_incompatibility():
"""
Assert an exception is raised if make_axes_locatable is None
"""
with pytest.raises(YellowbrickValueError):
JointPlot(hist=True) | 5,301,543 |
def torch_image_to_numpy(image: torch.Tensor):
"""
We've created a function `torch_image_to_numpy` to help you out.
This function transforms an torch tensor with shape (batch size, num channels, height, width) to
(batch size, height, width, num channels) numpy array
"""
# Normalize t... | 5,301,544 |
def has_data(file_path):
"""
Check if a file has any data in it.
`Args:`
file_path: str
The file path.
`Returns:`
boolean
``True`` if data in the file and ``False`` if not.
"""
if os.stat(file_path).st_size == 0:
return False
else:
r... | 5,301,545 |
def unsigned32(i):
"""cast signed 32 bit integer to an unsigned integer"""
return i & 0xFFFFFFFF | 5,301,546 |
def get_snippet_edit_code(request, snippet_id):
"""
Returns a HTTPResponse that renders the admin of a smartsnippet.
:param request: Request needed to create the rendering context
:param snippet_id: id of the smartsnippet model
:param request.POST.config: dictionary containing existing configurati... | 5,301,547 |
def add_htseq_options(parser):
""" Add options to a cmd parser to call htseq-count.
N.B. This is primarily intended for use with the htseq workflow.
Parameters
----------
parser: argparse.ArgumentParser
The parser to which the options will be added
"""
htseq_options = parser.add_a... | 5,301,548 |
def get_user_legs(df, user_id, use_multiprocessing=True) -> pd.DataFrame:
"""
Builds the legs DataFrame for the given user.
Args:
df (pandas.DataFrame): waypoints DataFrame
user_id (str): ID of the user whose legs are to be created
use_multiprocessing (bool, optional): Specifie... | 5,301,549 |
def generate_input(
seq_len: int, batch_size: int, input_names: List[str], device: str = "cuda"
) -> Tuple[Dict[str, torch.Tensor], Dict[str, np.ndarray]]:
"""
Generate dummy inputs.
:param seq_len: number of token per input.
:param batch_size: first dimension of the tensor
:param input_names: t... | 5,301,550 |
def get_task_or_404(challenge_slug, task_identifier):
"""Return a task based on its challenge and task identifier"""
t = Task.query.filter(
Task.challenge_slug == challenge_slug).filter(
Task.identifier == task_identifier).first()
if not t:
abort(404)
return t | 5,301,551 |
def make_window_fill(bm, face, fill_type, **kwargs):
"""Create extra elements on face
Args:
bm (bmesh.types.BMesh): bmesh for current edit mesh
face (bmesh.types.BMFace): face to operate on
fill_type (str): Type of elements to add
**kwargs: Extra kwargs from WindowProperty
... | 5,301,552 |
def BuildToken(request, execution_time):
"""Build an ACLToken from the request."""
token = access_control.ACLToken(
username=request.user,
reason=request.REQ.get("reason", ""),
process="GRRAdminUI",
expiry=rdfvalue.RDFDatetime().Now() + execution_time)
for field in ["REMOTE_ADDR", "HTTP_X... | 5,301,553 |
def test_entities__FieldCustomization__1(address_book):
"""It implements the IFieldCustomization interface."""
fc = IFieldCustomization(address_book)
assert isinstance(fc, FieldCustomization)
assert zope.interface.verify.verifyObject(IFieldCustomization, fc) | 5,301,554 |
def parse_logfile_event_marker(line_str):
"""
Parse a logfile line as an event marker.
Parameters:
line_str (str): a line from the locust log for a load test with markers
enabled.
Returns:
dict: dict object with the following keys: 'time' (value is
datetime.date... | 5,301,555 |
def preprocess_pipeline(image):
"""preprocess_pipeline processes the image data.
args:
image: a numpy array in shape of (224, 224, 3)
returns:
image: the processed image numpy array
"""
assert np.array_equal(image.shape, (224, 224, 3)), \
"The image's shape requires (22... | 5,301,556 |
def ask_path(folder_flag=True, multiple_files_flag=False):
"""Makes a tkinter dialog for choosing the folder if folder_flag=True
or file(s) otherwise. For multiple files the multiple_files_flag should
be True.
"""
# This method is almost never used, so the required imports are locally called
imp... | 5,301,557 |
def compute_gad_point_indices_mp(args: tuple) -> dict:
"""
Computes geometric anomaly detection (GAD) Procedure 1 from [1], for data point
indices, taking in args for multiprocessing purposes.
Parameters
----------
args : tuple
Multiprocessing argument tuple:
data_points : n... | 5,301,558 |
def has_and_not_none(obj, name):
"""
Returns True iff obj has attribute name and obj.name is not None
"""
return hasattr(obj, name) and (getattr(obj, name) is not None) | 5,301,559 |
def _dump(config_instance, dict_type=OrderedDict):
""" Dumps an instance from ``instance`` to a dictionary type mapping.
:param object instance: The instance to serialized to a dictionary
:param object dict_type: Some dictionary type, defaults to ``OrderedDict``
:return: Dumped dictionary
:rtype: c... | 5,301,560 |
def eval_jac_g(x, out):
"""Values of the jacobian of g"""
assert len(x) == nvar
out[()] = [
x[1] * x[2] * x[3],
x[0] * x[2] * x[3],
x[0] * x[1] * x[3],
x[0] * x[1] * x[2],
2.0 * x[0],
2.0 * x[1],
2.0 * x[2],
2.0 * x[3],
]
return out | 5,301,561 |
def pytorch_load_save_functions(
state_dict_objects: dict,
mutable_state: Optional[dict] = None,
fname: str = "checkpoint.json",
):
"""
Provides default `load_model_fn`, `save_model_fn` functions for standard
PyTorch models (arguments to `resume_from_checkpointed_model`,
`checkpoint_model_at... | 5,301,562 |
def trivial_tokenize_urdu(s):
"""
A trivial tokenizer which just tokenizes on the punctuation boundaries. This also includes punctuations for the Urdu script.
These punctuations characters were identified from the Unicode database for Arabic script by looking for punctuation symbols.
returns a list... | 5,301,563 |
def fpath_to_link(repo_id, path, is_dir=False):
"""Translate file path of a repo to its view link"""
if is_dir:
url = reverse("repo", args=[repo_id])
else:
url = reverse("repo_view_file", args=[repo_id])
href = url + '?p=/%s' % urllib2.quote(path.encode('utf-8'))
return '<a href="%... | 5,301,564 |
def _qname_matches(tag, namespace, qname):
"""Logic determines if a QName matches the desired local tag and namespace.
This is used in XmlElement.get_elements and XmlElement.get_attributes to
find matches in the element's members (among all expected-and-unexpected
elements-and-attributes).
Args:
... | 5,301,565 |
def NodeArrangementHexToTet(C):
"""Node ordering for conversion of a hexahedron into 6 tetrahedra
refer to: [Julien Dompierre et.al. "How to Subdivide Pyramids, Prisms and Hexahedra into Tetrahedra",
8th International Meshing Roundtable, Lake Tahoe, California, 10-13 October 1999.] for only p=1... | 5,301,566 |
def datetogmt(str):
""" Convert date string to gmt time. """
date_tuple = datetotuple(str)
return mkgmtime(date_tuple) | 5,301,567 |
def cookiecutter(input_dir):
"""
API equivalent to using Cookiecutter at the command line.
:param input_dir: A directory containing a project template dir,
or a URL to git repo.
"""
# If it's a git repo, clone and prompt
if input_dir.endswith('.git'):
got_repo_arg = True
... | 5,301,568 |
def parse_color(color):
""" Parses color into a vtk friendly rgb list """
if color is None:
color = rcParams['color']
if isinstance(color, str):
return vtki.string_to_rgb(color)
elif len(color) == 3:
return color
else:
raise Exception("""
Invalid color input
M... | 5,301,569 |
def skewness(iterable, sample=False):
""" Returns the degree of asymmetry of the given list of values:
> 0.0 => relatively few values are higher than mean(list),
< 0.0 => relatively few values are lower than mean(list),
= 0.0 => evenly distributed on both sides of the mean (= normal distribu... | 5,301,570 |
def create_plant(user_id, plant_name, plant_type, photo_url, germinate_date,
directsow, transplant_date, growing_medium, location,
environment, lighting, schedule):
""" For example:
>>> create_plant(1, "Nadine", "Aloe", "/static/img/aloe.jpg", "11/11/2020",
"dir... | 5,301,571 |
def writeDaily(config, daily, data_binding, table_type):
"""
Writes a Daily object or list of Daily objects to the specified data_binding and table. table_type must be 'obs',
'verif', 'climo', 'hourly_forecast', or 'daily_forecast', or something defined in the schema of data_binding as
%(stid)_%(table_t... | 5,301,572 |
def get_train_task_paths(args):
"""
store
1. all the patterns (i.e. relation in the path at most 3-hop)
2. all the subgraphs (i.e. nodes and their labels in the paths)
between the head and candidate tails in test_tasks
"""
#bg_graph = BGGraph(args)
dataset = os.path.join(... | 5,301,573 |
def get_line_extents_from_json(json_data, font_file_name):
"""Find the vertical extents of a line based on HarfBuzz JSON output."""
max_height = None
min_height = None
for glyph_position in json.loads(json_data):
glyph_id = glyph_position['g']
glyph_ymin, glyph_ymax = get_glyph_vertical_... | 5,301,574 |
def findSpikes(
file_name,
sweep_IB_concatenated,
prominence_min = None,
prominence_max = None,
wlen_ms = 10,
sampling_rate_khz = 25
):
"""
`findSpikes` uses scipy's `find_peaks` on the concatenated sweeps to detect peaks in the data and obtain their prominences. It then plots the di... | 5,301,575 |
def promptForFlirtFiles(parent, overlay, overlayList, displayCtx, save=False):
"""Displays a dialog prompting the user to select a FLIRT
transformation matrix file and associated reference image for
the given overlay.
:arg parent: The :mod:`wx` parent object.
:arg overlay: The overlay to l... | 5,301,576 |
def coord_c2g(map_):
"""Rotate a map from celestial co-ordinates into galactic co-ordinates.
This will operate on a series of maps (provided the Healpix index is last).
Parameters
----------
map : np.ndarray[..., npix]
Healpix map.
Returns
-------
rotmap : np.ndarray
T... | 5,301,577 |
def tourism_per_year_by_country(country):
"""Returns the number of arrivals (tourism) per year of the given country."""
cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="ST.INT.ARVL"'.format(country))
tourism = cur.fetchall()
cur.close()
return json... | 5,301,578 |
def run_spark_job(spark_args):
"""
:param spark_args:
:type spark_args:
:return:
:rtype:
"""
storage_account_name = spark_args.storage_account_name
output_container = spark_args.output_container_name
output_folder = spark_args.output_folder_path
application_id = spark_args.applic... | 5,301,579 |
def bar_plot(df, col_name, title=None, xlabel=None, ylabel='Count'):
"""
Draw's a single bar plot
Parameters
----------
df : Pandas Data Frame
col_name : column name in data frame
title : Plot title
xlabel : X-axis label
ylabel : Y-axis label
"""
fig = plt.figure(figsize=(10... | 5,301,580 |
def run_local(command: str, str_output: Optional[bool] = False) -> Union[int, str]:
"""Runs a command locally and captures output."""
print(command)
if str_output:
process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
universal_newl... | 5,301,581 |
def test_replace_common_object_attrs():
"""test_replace_common_object_attrs test to verify the functionality of replacing an action objects unique attributes
:param fx_get_sub_parser: [description]
:type fx_get_sub_parser: [type]
"""
test_name = "My new name"
original_uuid = TEST_OBJ['uuid']
... | 5,301,582 |
def get_hst_to_jwst_coefficient_order(polynomial_degree):
"""Return array of indices that convert an aeeay of HST coefficients to JWST ordering.
This assumes that the coefficient orders are as follows
HST: 1, y, x, y^2, xy, x^2, y^3, xy^2, x^2y, x^3 ... (according to Cox's
/grp/hst/OTA/alignment/Fo... | 5,301,583 |
def get_categories(title: str) -> List[str]:
"""
Gets the categories of the wikipedia page `title` from
https://en.wikipedia.org/w/api.php?action=query&format=json&titles={title}&prop=categories
Returns empty list for invalid title with no redirects
"""
params = {
**PARAMS_CATEGORIES,
... | 5,301,584 |
def get_chombo_box_extent(box, space_dim):
"""
Parse box extents from Chombo HDF5 files into low and high limits
Parameters
----------
box : List
Chombo HDF5 format box limits,
e.g. [x_lo, y_lo, x_hi, y_hi] = [0,0,1,1]
space_dim : int
Number of spatial dimensions
... | 5,301,585 |
def _fast_rcnn_box_loss(box_outputs, box_targets, class_targets, normalizer=1.0,
delta=1.):
"""Computes box regression loss."""
# delta is typically around the mean value of regression target.
# for instances, the regression targets of 512x512 input with 6 anchors on
# P2-P6 pyramid is a... | 5,301,586 |
def calc_gcn_norm(edge_index, num_nodes, edge_weight=None):
"""
calculate GCN Normalization.
Parameters
----------
edge_index:
edge index
num_nodes:
number of nodes of graph
edge_weight:
edge weights of graph
Returns
-------
1-dim Tensor
"... | 5,301,587 |
def get_raw_pdb_filename_from_interim_filename(interim_filename, raw_pdb_dir):
"""Get raw pdb filename from interim filename."""
pdb_name = interim_filename
slash_tokens = pdb_name.split('/')
slash_dot_tokens = slash_tokens[-1].split(".")
raw_pdb_filename = raw_pdb_dir + '/' + slash_tokens[-2] + '/'... | 5,301,588 |
def txt_to_csv(dfile):
"""Converting the textfile to another textfile where elements are seperated with commas
Function meant for false detection module only
"""
with open("resultsdata_mod_.txt", "a") as f:
f.write("_id,time_ratio,intensity_ratio,bandwidth_1,bandwidth_2,error")
f.write(... | 5,301,589 |
def test(ctx, checks=False, doctest=False):
"""Run all tests."""
if checks:
check(ctx)
with chdir(BASE_FOLDER):
cmd = ['pytest']
if doctest:
cmd.append('--doctest-modules')
ctx.run(' '.join(cmd)) | 5,301,590 |
def mae(y_true, y_pred):
"""Mean absolute error"""
assert y_true.shape == y_pred.shape, f"{y_true.shape} != {y_pred.shape}"
return np.mean(np.abs(y_true - y_pred), axis=0) | 5,301,591 |
def class_tree_graph(bases, linker, context=None, **options):
"""
Return a `DotGraph` that graphically displays the class
hierarchy for the given classes. Options:
- exclude
- dir: LR|RL|BT requests a left-to-right, right-to-left, or
bottom-to- top, drawing. (corresponds to the dot op... | 5,301,592 |
def start_cameras_and_mjpeg_servers():
"""
Starts the cameras and mjpeg servers
"""
if not DEVELOP:
# Stop camera triggers
camera_trigger.stop()
# Wait until camera inspectors are running and then start cameras
while not mct_introspection.camera_inspectors_ready():
... | 5,301,593 |
def sub_sample_dataset_iterator(key, dataset, batch_size):
"""Iterator for subsample a dataset such that each sub_dataset has at most batch_size data points.
Args:
key: Jax random state.
dataset: dict of SubDataset.
batch_size: int, maximum number of data points per sub dataset in a batch.
Yields:
... | 5,301,594 |
def generate_parameters(phase_models, datasets, ref_state, excess_model, ridge_alpha=None, aicc_penalty_factor=None, dbf=None):
"""Generate parameters from given phase models and datasets
Parameters
----------
phase_models : dict
Dictionary of components and phases to fit.
datasets : Pickle... | 5,301,595 |
def cg_optimize(th,floss,fgradloss,metric_length, substeps,damping,cg_iters=10, fmetric=None,
num_diff_eps=1e-4,with_projection=False, use_scipy=False, fancy_damping=0,do_linesearch=True, min_lm = 0.0):
"""
Use CG to take one or more truncated newton steps, where a line search is used to
enforce improv... | 5,301,596 |
def create_ipython_shortcuts(shell):
"""Set up the prompt_toolkit keyboard shortcuts for IPython"""
kb = KeyBindings()
insert_mode = vi_insert_mode | emacs_insert_mode
if getattr(shell, 'handle_return', None):
return_handler = shell.handle_return(shell)
else:
return_handler = newli... | 5,301,597 |
def b():
"""Break into the Debugger when called"""
pdb.set_trace() | 5,301,598 |
def add_forth_coord(points):
"""forth coordinate is const = 1"""
return np.hstack((points, np.ones((len(points), 1)))) | 5,301,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.