content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def import_catalog(json_body):
"""Upload up to 5000 events using catalogItems.import()."""
event_count = \
len(json_body['inputConfig']['catalogInlineSource']['catalogItems'])
print('Importing ' + str(event_count))
import_request = service.projects().locations().catalogs().catalogItems()\
.import_(... | 56,000 |
def create_mesh_from_trace(linestring,
zmax: Union[float, int],
zmin: Union[float, int],
):
"""
Args:
linestring (shapely.geometry.LineString):
zmax:
zmin:
Returns:
"""
from scipy.spatial.qhul... | 56,001 |
def find_nearest(array,value):
"""
Find nearest value in array
"""
idx = np.searchsorted(array, value, side="left")
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return array[idx-1]
else:
return array[idx] | 56,002 |
def handle_context_opt(ctx, param, value):
"""Handle eager CLI options to configure context.
The eager options are evaluated directly during parsing phase, and can
affect other options parsing (like required/not).
The only side effect of consuming these options are setting attributes
of the global... | 56,003 |
def make_minimal_feature_set(feature_definitions, features):
"""Reduce feature_definitions to the minimum necessary features
Parameters
----------
feature_definitions : list of dict
Feature definitions from the elasticsearch LTR plugin
features : list of str
List of feature names re... | 56,004 |
def nonroster_player_attr_by_id(player_id, attribute):
"""Returns the attribute of a non-roster player via the NHL People API.
Args:
player_id (str): Player unique identifier (IDXXXXXXX)
attribute (str): Attribute from roster dictionary.
Returns:
string: Attribute of the person req... | 56,005 |
def merge_aug_bboxes(aug_bboxes, aug_scores, img_metas, rcnn_test_cfg):
"""Merge augmented detection bboxes and scores.
Args:
aug_bboxes (list[Tensor]): shape (n, 4*#class)
aug_scores (list[Tensor] or None): shape (n, #class)
img_shapes (list[Tensor]): shape (3, ).
rcnn_test_cfg... | 56,006 |
def local_helper_exists(production=False):
"""This function checks to see if a helper file is present in the ``local/`` directory.
.. versionadded:: 4.1.0
:param production: Defines whether or not the helper file is associated with a Production environment
:type production: bool, None
:returns: Bo... | 56,007 |
def is_provided_and_is_date_less_than_a_year_ago(value):
"""Returns True if the date value is provided and within the last year."""
if not value:
return False
return _is_provided_and_is_date_in_the_past(
value,
) and (
value > date.today() - relativedelta(years=1)
) | 56,008 |
def load_data(train_data, valid_data, test_data, user_review, item_review, user_rid, item_rid, stopwords):
"""
Loads and preprocessed data for the MR dataset.
Returns input vectors, labels, vocabulary, and inverse vocabulary.
"""
# Load and preprocess data
u_text, i_text, u_text_old, i_text_old,... | 56,009 |
def filter_records(records, key, operator, test_value):
"""Removes all records from a list of records, which do not
fulfill the specified criteria.
"""
filtered_records = []
for record in records:
# @shoeffner: missing , and :
if isinstance(record[key] int)
test_value = i... | 56,010 |
def _numeric_range_is_disjoint(
bin_ranges: FrozenSet[Range],
numeric_accuracy: float
) -> bool:
"""
A method that checks if the numeric range bins are disjoint and don't contain gaps.
:param bin_ranges: the set of ranges we want to check
:param numeric_accuracy: the minimum difference ... | 56,011 |
def large_state_termination(state, action, next_state=None):
"""Termination condition for environment."""
if not isinstance(state, torch.Tensor):
state = torch.tensor(state)
if not isinstance(action, torch.Tensor):
action = torch.tensor(action)
done = torch.any(torch.abs(state) > 200, d... | 56,012 |
def get_filtered_properties_df(prefix: str, prop: str, **kwargs) -> pd.DataFrame:
"""Extract a single property for each term."""
path = prefix_directory_join(prefix, 'cache', 'properties', f"{prop}.tsv")
@cached_df(path=path, dtype=str)
def _df_getter() -> pd.DataFrame:
obo = get(prefix, **kwar... | 56,013 |
def ormolu_test(name, srcs, **kwargs):
"""Generates a test rule for each Haskell source file.
Then places all of them into a single test suite.
Args:
name: Name of the test suite.
srcs: Haskell source files to run ormolu on.
kwargs: Additional keyword arguments to pass to the `test_... | 56,014 |
def main(username,password):
""" Opens FacebookClient and posts random status """
username, password = manager.session()
fb = FacebookClient(username,password)
humanRandom.searchEngineWaitTime()
print("doing something fun...")
fb.set_status()
fb.destroy() | 56,015 |
def to_1d(arg, raw=False):
"""Reshape argument to one dimension.
If `raw` is `True`, returns NumPy array.
If 2-dim, will collapse along axis 1 (i.e., DataFrame with one column to Series)."""
if raw or not checks.is_array(arg):
arg = np.asarray(arg)
if arg.ndim == 2:
if arg.shape[1]... | 56,016 |
def guard_restart():
""" Callback for config options requiring a restart """
global RESTART_REQ
sabnzbd.RESTART_REQ = True | 56,017 |
def _load_model_from_local_file(path, serialization_format):
"""Load a scikit-learn model saved as an MLflow artifact on the local file system.
:param path: Local filesystem path to the MLflow Model saved with the ``sklearn`` flavor
:param serialization_format: The format in which the model was serialized.... | 56,018 |
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the patch.
Parameters :
img_0, img_1 : two images being compared
u : displacement vector between patches
x, y ... | 56,019 |
def instance_name_from_zip(path):
"""Determines the instance filename within a SEC EDGAR zip archive."""
re_instance_name = re.compile(r'.+-\d{8}\.xml')
for name in zipfile.ZipFile(path).namelist():
if re_instance_name.fullmatch(name):
return name
raise RuntimeError('Zip archive does... | 56,020 |
def delete_load_blanacer(ilb_name):
"""
Delete a deployed Internal Load Balancer
:param ilb_name:
:return: None or str
"""
response = describe_load_balancers(ilb_name)
for i in response['LoadBalancerDescriptions']:
if 'LoadBalancerName' in i:
elb.delete_load_balancer(Loa... | 56,021 |
def get_arguments():
"""Obtains command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--inputs',
required=True,
nargs='+',
metavar='INPUT',
help='read Q2 inputs from Feather files %(metavar)ss')
parser.add_argument(
'--outp... | 56,022 |
def crosscorrelation(a, b):
"""
Calculates a normalized cross-correlation between two vectors.
Returns the Pearson correlation coefficient.
"""
from scipy.stats import pearsonr
return (pearsonr(a, b))[0] | 56,023 |
def hypothesis_test_v1(unknown_agent_actions, known_agent_dists,
update_times, num_actions, num_samples=50,
score_funcs_list = [z1_score_function, z2_score_function, z3_score_function],
weight_value=(1.0/3)):
"""
Calculate p-values for various timesteps of an i... | 56,024 |
def area_hexagon(r):
"""Return the area of a regular hexagon with side length R."""
return r * r * 3 * sqrt(3) / 2 | 56,025 |
def index2state(Is, n, Juv, Jdv=None):
"""
Returns state with a given index
Parameters
----------
Is : ndarray
list of indices
n : int
number of sites
Juv : ndarray
Lin table of spin-up states
Jdv : ndarray
Lin table for spin-down states
"""
Nu = ... | 56,026 |
def test_endpoints_status_code(client):
"""Test all endpoints and wrong url status codes."""
assert client.get('/').status_code == 200
assert client.get('/boardgames').status_code == 200
assert client.get('/boardgames/2').status_code == 200
assert client.get('/categories').status_code == 200
ass... | 56,027 |
def headers_ok(meta):
"""check that headers are 'name' or end with c/d/ll"""
meta_fh = open(meta)
headers = meta_fh.readline().rstrip().split('\t')
return headers[0] == 'name' and \
all(map(lambda s: re.search(r'\.(c|d|ll)$', s), headers[1:])) | 56,028 |
def rasterizeSSURGOFeatures(config, outputDir, featureFilename, featureLayername, featureAttrList, \
getResolutionFromRasterFileNamed=None, rasterResolutionX=None, rasterResolutionY=None):
""" Create raster maps, in GeoTIFF format, for SSURGO attributes associated with SSURGO MapunitPoly... | 56,029 |
def get_fontawesome_panel_express() -> str:
"""Converts the official css file at FONTAWESOME_CSS_URL into it's panel
representation
Returns:
str -- [description]
"""
with urllib.request.urlopen(FONTAWESOME_CSS_URL) as file:
fontawesome_css = file.read().decode("utf-8")
... | 56,030 |
def delete_mysql_data(port):
""" Purge all data on disk for a MySQL instance
Args:
port - The port on which to act upon on localhost
"""
for dir_key in DIRS_TO_CLEAR:
directory = get_cnf_setting(dir_key, port)
if not os.path.isdir(directory):
directory = os.path.dirname(... | 56,031 |
def search_index_for_variable(index,parent_tag,variable_expression,resolve=False):
"""
:param str parent_tag: tag created of colon-separated identifiers, e.g. "mymodule" or "mymodule:mysubroutine".
%param str variable_expression% a simple identifier such as 'a' or 'A_d' or a more complicated tag representin... | 56,032 |
def has_number(name):
"""判断名name内是否出现了数字(包括中文的数字)"""
if bool(re.search(r'\d',name)):
return True
num_str = ['一','二','三','四','五','六','七','八','九','十']
for s in num_str:
if s in name:
return True
return False | 56,033 |
def validate_entity_arn(entity_arn):
"""Validate entity ARN"""
# account_number = SESSION.client('sts').get_caller_identity()["Account"]
# Roles are valid: arn:aws:iam::842337631775:role/1S-Admins
# arn:aws:sts::281782457076:assumed-role/1S-Admins/alex
# Users are invalid: arn:aws:... | 56,034 |
def seed_student_proposal(request, i):
"""Returns the properties of a new student proposal.
"""
ensureUser()
org = Organization.get_by_key_name('google/gsoc2009/org_%d' % i)
mentor = Mentor.get_by_key_name('google/gsoc2009/org_%d/mentor' % i)
user = User.get_by_key_name('user_%d' % i)
student = Student.g... | 56,035 |
def get_data_f2(x, a, b, c, d, noise):
"""
return function y = a*exp(-(x-b/c)^2) + d + noise
"""
y = a * np.exp(-(
(x - b) / c)**2) + d + noise * np.random.rand(x.shape[0], x.shape[1])
return y | 56,036 |
def password2():
"""
Asks the user for a username and password
compares these to the stored username and password.
Displays a message to inform the user if their username or password
are incorrect and whether they have access
uses a Boolean flag
:return: none
"""
username = "morty"
... | 56,037 |
def subpixel_contours(da,
z_values=[0.0],
crs=None,
affine=None,
attribute_df=None,
output_path=None,
min_vertices=2,
dim='time',
errors='ignore... | 56,038 |
def collect_hosts(hosts):
"""Collect a set of hosts and an optional chroot from a string."""
host_ports, chroot = hosts.partition("/")[::2]
chroot = "/" + chroot if chroot else None
result = []
for host_port in host_ports.split(","):
# put all complexity of dealing with
# IPv4 & IPv... | 56,039 |
def process_frame(img, frame, face_cascade):
"""
Determine whether the current frame contains the faces of people from our database
"""
global ready_to_detect_identity
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# Loop through all the f... | 56,040 |
def GetMtdDevForNameOrNone(partname):
"""Find the mtd# for a named partition.
In /proc/mtd we have:
dev: size erasesize name
mtd0: 00200000 00010000 "cfe"
mtd1: 00200000 00010000 "reserve0"
mtd2: 10000000 00100000 "kernel0"
mtd3: 10000000 00100000 "kernel1"
Args:
partname: the partition to ... | 56,041 |
def WaitForApps(handles: AppHandles):
"""Waits for the applications in the experiment to finish.
This function first waits for the RocksDB application (and, if the
Antagonist runs in this experiment, the Antagonist application) to finish.
This app (or apps) finish on their own since they set a timer and exit
... | 56,042 |
def PIoN2SolNTableConvert (inUV, outSNVer, NITable, pos, err):
"""
Evaluate Ionospheric model table at pos and convert to SN table
Returns resultant SN table
* inUV = UV data for output SN table.
Control parameters on inUV info member:
========== ================ =================... | 56,043 |
def hasp(
revisions: pd.DataFrame,
window: int = 12,
) -> pd.DataFrame:
"""Apply the half window splice revision extension method.
Parameters
----------
revisions : pandas DataFrame
A DataFrame of the rolling revisions. The values only need to be
correct for the size of the ... | 56,044 |
def append_annot_case_tags(ibs, aid_list, tag_list):
"""
Generally appends tags to annotations. Careful not to introduce too many
random tags. Maybe we should just let that happen and introduce tag-aliases
Note: this is more of a set add rather than a list append
TODO: remove
"""
# Ensure ... | 56,045 |
def get_vignette_mask(image, percent_vignetted=5):
"""Convert a well-exposed image (ideally a brightfield image with ~uniform
intensity) into a mask delimiting the image region from the dark,
vignetted borders of the image.
percent_vignetted: percent (0-100) of pixels estimated to be in the vignetted r... | 56,046 |
def plots(hit, hor_fans, mlab):
"""
Plot rays from focal point to ``hit`` points. Plot triangulated surface for each fan in
``hor_fans``.
"""
color = next(colors)
if hit:
## Use triangles to show mesh rays from the focal point to the hit point.
hit_t = np.array(hit).tr... | 56,047 |
def cohort_to_int(year, season, base=16):
"""cohort_to_int(year, season[, base])
Converts cohort tuple to a unique sequential ID.
Positional arguments:
year (int) - 2-digit year
season (int) - season ID
Keyword arguments:
base (int) - base year to treat as 0
Returns:
... | 56,048 |
def delete_project(project_ids: list) -> bool:
"""
Deletes project, groups, tasks and results from Firebase and Postgres.
"""
for project_id in project_ids:
logger.info(
f"Delete project, groups, tasks and results of project: {project_id}"
)
fb_db = auth.firebaseDB()... | 56,049 |
def set_data_format(array_values):
"""
Check and set the corresponding format for each value
:param list[list[str]] array_values: list of values
:return: list[list[str]]: array formatted
"""
formatted_data = []
for d in array_values:
values = []
for v in d:
# Try... | 56,050 |
def dict_of_transition_matrix(mat):
""" Convert a transition matrix (list of list or numpy array) to a dictionary mapping (state, state) to probabilities (as used by :class:`pykov.Chain`)."""
if isinstance(mat, list):
return {(i, j): mat[i][j] for i in range(len(mat)) for j in range(len(mat[i]))}
el... | 56,051 |
def taxii2_collection_by_id(api_root: str, collection_id: str) -> Response:
"""
Defines TAXII API - Collections:
Get Collection section (5.2) `here for v.2.0
<http://docs.oasis-open.org/cti/taxii/v2.0/cs01/taxii-v2.0-cs01.html#_Toc496542736>`__
and `here for v.2.1 <https://docs.oasis-open.org/cti/ta... | 56,052 |
def argmaxn(value_list, n, order='desc'):
"""
Return the index of top n elements in the list if order is set to 'desc',
otherwise return the index of n smallest elements
:param value_list: a list containing all values
:type value_list: list, array
:param n: the number of the elements to select
... | 56,053 |
def nms(args, classes, offsets, anchors):
"""Perform NMS (Algorithm 11.12.1).
Arguments:
args : User-defined configurations
classes (tensor): Predicted classes
offsets (tensor): Predicted offsets
Returns:
objects (tensor): class predictions per anchor
indexe... | 56,054 |
def main():
"""Chechs the specified args and calls the appropriate method.
"""
args = get_args()
if args.version:
sys.exit(args.version)
if args.source:
items_list = get_data_from_non_local(args.source)
else:
items_list = get_data_from_local()
if args.date:
... | 56,055 |
def extract_features(data_frame: pd.DataFrame) -> pd.DataFrame:
"""Obtains training features from the data frame containing subreddit data.
Params:
- data_frame (pd.DataFrame): data frame containing subreddit data
Returns:
- features (pd.DataFrame): the training features returned by the data frame... | 56,056 |
def get_bugzilla_bug(bugzilla_url, bug_id):
"""
Read bug XML, return all fields and values in a dictionary.
"""
bug_xml = _fetch_bug_content(bugzilla_url, bug_id)
return parse_bug_fields(bug_xml) | 56,057 |
def get_characters_character_id(*, character_id, if_none_match=None):
"""
:param character_id: An EVE character ID
:param if_none_match: ETag from a previous request. A 304 will be returned if this matches the current ETag
Public information about a character
---
Alternate route: `/dev/character... | 56,058 |
def _funded_by(record, extra_data):
"""Check if publication has "Funded by SCOAP3" marking *in pdf(a) file* """
patterns = ['funded.?by.?scoap3?', ]
return __find_regexp_in_pdf(extra_data, patterns) | 56,059 |
def profile(request, profile_slug):
"""
Display profile details.
"""
speaker_profile = get_object_or_404(AttendeeProfile, slug=profile_slug)
if not profile_page_visible(profile=speaker_profile, for_user=request.user):
return TemplateResponse(request, "conference/profiles/profile_unavailable... | 56,060 |
def save_file(filename, contents):
"""Save a file from the editor"""
if not filename:
return 0, 0
with open(filename, 'w') as f:
f.write(contents)
return len(contents), hash(contents) | 56,061 |
def mapping_rules(service, backend_orig, backend_new):
"""
Adds the "/" mapping rule to both backends.
"""
proxy = service.proxy.list()
proxy.mapping_rules.delete(proxy.mapping_rules.list()[0]["id"])
orig_metric = backend_orig.metrics.list()[0]
new_metric = backend_new.metrics.list()[0]
... | 56,062 |
def configure_tray(tray, params, stats, logger):
"""
Configures the I3Tray instance: adds modules, segments, services, etc.
Args:
tray (I3Tray): the IceProd tray instance
params (dict): command-line arguments (and default values)
referenced as dict entries; see a... | 56,063 |
def GetDockerImageFromTagOrDigest(image_name):
"""Gets an image object given either a tag or a digest.
Args:
image_name: Either a fully qualified tag or a fully qualified digest.
Defaults to latest if no tag specified.
Returns:
Either a docker_name.Tag or a docker_name.Digest object.
"""
if no... | 56,064 |
def line_label(ax, pos, label, dir='v', loc='top', xx=None, yy=None, ha=None, va=None,
line_kwargs={}, text_kwargs={}, dashes=None, rot=None):
"""Plot a vertical line, and give it a label outside the axes.
Arguments
---------
ax : `matplotlib.axes.Axes` object
Axes on which to pl... | 56,065 |
def fixture_vm_dir(request: FixtureRequest, test_dir) -> Generator[str, None, None]:
"""
Make and return a function that sets up the temporary directory with a
Vagrantfile. By default, use VM_VAGRANTFILE.
vagrantfile: path to a vagrantfile to use as Vagrantfile in the testing temporary directory.
"... | 56,066 |
def hashfile(path: str, blocksize: int = 65536) -> Tuple[str, str]:
"""Calculate the MD5 hash of a given file
Args:
path ()str, os.path): Path to the file to generate a hash for
blocksize (int, optional): Memory size to read in the file
Default: 65536
Ret... | 56,067 |
def generate_bandit_samples(logging_policy, syn, k=5):
"""Generates partial-labeled bandit samples with the logging policy.
Arguments:
k: The number of items to be sampled for each user.
"""
logging_policy.set_binary(False)
with torch.no_grad():
feats = {}
feats["user_feats"... | 56,068 |
def update_by_table_column(table_name, column, variable, db_url=None
,connection_func=None):
"""
updates a variable (identified by name) in the warehouse database
Keyword Parameters:
table_name -- String, table which the variable to update belongs to
column -- String, r... | 56,069 |
def get(key):
"""
Retrieve a constant by key. This is just a short cut into a dictionary.
Parameters
----------
key : Python string or unicode
Key in dictionary in `constants`
Returns
-------
constant : `~astropy.units.Constant`
See Also
--------
_constants : Cont... | 56,070 |
def test_single_null(setup_teardown_file):
"""Single-element selection with [()] yields ndarray."""
f = setup_teardown_file[3]
dset = f.create_dataset('x', (1,), dtype='i1')
out = dset[()]
assert isinstance(out, np.ndarray)
assert out.shape == (1,) | 56,071 |
def test_convT_rf():
"""
CommandLine:
xdoctest -m ~/code/netharn/tests/test_receptive_feild.py test_convT_rf
"""
# Test that we always invert whatever weird crazy thing we do
import netharn as nh
rng = np.random.RandomState(3668028386)
ntrials = 100
M = 9
for _ in ub.ProgIt... | 56,072 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Coinbase sensors."""
if discovery_info is None:
return
if "account" in discovery_info:
account = discovery_info["account"]
sensor = AccountSensor(
hass.data[DATA_COINBASE], account["name"],... | 56,073 |
async def async_id_unknown_devices(config_dir):
"""Send device ID commands to all unidentified devices."""
await devices.async_load(id_devices=1)
for addr in devices:
device = devices[addr]
flags = True
for name in device.operating_flags:
if not device.operating_flags[nam... | 56,074 |
def compute_qvalues(state_action_reward: np.ndarray, discount: float) -> np.ndarray:
"""Computes the Q-values of `state_action_reward` under deterministic dynamics."""
transitions = build_transitions(*state_action_reward.shape)
reward = build_reward(state_action_reward)
return reward | 56,075 |
def get_args( ):
""" Get args from Argparse """
parser = argparse.ArgumentParser(
description=description,
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument( "-i", "--input",
required=True,
help="HUMAnN genefamilies... | 56,076 |
def FreeSid(pSid): # pylint: disable=C0103
"""The FreeSid function frees a security identifier (SID)
previously allocated by using the AllocateAndInitializeSid function."""
ctypes.windll.advapi32.FreeSid(pSid) | 56,077 |
def image_conversion(source_path, dest_fmt, wipe=False):
"""
Convert image from one format to another, optionally erasing the source image
image_path : string
Path to image to be converted.
wipe : bool
If True, delete the source image after successful conversion
"""
from numpy... | 56,078 |
def main(addr, game_port, web_port,
q_rate = datetime.timedelta(seconds=10)):
"""main game entry point. everything is event driven.
this used to handle both the web page/status and the game server (web_skt and game_skt).
However, for improved reliabilty the web page server is now in ajax_server.py.... | 56,079 |
def parse_csr(csr):
"""
Helper function that parses a CSR.
:param csr:
:return:
"""
assert isinstance(csr, str)
return x509.load_pem_x509_csr(csr.encode("utf-8"), default_backend()) | 56,080 |
def count_matches(list, item):
"""
Return the number of occurrences of the given item in the given
list.
"""
pass | 56,081 |
def docker_compose_yml(opts):
"""docker-compose.yml for vscode
Args:
opts (dict): given options, see :obj:`create_project` for
an extensive list.
Returns:
str: file content as string
"""
template = get_template("docker_compose_yml")
return template.safe_substitute(o... | 56,082 |
def get_directory():
"""
Get the name of home directory of usecase. Use the home directory for file
path construction.
"""
home_dir = dirname(
dirname(abspath(__file__))
) # call dirname twice to get parent dir
return home_dir | 56,083 |
def edit_pkgbuild(pkgname):
"""Edit a PKGBUILD interactively. Returns False if user aborts install."""
yesno = DS.fancy_msg_prompt(_('Edit PKGBUILD of {0}? [Y/n] ').format(pkgname))
if yesno.lower().strip().startswith('y') or not yesno.strip():
if os.environ['EDITOR']:
subprocess.call([... | 56,084 |
def package_data() -> pathlib.Path:
""" Returns the absolute path to the circe/data directory. """
return pathlib.Path(__file__).parents[1].joinpath("data") | 56,085 |
def _resource_directory_configurator(developer_dir, prerequisites, args):
"""Configures compiler flags about the toolchain's resource directory.
We must pass a resource directory explicitly if the build rules are invoked
using a custom driver executable or a partial toolchain root, so that the
compiler... | 56,086 |
def changeFileNoInFilePath(path: str, fileNo: int) -> str:
"""replaces the number in the path with the given number."""
separator = r"[0-9]+\."
splitted_path = re.split(separator, path, 1)
new_path = splitted_path[0] + str(fileNo) + "." + splitted_path[1]
return new_path | 56,087 |
def common_fill_value(a, b):
"""Return the common filling value of a and b, if any.
If a and b have different filling values, returns None.
"""
t1 = get_fill_value(a)
t2 = get_fill_value(b)
if t1 == t2:
return t1
return None | 56,088 |
def hybrid_to_plevs(var, hyam, hybm, ps, plev):
"""Convert from hybrid pressure coordinate to desired pressure level(s)."""
p0 = 1000. # mb
ps = ps / 100. # convert unit from 'Pa' to mb
levels_orig = cdutil.vertical.reconstructPressureFromHybrid(
ps, hyam, hybm, p0)
levels_orig.units = 'mb... | 56,089 |
def pentatope():
"""
Vertices of the 5-cell
"""
s = 3.2**-0.5
return np.array([
np.quaternion(1, 0, 0, 0),
np.quaternion(-0.25, s, s, s),
np.quaternion(-0.25, s, -s, -s),
np.quaternion(-0.25, -s, s, -s),
np.quaternion(-0.25, -s, -s, s),
]) | 56,090 |
def shift_write_affnist(dataset, filename, shift, pad):
"""Writes the transformed data as tfrecords.
Pads and shifts the data by adding zeros. Writes each pair of image and
label as a tf.train.Example in a tfrecords file.
Args:
dataset: A list of tuples containing corresponding images and labels... | 56,091 |
def checkDaysWeeksElapsed(count, days, weeks):
"""
:param count: the number of checks performed
:param days: the number of days elapsed
:param weeks: the number of weeks elapsed
:return: the number of checks performed (0 if one day has gone).
"""
if (count % 144) == 0:
days += 1
... | 56,092 |
def not_found(f):
"""
Registers a function as 404 error handler
:param f: function
Function should receive an :class:`werkzeug.exceptions.Exception` object as parameter
"""
_utils.not_found(_utils.caller(), f) | 56,093 |
def spawnpty(cmd, logfile=None, env=None, callback=None,
persistent=False, merge=True, pwent=None, async=False,
devnull=False):
"""Start a child process using a pty.
"""
pm = get_procmanager()
proc = pm.spawnpty(cmd, logfile, env, callback, persistent, merge, pwent,
... | 56,094 |
def dirmap_file_name_filter(file_name):
"""Nuke callback function with single full path argument.
Checks project settings for potential mapping from source to dest.
"""
dirmap_processor = NukeDirmap("nuke",
DirmapCache.project_settings(),
... | 56,095 |
def h2o_H2OFrame_modulo_kfold_column():
"""
Python API test: h2o.frame.H2OFrame.modulo_kfold_column(n_folds=3)
"""
python_lists = np.random.randint(-5,5, (1000, 2))
k = randrange(2,10)
h2oframe = h2o.H2OFrame(python_obj=python_lists)
clist = h2oframe.kfold_column(n_folds=k)
assert_is_ty... | 56,096 |
def update_submission_status(
sub_status: SubmissionStatus,
values: typing.Union[Annotations, dict],
status: str = None,
) -> SubmissionStatus:
"""Updates submission status and annotations
Args:
sub_status: A synapseclient.SubmissionStatus
values: A synapseclient.Annotations or di... | 56,097 |
def get_window_radial(xx, yy, zz=None, wtype='hamming', rmax=None, duration=None,
x0=0, x1=None, y0=0, y1=None, z0=0, z1=None,
n=500):
"""
General method to get a window with shape (xx.shape[:], duration) or (xx.shape[:]) if duration is None
... Window types:
... | 56,098 |
def test_sys():
""" Test sys functions."""
try:
afsapi = AFSAPI(URL, PIN, TIMEOUT)
set_power = yield from afsapi.set_power(True)
print('Set power succeeded? - %s' % set_power)
power = yield from afsapi.get_power()
print('Power on: %s' % power)
end_po... | 56,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.