content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_custom_char_line_import():
"""Test importing a custom characteristc lines."""
# we need to write some data to the path first, using defaults
data_path = resource_filename('tespy.data', 'char_lines.json')
path = extend_basic_path('data')
tmp_path = extend_basic_path('tmp_dir_for_testing')
... | 5,292,600 |
def _get_project_id():
"""Get project ID from default GCP connection."""
extras = BaseHook.get_connection("google_cloud_default").extra_dejson
key = "extra__google_cloud_platform__project"
if key in extras:
project_id = extras[key]
else:
raise ("Must configure project_id in google_cloud_defau... | 5,292,601 |
def main(args=sys.argv[1:]):
""" Main function. :param: args is used for testing """
user_inputs = cli(args)
url = user_inputs.params.url
active_features = user_inputs.active_features
if len(active_features) > 0:
time_dir = create_timestamped_dir()
with driver_factory(url) as driver:
for feature in active_f... | 5,292,602 |
def get_old_groups():
"""
Get all projects from Firebase which have been created
before we switched to v2.
"""
fb_db = auth.firebaseDB()
ref = fb_db.reference("groups")
projects = ref.get(shallow=True)
logger.info("got old projects from firebase")
return projects | 5,292,603 |
def get_orders():
"""Return all orders"""
return json.dumps(orders, indent = 4) | 5,292,604 |
def transform_geom(proj, geom):
"""Transform geometry"""
projected_geom = transform(proj, geom)
return projected_geom | 5,292,605 |
def test_getArgs():
"""
Test pdinstall.main.getArgs
"""
from pdinstall.main import getArgs
argv = ["install", "--source", "paradrop_0.1.0_all.snap"]
args = getArgs(argv)
assert args.sources == [argv[2]] | 5,292,606 |
def get_rotation_matrix(init, target):
"""Get rotation matrix that rotates the unit vector init to unit vector target
https://en.wikipedia.org/wiki/Rotation_matrix
Parameters
----------
init : list or numpy array
Initial unit vector
target : list or numpy array
Target unit vecto... | 5,292,607 |
def test_sorter_functions(func, array_to_sort, expected_sorted_array):
"""Test each array sorting algorithm implementation against the same set
of test parameters"""
assert func(array_to_sort) == expected_sorted_array | 5,292,608 |
def make_dcos_request(host_address, relative_url, params=None):
"""Makes a requests that is capable of traversing DCOS EE Strict boundary
:param master: The address for the Mesos master
:type master: `util.host.HostAddress`
:param relative_url: URL path relative to the base address
:type relative_u... | 5,292,609 |
def compute_log_phi(data_intervals, qs, eps, swap):
"""Computes multi-dimensional array log_phi.
Args:
data_intervals: Array of intervals of adjacent points from
compute_intervals.
qs: Increasing array of quantiles in [0,1].
eps: Privacy parameter epsilon.
swap: If true, uses swap dp sensitiv... | 5,292,610 |
def get_referencing_foreign_keys(mixed):
"""
Returns referencing foreign keys for given Table object or declarative
class.
:param mixed:
SA Table object or SA declarative class
::
get_referencing_foreign_keys(User) # set([ForeignKey('user.id')])
get_referencing_foreign_k... | 5,292,611 |
def save_environments(workspace, project, env_data):
"""save environments.json file contents.
env_data must be a valid json string.
Returns a string with the error or empty string otherwise"""
error = ''
if len(env_data):
try:
json.loads(env_data)
except:
erro... | 5,292,612 |
def G1DListMergeEdges(eda, edb):
""" Get the merge between the two individual edges
:param eda: the edges of the first G1DList genome
:param edb: the edges of the second G1DList genome
:rtype: the merged dictionary
"""
edges = {}
for value, near in eda.items():
for adj in near:
if (... | 5,292,613 |
def find_corners_of_largest_polygon(img):
"""Finds the 4 extreme corners of the largest contour in the image."""
opencv_version = cv2.__version__.split('.')[0]
if opencv_version == '3':
_, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours
else:
contours, h =... | 5,292,614 |
def main() -> None:
"""Wrap the main routine so that it can be tested."""
args = parse_args(sys_argv=sys.argv)
sys.exit(_main(args=args)) | 5,292,615 |
def hist_k(*args, **kwargs) -> str:
"""Returns the contents of the file created by ISIS hist as a string.
If there is a TO= parameter in the arguments, ``hist_k()`` will
create the file, and return its contents as a string
"""
to_pathlike = None
for (k, v) in kwargs.items():
if "to" == ... | 5,292,616 |
def test_hash_key_valid_input_longer():
"""Test hash key method with a longer valid input."""
h = HashTable(10)
assert h.hash_key('califradulouspiexpialidocious') == 3 | 5,292,617 |
def make_rpc_batch_request_entry(rpc_name, params):
"""
Construct an entry for the list of commands that will be passed as a batch
(for `_batch`).
"""
return {
"id": "50",
"version": "1.1",
"method": rpc_name,
"params": params,
} | 5,292,618 |
def iterm2hex(root):
"""Get hex codes from iterm xml
Args:
root (xmlroot): xmlroot
Returns:
dict: iterm keys to hex
"""
keys = root.findall("./dict/key")
dicts = root.findall("./dict/dict")
iterm = {}
for i, _key in enumerate(keys):
keyName = keys[i].text
r = g = b = None
for index, item in enumerat... | 5,292,619 |
def test_pds4_orbnum_blank_records_no_version(self):
"""Test an orbnum file with blank records.
Test the generation of a label when the ORBNUM file has some incomplete
entries (which is a real possibility.)
In such case the record length is expanded to the adequate fixed length.
Afterwards the ORB... | 5,292,620 |
def __increaseCombinationCounter(root):
""" increase the combination-counter,
which is located in the provided root-node """
if root['type']=='graphroot':
root['combination'] += 1
return root | 5,292,621 |
async def get_complaints(request: Request):
"""Get complains
Get complaints for User.
- If user has role complainer, returns complaints created by this user.
- If user has role aprover, returns complains in status pending
The user have been authenticate!!!.
Args:
request (Request): ... | 5,292,622 |
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- Plot saved under given f... | 5,292,623 |
def supports_color():
"""
Return True if the running system's terminal supports color,
and False otherwise.
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the Windows Registry to see if VT code handling has been enabled
by default, see https://superuser.com/a/13002... | 5,292,624 |
def test_bias_v_row():
"""Test the BiasVRowTask"""
task = bias.BiasVRowTask()
if RUN_TASKS:
task.run(nfiles=2, slots=['S00'], **RUN_OPTIONS) | 5,292,625 |
def make_list_of_model_filenames(model,fc_dates,lt):
"""
returns: flst - list of model files to be opened
dlst - list of dates to be chosen within each file
"""
#fn = make_model_filename_wrapper('mwam4',datetime(2021,1,1,1),1)
flst = []
for d in fc_dates:
fn = make_model_fil... | 5,292,626 |
def mask_to_lbl(mask, label):
"""Convert mask to label image."""
lbl = np.empty(mask.shape, dtype=np.int32)
lbl[mask] = label
lbl[~mask] = -1
return lbl | 5,292,627 |
def make_application_public(application_id, sar_client=None):
"""
Set the application to be public.
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param sar_client: The boto3 client used to access SAR
:type sar_client: boto3.client
:raise... | 5,292,628 |
def test_check_input_not_list():
"""Test that inputs are of type list."""
from simplecalc.calculator import _check_input
from simplecalc.calculator import CalculatorTypeError
with pytest.raises(CalculatorTypeError) as e:
_check_input("Test")
assert "Input must be a list, received: " in str... | 5,292,629 |
def create_report(messages):
"""Compile the final HTML report."""
install_msg, verify_msg, instantupgrade_install_msg, instantupgrade_verify_msg, deonboard_reonboard_msg, remove_msg, reinstall_msg, long_verify_msg, long_status_msg = messages
# summary table
imagesth = ""
resultsth = ""
for imag... | 5,292,630 |
def setup_resources(resources=None):
"""
Call either with a list of resources or a resource string.
If ``None`` is given, get the resource string from the environment.
"""
if isinstance(resources, str) or resources is None:
resources = parse_resources(resources)
from . import support
... | 5,292,631 |
def approx_average_is_average(hand):
"""
:param hand: list - cards in hand.
:return: bool - is approximate average the same as true average?
"""
median = hand[len(hand)//2]
approx_average = (hand[0] + hand[-1])/2
avg = card_average(hand)
return median == avg or approx_average == avg | 5,292,632 |
def test_runner_names():
"""Get iterable of test-runner plugin names."""
return ExtensionManager('cosmic_ray.test_runners').names() | 5,292,633 |
def get_options():
"""Create user interface options."""
user_options = {}
user_options['chassis'] = {'label': 'Chassis',
'type': 'stringList',
'default': 'benzene',
'values': chassis_list}
user_options['center-... | 5,292,634 |
async def test_availability(hass):
"""Ensure that we mark the component available/unavailable correctly."""
await setup_awair(hass)
assert hass.states.get("sensor.awair_score").state == "78"
future = NOW + timedelta(minutes=30)
data_patch = patch(
"python_awair.AwairClient.air_data_latest"... | 5,292,635 |
def test_aerial_photo_extension_added_if_empty_metadata():
"""Tests aerial-photo extension is still added if empty metadata"""
source_path = "test_abc.tiff"
item = stac.Item(source_path)
metadata = {"run": "", "altitude": "", "scale": "", "photo_no": "", "image_anomalies": ""}
metadata_loader_imager... | 5,292,636 |
def compute_dissymmetries(diffables_a, diffables_b):
"""Return a list of dissymmetry from two given diffable lists."""
if not diffables_a and not diffables_b:
return []
dissymmetries = []
for a, b in _outer_join_diffables(diffables_a, diffables_b):
if not a:
dissymmetry = b.... | 5,292,637 |
def getInterestHistory(asset="", isolatedSymbol="", startTime="", endTime="", current="", size="", archived="", recvWindow=""):
"""# Get Interest History (USER_DATA)
#### `GET /sapi/v1/margin/interestHistory (HMAC SHA256)`
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------... | 5,292,638 |
def _add_graph_level(graph, level, parent_ids, names, scores):
"""Adds a levelto the passed graph"""
for i, parent_id in enumerate(parent_ids):
new_node = (level, i)
parent_node = (level - 1, parent_id)
graph.add_node(new_node)
graph.node[new_node]["name"] = names[i]
grap... | 5,292,639 |
def orthonormalize(A):
"""Return an orthonormal basis in which `A` has a sparse representation.
`A` will have support only on the first three elements. The first element
is guaranteed to be proportional to the identity. This basis is
constructed using Gram-Schmidt orthogonalization.
Parameters
... | 5,292,640 |
def probability_plot(data, wt=None, lower=None, upper=None, logscale=True, ax=None, figsize=None,
xlim=None, ylim=(0.01, 99.99), nyticks=15, title=None, xlabel=None, s=2, color='k',
grid=True, axis_xy=None, line=False, plot_style=None, custom_style=None, output_file=None,
... | 5,292,641 |
def get_time_human_readable():
"""
returns well formated time string.
for example: Donnerstag, 21:00
"""
return time.strftime("%A, %H:%M") | 5,292,642 |
def proc_annotation(file_path, ann_dict, split, trimmed, class_to_id_map):
"""Process the annotations and return list of file_paths and corresponding
annotations
Arguments:
file_path (str): File path for the corresponding annotation
ann_dict (dict): The annotation dictionary
spl... | 5,292,643 |
def get_csv_filename(name: str) -> str:
"""
Returns the name of a CSV file corresponding to the input file `name`. If `name` is a CSV
file already (that is: does not have an .xls ending or some extension of this suffix) the
`name` is returned unchanged. If on the other hand `name` is the name of a
s... | 5,292,644 |
def findpeaks(data, spacing=1, limit=None):
"""Finds peaks in `data` which are of `spacing` width and >=`limit`.
:param data: values
:param spacing: minimum spacing to the next peak (should be 1 or more)
:param limit: peaks should have value greater or equal
:return:
"""
len = data.size
... | 5,292,645 |
def test_one_dn_isolate_scm_other_dn():
"""
In this test, one of the DNs cannot communicate with SCM and other DNs.
Other DNs can communicate with each other and SCM .
Expectation : The container should eventually have two closed replicas.
"""
om = cluster.om
scm = cluster.scm
dns = clus... | 5,292,646 |
def parse_command_line():
"""
Parse the command line.
Returns:
Namespace: The parsed command line container.
"""
parser = argparse.ArgumentParser()
# All reference encoders
refcoders = ["ref-1.7",
"ref-2.5-neon", "ref-2.5-sse2", "ref-2.5-sse4.1", "ref-2.5-avx2",
... | 5,292,647 |
def gaussian_kernel(x1, x2, sigma):
"""
Computes the radial basis function
Returns a radial basis function kernel between x1 and x2.
Parameters
----------
x1 : numpy ndarray
A vector of size (n, ), representing the first datapoint.
x2 : numpy ndarray
A vector of size (n, )... | 5,292,648 |
def build(ctx, c, nocache=False, push=False):
"""
Build container images
"""
this_version = get_version()
for container in c:
tag_name = "faabric/{}:{}".format(container, this_version)
if nocache:
no_cache_str = "--no-cache"
else:
no_cache_str = ""
... | 5,292,649 |
def _extractSpecCAP(config, tab, kernelDict, method = 'CAP', diskRadiusArcmin = 4.0, highPassFilter = False,
estimateErrors = True):
"""See extractSpec.
"""
# Define apertures like Schaan et al. style compensated aperture photometry filter
innerRadiusArcmin=diskRadiusA... | 5,292,650 |
def uniform_on_unit_sphere(N, D):
"""Draw ``N`` points uniformly distributed on the surface of a
``D``-dimensional unit sphere.
Example
-------
.. plot::
:include-source:
import matplotlib.pyplot as pl
import bluebell as bb
import bluebell.plot as bbplot
x = bb... | 5,292,651 |
def freq_title_format(freq):
"""
e.g. Frequency: 440 Hz
e.g. Frequency: 15.0 kHz
"""
if freq < 10000:
title = f"Frequency: {round(freq, 1)} Hz"
elif freq >= 10000:
freq = round(freq * 1e-3, 1)
title = f"Frequency: {freq} kHz"
return title | 5,292,652 |
def mat_toeplitz(h, g):
"""
Constructs a Toeplitz matrix from the given sequences
Parameters
----------
h: list[]
A sequence defining the matrix for non-negative indices.
This will define the number of rows.
g: list[]
A sequence defining the matrix for negative indices. ... | 5,292,653 |
def validateShot(msg):
"""Valida tiro dado e retorna uma resposta formatada.
Parameters
----------
msg : str
Mensagem do client.
Returns
-------
response : str
Resposta formatada.
"""
# Pegar linha e coluna do tabuleiro
line = msg[3] # linha
column = msg[4... | 5,292,654 |
def dsift_llc(image_filenames, image_ids):
"""
For each image_id in the list, compute the Dense SIFT feature, LLC coded
with a 10K-dimensional codebook (obtained by subsampling a 100K-dimensional
codebook.
Store the result in the mongo database.
Uses Stanford Vision Group's hedging-1.0 release... | 5,292,655 |
def _normalize_einsum_in_subscript(subscript: str,
in_operand_shape: ShapeT,
index_to_descr: PMapT[str,
EinsumAxisAccess],
index_to_axis_length: PMapT[str,
... | 5,292,656 |
def poincareSeedsLine(POT, nPoints = 500, start=-1, stop=1, center = [0,0,0]):
"""
returns an array of the positions to seed the stream tracing
the positions lie on a line from going from center through the degenerate
torus. start should be negative for the points to start before the degenerate
to... | 5,292,657 |
def caterpillars(path):
"""Caterpillars
Measurements on a sample of Manduca Sexta caterpillars
A dataset with 267 observations on the following 18 variables.
`Instar`
Coded from 1 (smallest) to 5 (largest) indicating stage of the
caterpillar's life
`ActiveFeeding`
Indicator (`Y` or `N`) of whether... | 5,292,658 |
def fetch_adhd(n_subjects=None, data_dir=None, url=None, resume=True,
verbose=1):
"""Download and load the ADHD resting-state dataset.
Parameters
----------
n_subjects: int, optional
The number of subjects to load. If None is given, all the
40 subjects are used.
data... | 5,292,659 |
def modify_openapi() -> Dict[str, Any]:
"""modify_openapi."""
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="MySQL-AutoXtrabackup",
version=f"{VERSION}",
description="Rest API doc for MySQL-AutoXtrabackup",
routes=app.routes,
... | 5,292,660 |
def get_atol(atol=None):
"""Get default numerical threshold for regression test."""
# _TODO: get from env variable, different threshold might
# be needed for different device and dtype
return 1e-20 if atol is None else atol | 5,292,661 |
def path(*parts):
"""
Joins the path parts with the #project_path, which is initialized with the
parent directory of the file that first imported this module (which is
usually the Python plugin file).
"""
path = os.path.join(*parts)
if not os.path.isabs(path):
path = os.path.join(project_path, path)
... | 5,292,662 |
def bootstrap(values, nIter, alpha):
"""
bootstrapping to create error bounds, uses resmapling with replacement of sample size n-4
:param values: n-by-m matrix, n = number of runs to resmaple from, m = observations per run
:param nIter: int, number of resamples
:param alpha: float, percentile bounds... | 5,292,663 |
def resolve_required_interfaces():
"""Helper function to build a map of required interfaces based on the
OpenStack release being deployed.
@returns dict - a dictionary keyed by high-level type of interfaces names
"""
required_ints = deepcopy(REQUIRED_INTERFACES)
if CompareOpenStackReleases(os_r... | 5,292,664 |
def create_run(
logger: Optional[HasuraLogger] = None,
config: Optional[Union[Path, str]] = None,
charts: Optional[List[dict]] = None,
metadata: Optional[Dict] = None,
sweep_id: Optional[int] = None,
load_id: Optional[int] = None,
) -> NewParams:
"""
Creates a new run. It registers the r... | 5,292,665 |
async def stop_signal():
"""
Implements Python's asyncio eventloop signal handler
https://docs.python.org/3/library/asyncio-eventloop.html
Cancels all running tasks and exits the app.
"""
global user_exit
user_exit = True
await cancel_async_tasks() | 5,292,666 |
def generate_bootstrap_sql_bal_erg(header: Header, outputs: List[Output]) -> str:
"""
Bootstrap sql for erg balance tables
Watcher checks latest height in bal.erg_diffs to determine if bootstrapping
is needed and if so, from which height. Here, we set it to same height as core tables
meaning ... | 5,292,667 |
def _gen_id(prefix, suffix=None):
"""
Generates the id
"""
suffix = "-{}".format(suffix) if suffix else ""
return "{prefix}-{uid}{suffix}".format(prefix=prefix, uid=uuid4(), suffix=suffix) | 5,292,668 |
def test_population():
"""
This test will simply ensure that a created Society object has a list of
Person objects, that is of length population_size.
"""
# Set up constants
population_size = 50
connectivity_probability = 0.15
# Create Society object.
society = Society(
popul... | 5,292,669 |
def _add(set, item):
"""Adds an item to the set and returns the set"""
set[item] = _EMPTY
return set | 5,292,670 |
def ensure_symlink (src, dst):
"""Ensure the existence of a symbolic link pointing to src named dst. Returns
a boolean indicating whether the symlink already existed.
"""
try:
os.symlink (src, dst)
except OSError as e:
if e.errno == 17: # EEXIST
return True
raise... | 5,292,671 |
def suntime(date_time,latitude,longitude):
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 21 10:36:23 2017
@author: Roland Proud
"""
import math
T = date_time.timetuple() ### time (today)
## (year, month, day, hour, minutes, seconds)
## lat lon for hobart, tasmania
#lat1 = -42.87
#lon1 = 147.32
lat... | 5,292,672 |
def _get_batch(data, i, seq_len):
"""バッチ毎にデータを取得する
"""
slen = min(seq_len, data.shape[0] - i)
inputs = data[i:i + slen]
target = inputs.copy()
# tensorflowのopに変換
# dataは変数ではないのでconstantとする
return tf.constant(inputs), tf.constant(target) | 5,292,673 |
def calibrate_universal(observations: List, detector, num_radial=2, tangential=True, zero_skew=True,
mirror_offset=None):
"""
Calibrate a fisheye camera using Universal Omni model.
:param observations: List of {"points":(boofcv detections),"width":(image width),"height":(image heigh... | 5,292,674 |
def setup_main_logger(log_level, log_filename):
"""Sets up the global logger of the script"""
global logger
if type(log_level) is not int:
raise TypeError('log_level expects an integer')
elif type(log_filename) is not str:
raise TypeError('log_filename expects a string')
formatter = logging.Formatter('%(asc... | 5,292,675 |
def wrap_with_logs(fn: Optional[Callable] = None, target: str = __name__) -> Callable:
"""Calls the supplied function, and logs whether that
function raised an exception or terminated normally.
This is intended to be used around the top level functions of
processes and threads, where exceptions would n... | 5,292,676 |
def gen_string(parent, name, text):
"""Generate one <string /> element and put into the list of keeps.
Args:
parent: The object that will hold the string.
name: The name to store the string under.
text: The text of the string.
"""
if text:
prev = parent.get('tools:keep', '')
if prev:... | 5,292,677 |
def first_pass(text):
"""
Find links, comments, escaped (or non wiki-formatted text), templates and template arguments
:param text:
:return: list containing 2 lists
(first one gives the locations of links, templates and template arguments,
... | 5,292,678 |
def batch_process_and_mask_ids(
data,
batch_size=32,
shuffle=True,
seq_len=256,
padding='left',
keep='start',
start_token=1,
end_token=2):
"""
Takes data that contains a list of lines in string form, and returns a
generator producing a nump... | 5,292,679 |
def test_that_split_on_dot_can_only_split_on_the_last_one():
"""
config_file.utils.split_on_dot
Ensure that the only_last_dot parameter only splits the input
on the last dot.
"""
assert split_on_dot("test.input.should.only.split.on.last", only_last_dot=True) == [
"test.input.should.only... | 5,292,680 |
def map_url_out(request, env, application, controller,
function, args, other, scheme, host, port, language=None):
"""
Supply /a/c/f (or /a/lang/c/f) portion of outgoing url
The basic rule is that we can only make transformations
that map_url_in can reverse.
Suppose that the... | 5,292,681 |
def add_example_image():
"""Populates the DB with example sketches for debugging purposes."""
example_svg1 = """<svg baseProfile="full" height="72.9483836" version="1.1"
width="76.45813535" xmlns="http://www.w3.org/2000/svg"
xmlns:ev="http://www.w3.org/2001/xml-events" xmln... | 5,292,682 |
def gen_mocs_image(fits_file: str,
outdir: Union[str, Path] = '.',
write: bool = False
) -> Union[MOC, STMOC]:
"""
Generate a MOC and STMOC for a single fits file.
Args:
fits_file: path to the fits file.
outdir: Path to the output dir... | 5,292,683 |
def remove_numbers(s):
"""Removes numbers, including times."""
return re.sub('\d+(:\d*)*(\.\d*)?', ' ', s) | 5,292,684 |
def process_lightcurve_into_numpy_array(hdulist, row, replace_outliers=True):
"""The function is to get the time series and the flux series from the original light curve file."""
## get planetary and stellar parameters
quality = hdulist[1].data['QUALITY']
tess_mag = hdulist[0].header['TESSMAG']
sta... | 5,292,685 |
def main():
"""Do great things."""
pgconn = get_dbconn("idep")
df = get_flowpath_lengths(pgconn)
result_full = compute_daily(df)
with pd.ExcelWriter("daily.xlsx") as writer:
result_full.to_excel(writer, "Single Flowpath-daily", index=False) | 5,292,686 |
def array_preview(name, arr):
"""Helper function for checking out arrays."""
if arr:
logging.info(name.upper())
logging.info("----------------")
logging.info("shape: " + str(np.shape(arr)))
logging.info("first element :")
logging.info(arr[0]) | 5,292,687 |
def florida(path):
"""Florida County Voting
The `Florida` data frame has 67 rows and 11 columns. Vote by county in
Florida for President in the 2000 election.
This data frame contains the following columns:
GORE
Number of votes for Gore
BUSH
Number of votes for Bush.
BUCHANAN
Number... | 5,292,688 |
def char_ngram_count_normalised(text, n, number_of_terms = 0):
"""Returns a list of ngram frequencies given a text
text -- the text from which the word frequencies are to be extracted
n - the number of grams (2 indicates bigram)
number_of_terms -- number of terms to extract
"""
char_... | 5,292,689 |
def entropy_difference_timeseries(usage_distribution, absolute=True, intervals=None):
"""
:param usage_distribution: a CxT diachronic usage distribution matrix
:return: array of entropy differences between contiguous usage distributions
"""
if absolute:
return np.array([abs(d) for d in np.di... | 5,292,690 |
def merge_files(left_file: str, right_file: str, columns: list, keep: str = 'none', keep_missing: str = 'none') -> pd.DataFrame:
"""
Merges two csv files
Parameters:
left_file (str): Path to first file
right_file (str): Path to second file
column (str): Name of column to merge files on
kee... | 5,292,691 |
def transformMeshPosOri(vertices, normals, pos=(0., 0., 0.), ori=(0., 0., 0., 1.)):
"""Transform a mesh.
Transform mesh vertices and normals to a new position and orientation using
a position coordinate and rotation quaternion. Values `vertices` and
`normals` must be the same shape. This is intended to... | 5,292,692 |
def rmse_over_time(pred_time_series, meas_time_series, normalization=None):
""" Calculates the NRMSE over time,
Args:
pred_time_series (np.ndarray): predicted/simulated data, shape (T, d)
meas_time_series (np.ndarray): observed/measured/real data, shape (T, d)
normalization (str_or_None... | 5,292,693 |
def SampleSelection_v2(setOfPoints,nSamples,returnIndicies=False, nTrials=10, debug=False):
"""Using Convex Hull to select boundary points. Filling the rest by performing random selections """
nPoints = setOfPoints.shape[0]
hull = ConvexHull(setOfPoints)
indicies = hull.vertices.tolist()
boundaryPo... | 5,292,694 |
def planFree(world,hand,qtarget):
"""Plans a free-space motion for the robot's arm from the current
configuration to the destination qtarget"""
globals = Globals(world)
cspace = TransitCSpace(globals,hand)
robot = world.robot(0)
qmin,qmax = robot.getJointLimits()
#get the start/goal con... | 5,292,695 |
def test_md033_good_html_comment():
"""
Test to make sure this rule does not trigger with a document that
contains an hTML comment block.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/rules/md033/good_html_comment.md",
]
ex... | 5,292,696 |
def squash_tensor(x, min_val, max_val):
"""Normalize a tensor to a specific range."""
x_np = x.clone().numpy()
sq = np.interp(x_np, (x_np.min(), x_np.max()), (min_val, max_val))
return torch.from_numpy(sq) | 5,292,697 |
def test_downstream_message_sending_via_recipewrapper_with_unnamed_output():
"""Test sending messages via the RecipeWrapper when the current step
does not have named outputs, or any output at all.
"""
def downstream_message(dest, payload, path=()):
"""Helper function to generate expected messag... | 5,292,698 |
def update_version_and_tag_for_release():
"""full process. utilized by root release script."""
print(f'current version is {__version__}.')
if len(sys.argv) > 1:
new_version = sys.argv[1]
else:
try:
new_version = input(
'''what do you want the new version to ... | 5,292,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.