content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_land_fraction(cube, fx_variables):
"""Extract land fraction as :mod:`dask.array`."""
land_fraction = None
errors = []
if not fx_variables:
errors.append("No fx files given.")
return (land_fraction, errors)
for (fx_var, fx_path) in fx_variables.items():
if not fx_path... | 71,700 |
def datasets_startswith(names):
"""
Return a list of strings with dataset names that begin with the given
names.
:param names:
String or tuple of strings.
:return:
List of strings.
"""
# Load dict with info about all the datasets.
info_datasets = load_info_datasets()
... | 71,701 |
def check_given_args_update_alert(args_list):
"""Gets an arguments list and returns an error if all of them are empty
"""
if all(v is None for v in args_list):
raise Exception('No arguments were given to update the alert') | 71,702 |
def mandelbrotCalcSet(w, h, max_iteration=10000, output='mandelbrot_mp.png'):
""" Calculate a mandelbrot set given the width, height and
maximum number of iterations """
image = Image.new("RGB", (w, h))
image_rows = {}
mandelbrot_callable = functools.partial(mandelbrotCalcRow, w=w, h=h, max_it... | 71,703 |
def get_pid_uid_sequences(infile, max_len=5000):
"""
Fetch a hierarchical dictionary with keys [pid][uid] and values which are sequences of actions
:param infile:
:param max_len: maximum length of sequence to store
:return: hierarchical dictionary with keys [pid][uid] and values which are np.ndarray... | 71,704 |
def load_darshan_header():
"""
Returns a CFFI compatible header for darshan-utlil as a string.
:return: String with a CFFI compatible header for darshan-util.
"""
curdir, curfile = os.path.split(__file__)
filepath = os.path.join(curdir, 'data', 'darshan-api.h')
# filepath = os.path.join(cu... | 71,705 |
def randomDatabaseName() -> str:
"""
Generate a unique string for use as a database name.
"""
return f"d{uuid4().hex}" | 71,706 |
def concat_body_paragraphs(body_candidates):
"""
Concatenate paragraphs constituting the question body.
:param body_candidates:
:return:
"""
return ' '.join(' '.join(body_candidates).split()) | 71,707 |
def test_confluence_cloud_space_list_command_when_valid_response_is_returned(requests_mock):
"""
To test confluence_cloud_space_list command when valid response return.
Given:
- command arguments for list space command
When:
- Calling `confluence-cloud-space-list` command
Then:
... | 71,708 |
def home(request):
"""docstring for home"""
return render(request,"home.html",{}) | 71,709 |
def add_master_course_staff_to_ccx_for_existing_ccx(apps, schema_editor):
"""
Add all staff and admin of master course to respective CCX(s).
Arguments:
apps (Applications): Apps in edX platform.
schema_editor (SchemaEditor): For editing database schema i.e create, delete field (column)
... | 71,710 |
def AlbersUsaProjection():
"""
Create function to project coordinates using an Albers USA projection.
"""
# Based on D3's AlbersUSA projection
# https://github.com/mbostock/d3/blob/master/src/geo/albers-usa.js
# http://spatialreference.org/ref/esri/usa-contiguous-albers-equal-area-conic/
lo... | 71,711 |
def _build_generator(X_list, y_list, batch_size, timesteps, input_size, shuffle, positive_weight):
"""
Build looping generator of training batches. Will return the generator and the number of batches in each epoch.
In each epoch, all samples are randomly split into batch_size "chunks", each "chunk" in batch... | 71,712 |
def read_annotation_file(annotation_file_path):
"""
Read all the annotation information from annotated json file
:param annotation_file_path: dir which contains all annotated json file
:return: final_annotation: a dictionary contains all information
"""
final_annotation_dict = {}
files = os... | 71,713 |
def _open_website(url: Optional[str]) -> None:
"""Open a website in the default browser.
:param url: The URL to open
"""
if url:
webbrowser.get().open(url, new=2) | 71,714 |
def merge_tables(version=''):
"""
given hdf5s, pivot and merge them at the same time
"""
df_merged = merge_duplicates_and_pivot(df=None, version=version)
# Fluid balance OUT == hourly urine
df_merged['vm32'] = df_merged['vm24']
output_path = mimic_paths.merged_dir + version + '/reduced/merge... | 71,715 |
def get_fuzzer_stats(stats_filestore_path):
"""Reads, validates and returns the stats in |stats_filestore_path|."""
with tempfile.NamedTemporaryFile() as temp_file:
result = filestore_utils.cp(stats_filestore_path,
temp_file.name,
e... | 71,716 |
def check_package_files(ports):
"""Check port package.sh file for required properties.
Args:
ports (list): List of all ports to check
Returns:
bool: no errors encountered
"""
all_good = True
for port in ports:
package_file = f"{port}/package.sh"
if not os.path.... | 71,717 |
def imu(draw,
header=header(),
orientation=quaternion(),
orientation_covariance=array(elements=float64(), min_size=9, max_size=9),
angular_velocity=vector3(),
angular_velocity_covariance=array(elements=float64(), min_size=9, max_size=9),
linear_acceleration=vector3(),
... | 71,718 |
def combine_sample_standard_deviation(As, n = None, u = None, v = None):
"""Computes the combined sample standard deviation of a group of
`measured_value`s.
Let:
* `g = len(As)`.
* `u_i = As[i].quantity`.
* `s_i = As[i].uncertainty`.
* `n_i = As[i].samples`.
* `n` denote the combined sample ... | 71,719 |
def adjust_learning_rate(optimizer, epoch):
"""
Sets learning rate to default value, decayed by division with 10 every 25 epochs and
updates the lr in the optimizer.
"""
if not epoch % 25 == 0 and epoch > 0:
return
lr = LEARNING_RATE * (0.1 ** (epoch // 25))
for param_group... | 71,720 |
def test_route_table_replace_route_table_association():
"""
Note: Boto has deprecated replace_route_table_association (which returns status)
and now uses replace_route_table_association_with_assoc (which returns association ID).
"""
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.c... | 71,721 |
def hash_password(pwd):
"""
https://passlib.readthedocs.io/en/stable/index.html
:param pwd:
:return:
"""
return _pwd_context.hash(pwd) | 71,722 |
def matchNumbersOnly(value):
"""Match strings with numbers and '.' only."""
if re.match('^[0-9.]+$', value):
return True
return False | 71,723 |
def upload_attachment(page_id, file, comment):
"""
Upload an attachment
:param page_id: confluence page id
:param file: attachment file
:param comment: attachment comment
:return: boolean
"""
if re.search('http.*', file):
return False
content_type = mimetypes.guess_type(fil... | 71,724 |
def read_one(person_id):
"""
This function responds to a request for /api/people/{person_id}
with one matching person from people
:param person_id: Id of person to find
:return: person matching id
"""
# Get the person requested
person = Person.query.filter(Person.person_id ... | 71,725 |
def getPointsProjectedToPlane(pointsArray, planePosition, planeNormal):
"""
Returns points projected to the plane in world coordinate system and in the plane coordinate system,
and an array of booleans that tell if the point was above/below the plane.
pointsArray contains each point as a column vector.
"""
... | 71,726 |
def diff_one_tc(x: int, y: int) -> int:
"""Compute x - y.
This problem has only one test case to make inspecting the specific error message
easier.
"""
return x - y | 71,727 |
def reduce_rational_inequalities(exprs, gen, relational=True):
"""
Reduce a system of rational inequalities with rational coefficients.
Examples
========
>>> x = Symbol('x', real=True)
>>> reduce_rational_inequalities([[x**2 <= 0]], x)
Eq(x, 0)
>>> reduce_rational_inequalities([[x + 2... | 71,728 |
def read(string: str) -> dict:
"""Parse an ordered map file.
:arg string: Content of an ordered map file.
:returns: An ordered map.
"""
data = {}
for line in string.split('\n'):
if line and line[0] not in ('#', ' ', '\t', '\r'):
data = _merge(data, _deserialise(line))
r... | 71,729 |
def _generate_indicators(catalog, validator=None, only_numeric=False,
broken_links=False, verify_ssl=True,
url_check_timeout=1, broken_links_threads=1):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.js... | 71,730 |
def test_single_gpu_model():
"""
Make sure single GPU works (DP mode)
:return:
"""
reset_seed()
if not torch.cuda.is_available():
warnings.warn('test_single_gpu_model cannot run.'
' Rerun on a GPU node to run this test')
return
model, hparams = get_mode... | 71,731 |
def metric_weekday(weekday_1, weekday_2):
"""Calculate the distance between two weekdays as a positive integer.
:param weekday_1: A positive integer between 0 and 6
:param weekday_2: A positive integer between 0 and 6
:returns: The absolute valued distance between two weekdays
:rtype: int
"""
... | 71,732 |
def apply_tweet_text_preprocessing(text: str) -> str:
"""Make Text Preprocessor object and apply some basic techniques to preprocess tweet text.
Args:
- text(str)
Returns:
- preprocessed_text(str)
Note:
- We opt for lemmatizing in this use case, just that the example output looks... | 71,733 |
def test_interrupt(notebook):
""" Test the interrupt function using both the button in the Kernel menu and the keyboard shortcut "ii"
Having trouble accessing the Interrupt message when execution is halted. I am assuming that the
message does not lie in the "outputs" field of the cell's JSON object... | 71,734 |
def addheader(datasets):
"""
The columns of the pandas data frame are numbers
this function adds the column labels
Parameters
----------
datasets : list
List of pandas dataframes
"""
header = get_header()
for i in range(0, len(datasets)):
datasets[i].colu... | 71,735 |
def gain_filt(b, a):
"""Step response from filter (used as initial conditions later)
Parameters
----------
b: ndarray
filter coefficients
a: ndarray
filter coefficients
Returns
-------
zi : ndarray
step response as a vector
"""
# max. length of coefficie... | 71,736 |
def vax_pacient(ime, priimek, cepivo):
"""Funkcija v bazi popravi podatek o cepljenu dolocenega pacienta. Ce osebe ni v bolnici, je nemoremo cepiti. Pravice ima samo zdravnik."""
return None | 71,737 |
def inner_kernel_serial(d_uv, d_u, d_v):
"""Kernel function to do inner product.
Returns a numpy array: the component wise multiplication of
two arrays
"""
n = d_u.shape[0]
i = cuda.grid(1)
if i >= n:
return
d_uv[i] = d_u[i] * d_v[i] | 71,738 |
def read_results_pickle(path):
"""Reads a resultset from a pickle file.
Parameters
----------
path : str
The file path from which results are read
Returns
-------
results : ResultSet
The read result set
"""
with open(path, 'rb') as pickle_file:
return pickle... | 71,739 |
def read_values_part2(file: Path) -> Mapping:
"""
Read netmask and memory values from an input file
:param file: text file
:return: generator of values formatted in a mapping
"""
batch = dict()
for i, l in enumerate(open(file)):
m = TXT_REGEX.match(l)
assert m, f'failed mat... | 71,740 |
def get_sample_mean(values: list) -> float:
"""
Calculates the sample mean (overline x) of the elements in a list
:param values: list of values
:return: sample mean
"""
sample_mean = sum(values) / len(values)
return sample_mean | 71,741 |
def _encode_raw_complex(data, prm):
""" Encode raw complex data."""
payload, content_type = prm.encode_raw(data)
return ResultAlt(payload, identifier=prm.identifier,
content_type=content_type) | 71,742 |
def polyfill_integers(generator, low, high=None, size=None, dtype="int32",
endpoint=False):
"""Sample integers from a generator in different numpy versions.
Parameters
----------
generator : numpy.random.Generator or numpy.random.RandomState
The generator to sample from. I... | 71,743 |
def which(program):
"""This method is not my code, thanks to Jay http://stackoverflow.com/a/377028/248220"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
e... | 71,744 |
def rotate(points, rot_vecs):
"""Rotate points by given rotation vectors.
Rodrigues' rotation formula is used.
Args:
points (array): points to rotate
rot_vecs (TYPE): rotation vector
Returns:
TYPE: rotated points
"""
theta = np.linalg.norm(rot_vecs, axis=1)[:, np.newax... | 71,745 |
def setLocale(locale):
"""Set the locale
if unsupported locale is set, BadLocale is raised."""
if Meta.locales.has_key(locale):
Meta.locale = locale
else :
raise BadLocale, ("Unsupported locale. Locale must be one of: %s" %
', '.join([x for x in Meta.locales.keys() if x])) | 71,746 |
def localadmin(address_book, UserFactory, browser):
"""Create an administrator inside the address book and log in him.
Returns a browser instance.
"""
# Using an administrator defined inside the address book to show that he
# serves fine as administrator.
UserFactory(address_book, 'Arne', 'Adm... | 71,747 |
def sigU(backend: Optional[BackendType] = None,
dtype: Optional[DtypeType] = None) -> tn.Tensor:
"""
Pauli 'up' matrix.
Args:
backend: The backend.
dtype : dtype of data.
Returns:
U : The Pauli U matrix, a tn.Tensor.
"""
vals = [[0., 1],
[0, 0]]
array = np.array(vals,... | 71,748 |
def add_trapeziums(dfmmodel, principe_profielen_bov_df, principe_profielen_ben_df, closed=False):
"""Add trapezium profiles on branches with missing crosssections."""
#siebe 22-6-2021: nu twee dataframes: een voor bovenstrooms een voor benedenstoomse zijde tak
xs = dfmmodel.crosssections
for branch in x... | 71,749 |
def get_one_uniform_value(value_range_or_upper_bound, lower_bound=0):
"""
return a random value from a specified interval or [0, 1]
:param value_range_or_upper_bound: list or upper and lower limits or float of upper bound
:param lower_bound: float, lower limit
:return: single float value
"""
... | 71,750 |
def efficientnet_b2c(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling
for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, de... | 71,751 |
def tapis_user(token: str = Depends(tapis_token)):
"""Get Tapis user profile for the provided token."""
try:
t = _client(token)
except BaseTapyException as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token was not valid: {0}".format(exc... | 71,752 |
def get_device(arg=None):
"""Gets the device from ID arg or given chainer's.
:class:`~pycuda.gpuarray.GPUArray`.
Args:
arg: Value to specify a GPU device.
Returns:
Device object specified by given ``arg``.
The rule of device selection is following.
==========================... | 71,753 |
def add_key():
"""
Repository keyserver is added
"""
tmp_key = "/tmp/key_katoolin.txt"
if os.path.exists(tmp_key):
pass
else:
os.system("apt-key adv --keyserver pgp.mit.edu --recv-keys ED444FF07D8D0BF6")
f = open(tmp_key, "wb")
f.write("katoolin\n")
f.close()
print green + "\n[+] Add keyserver\n" + re... | 71,754 |
def read_csv_into_df_with_header(csv: str):
"""
and also set datatimeindex csv has to have a column as 'DateTime'
Parameters
----------
csv :
Returns
-------
pd.DataFrame
"""
df = pd.read_csv(csv, na_values=['-9999'])
df['DateTimeIndex'] = pd.to_datetime(df['DateTime'])
... | 71,755 |
def find_node_named_graph(dataset, node):
"""
Search through each graph in a dataset for one node, when it finds it, returns the graph it is in
:param dataset:
:param node:
:return:
"""
if isinstance(node, rdflib.Literal):
raise RuntimeError("Cannot search for a Literal node in a dat... | 71,756 |
def test_metric_performance():
""" unittest entry for metric performance benchmarking """
# Each dictionary entry is (metric_name:(kwargs, DataGenClass))
metrics = [
('acc', ({}, MetricDataGen)),
('top_k_acc', ({'top_k': 5}, MetricDataGen)),
('F1', ({}, F1MetricDataGen)),
('P... | 71,757 |
def test_cherwell_get_one_step_actions_command(mocker, requests_mock):
"""
When:
Execute cherwell-get-one-step-actions-for-business-object.
Then:
Validate the command results is correct.
"""
mocker.patch.object(demisto, 'args', return_value={'busobjectid': '6dd53665'})
mocker.pat... | 71,758 |
def iqr(data_list):
""" Interquartile range of the data
Inputs:
data_list - a list of floats
Outputs:
val - The interquartile range of the data
"""
n = count(data_list)
cnt = n//2
if cnt ==0:
return 'NaN'
data_list.sort()
l_half = data_list[:cn... | 71,759 |
def _get_prediction(outputs):
"""Checks if multiple outputs were provided, and selects"""
if isinstance(outputs, (list, tuple)):
return outputs[0]
return outputs | 71,760 |
def plot_gb_mean_errorbar(df_m, df_s):
"""
In:
df_m: results of df.groupby().mean() renamed to have mean in col names
df_s: result of df.groupby().std() renamed to have std in col names
Returns:
list of CustomVis objects
"""
# tog = df_m.join(df_s, lsuffix=" (mean)", rsu... | 71,761 |
def Sync(skia_revision=SKIA_REV_DEPS, chrome_revision=CHROME_REV_LKGR,
fetch_target=DEFAULT_FETCH_TARGET,
gyp_defines=None, gyp_generators=None):
""" Create and sync a checkout of Skia inside a checkout of Chrome. Returns
a tuple containing the actually-obtained revision of Skia and the actually-
... | 71,762 |
def bot_answer(user_input):
"""
This function checks if the user input exists
in the database and returns an answer. If the
user input does not exists, it searches for
for something similar to the user input and returns an answer.
"""
answer = switchboard.DB_getQanswer(user_input)
if ans... | 71,763 |
def version(ctx, key):
"""Get version"""
ctx.obj["output"](get_version(key)) | 71,764 |
def test_get_key(software_hive):
"""
# Refers to https://github.com/mkorman90/regipy/issues/144
"""
registry_hive = RegistryHive(software_hive)
# We verify the registry headers are similar, because this is the same subkey.
assert registry_hive.get_key('ODBC').header == registry_hive.root.get_sub... | 71,765 |
def _setTextContent(df, txt_id, txt_content):
"""
Set the arbitrary text content.
Args:
df: DataFrame-initial information.
txt_id: str-the text id.
txt_content: str-the text content.
Returns:
df_temp: DataFrame-information after updates.
"""
df_TextDa... | 71,766 |
def sheet(request, ally_id):
"""
Alliance sheet
"""
request_alliance = requests.get(GLOBAL_URL+f"/{ally_id}", headers=global_headers(request))
if request_alliance.status_code != 200:
return render_error(request_alliance)
return render(request, "alliance/sheet.html",{
"changed_sc... | 71,767 |
def initWindKernel(direction, speed, c1):
"""
Function to generate the kernel for wind probabilities
to apply into the lattice transitions.
This version is for Moore's neighborhood only
parameters
----------
direction: int, float
Respect to a horizontal axis, the angle in which the... | 71,768 |
def pprint_diff(first, second, first_name='first', second_name='second'):
"""Compare the pprint representation of two objects and yield diff lines."""
return difflib.unified_diff(
pprint.pformat(first).splitlines(),
pprint.pformat(second).splitlines(),
fromfile=first_name, tofile=second_name, line... | 71,769 |
def declare_variable(name, shape, initializer):
"""Helper to create a variable."""
return tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) | 71,770 |
def unhover(i):
"""
Show figure image when figure is unhovered.
i: glimpse number
iqs: list of images and attention windows
"""
iqs[i][0].data_source.data["image"][0] = data["img"]
iqs[i][1].data_source.data = data["rects"][i]
push_notebook(handle=handle) | 71,771 |
def test_resume_module_build_failed_first_component(mock_config, tmpdir):
""" We test to resume the module build from the first failed component """
cwd = tmpdir.mkdir("workdir").strpath
rootdir = None
mock_cfg_path = get_full_data_path("mock_cfg/fedora-35-x86_64.cfg")
external_repos = []
build... | 71,772 |
def delete_live_instance(live_instance_id=None):
"""
Delete a live streaming instance
:param live_instance_id:
:return: boolean
"""
url = get_api_base() + '/livestream/%d' % live_instance_id
return RestClient.delete(url=url, headers=create_headers()) | 71,773 |
def load_data(train_size=10000, test_size=2000, load_challenge=False, create_matrices=False, generate_data=False,
create_pickle_file=True, mode="ltc", min_track_prior= 0.0):
""" Fixed Path Names """
data_folder = os.path.join(os.getcwd(), 'data/mpd.v1/data/')
challenge_file = os.path.join(os.... | 71,774 |
def inc(i):
"""Increments number.
Simple types like int, str are passed to function by value (value is copied to new memory slot).
Class instances and e.g. lists are passed by reference."""
i += 1
return i | 71,775 |
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
pass | 71,776 |
def test_linkedlist_bind():
"""Test monadic bind of LinkedList
Laws alone don't guarantee the desired behavior
"""
def f(x):
return Cons(x + 100, lambda: Cons(x + 200, lambda: Nil))
xs = Cons(10, lambda: Cons(20, lambda: Nil))
expected = Cons(
110,
lambda: Cons(
... | 71,777 |
def SoftmaxCrossEntropy(inputs, axis=1, normalization='FULL', **kwargs):
"""Compute the softmax cross entropy with given logits and one-hot labels.
**Type Constraints**: *float32*
Parameters
----------
inputs : sequence of Tensor
The inputs, represent [logits, labels].
axis : int, opti... | 71,778 |
def test_scenario_outline2_fr_from_string():
"""
Language: FR -> Scenario.from_string, with scenario outline, second case
"""
scenario = parse_scenario(OUTLINED_SCENARIO2, language="fr")
assert scenario.name == "Ajouter 2 nombres"
assert scenario.outlines == (
{"input_1": "20", "input... | 71,779 |
def checkForDonorWithRegion(op, graph, frm, to):
"""
Confirm donor mask exists and is selected by a SelectRegion
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
@t... | 71,780 |
def is_symbolic_tensor(tensor):
"""Returns whether a tensor is symbolic (from a TF graph) or an eager tensor.
A Variable can be seen as either: it is considered symbolic
when we are in a graph scope, and eager when we are in an eager scope.
Arguments:
tensor: A tensor instance to test.
Returns:
Tru... | 71,781 |
def execute_overload_ceilometer(config, state, overloaded_host, vm_uuids):
"""Process an overloaded host: migrate the selected VMs from it.
Same as "execute_overload" except measures are collected by ceilometer.
:param config: A config dictionary.
:type config: dict(str: *)
:param state: A state ... | 71,782 |
def simulate_lognormal(mu_lim, sigma_lim, count_lim):
"""Simulates log normal data of a specified size
Parameters
----------
mu_lim : list, float
The limits for selecting a mean for the log normal distributions
sigma_lim : list, float
The limits for selecting a standard deivation fo... | 71,783 |
def extract_video_id(string):
"""Extract what looks like a YouTube video id from a string"""
if len(string) == 11:
return string
matches = re.search("v?=(.{11})", string)
if matches is not None:
return matches.group(1)
matches = re.search(r"youtu\.be/(.{11})", string)
if matches ... | 71,784 |
def get_visible_cards(cards1, cards2):
"""Return a list of the intersection of cards1 and cards2; call only on
visible cards!"""
return [card for card in cards1 if card['name'] in names(cards2)] | 71,785 |
def phases_exponential_fit(phases_points, t, X, one_order):
"""
:Authors:
Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu>
:License:
MIT
:Version:
1.0
:Date:
2021-03-17
:Repository: https://github.com/thrash-lab/sparse-growth-curve
"""
all_starting_time=phases_poi... | 71,786 |
def ascii(value):
"""Return the string of value
:param mixed value: The value to return
:rtype: str
"""
return '{0}'.format(value) | 71,787 |
def run_experiment(params, rt_environment, trial_out_dir, n_generations=100,
save_results=False, silent=False, args=None):
"""
The function to run the experiment against hyper-parameters
defined in the provided configuration file.
The winner genome will be rendered as a graph as we... | 71,788 |
def find_closest_date(date, list_of_dates):
"""
This is a helper function that works on Python datetimes. It returns the closest date value,
and the timedelta from the provided date.
"""
match = min(list_of_dates, key = lambda x: abs(x - date))
delta = match - date
return match, delta | 71,789 |
def FormatDateTime(duration):
"""Return RFC3339 string for datetime that is now + given duration.
Args:
duration: string ISO 8601 duration, e.g. 'P5D' for period 5 days.
Returns:
string timestamp
"""
# We use a format that preserves +00:00 for UTC to match timestamp format
# returned by containe... | 71,790 |
def select_all_shapes(layer):
"""Select all shapes in the current view slice."""
if layer._mode in (Mode.DIRECT, Mode.SELECT):
layer.selected_data = set(np.nonzero(layer._data_view._displayed)[0])
layer._set_highlight() | 71,791 |
def is_depth(da, loc="any"):
"""Tell if a data array is identified as depths
Parameters
----------
da: xarray.DataArray
Return
------
bool
See also
--------
is_lon
is_lat
is_altitude
is_level
is_time
xoa.cf.CFCoordSpecs.match
"""
return xcf.get_cf_s... | 71,792 |
def num_bits_64(i):
"""Counts the bits in a given integer.
>>> num_bits_64(7)
3
>>> num_bits_64(8)
1
>>> num_bits_64(0b1100110000000000000000000000000)
4
"""
# & here converts negative integers to unsigned representation first,
# so we get the correct number of bits.
return bin(i & BITS_64).count... | 71,793 |
def test_with_valid_nulls_order():
"""Return column with a specific filter."""
col = ColumnDT(User.name, nulls_order='nullslast')
if col.nulls_order != 'nullslast':
raise AssertionError() | 71,794 |
def replace_str_index(text, index=0, replacement=''):
"""
Utility function
:param text:
:param index:
:param replacement:
:return:
"""
return '%s%s%s' % (text[:index], replacement, text[index + 1:]) | 71,795 |
def multipart_upload(s3server, bucket, s3_key_name, tarball, mb_size):
"""Upload large files using Amazon's multipart upload functionality.
"""
cores = multiprocessing.cpu_count()
def split_file(in_file, mb_size, split_num=5):
prefix = os.path.join(os.path.dirname(in_file),
... | 71,796 |
def discover_channels(path, serial_number, callback, cancellation_token, channel_termination_token, logger):
"""
Scans for USB devices that match the path spec.
This function blocks until cancellation_token is set.
Channels spawned by this function run until channel_termination_token is set.
"""
if path == ... | 71,797 |
def from_timestamp(timer: int) -> datetime.datetime:
"""
Converts timestamp to `datetime.datetime`
"""
return datetime.datetime.utcfromtimestamp(timer) | 71,798 |
def arg(name: str, value: Any) -> str:
"""
>>> arg("x", 1)
'`x`: <builtins.int> 1'
"""
return f"{tick(name)}: {val(value)}" | 71,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.