content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def expand_quantized(sample, feat_idxs): """ Get the neighbouring value (shift '1' right and left) in a quantized one-hot feature vector. :param sample: Initial node. :type sample: numpy array. :param feat_idxs: Indexes pointing to transformable features in the sample array. :type feat_idxs: nu...
86e95bee22b89be10a5fade8493b051a009abe27
3,600,570
def is_primary() -> bool: """Is Primary Device""" return get_rank() == 0
e0c43bf971988407d1392fb457fb3ca0be53c729
3,600,571
def advect(dens, dx, dy, dt, u): """ second-order upwind method for 2d advection Advects density in some subdomain by velocity u, given timestep dt and grid spacing (dx, dy). """ gradx = np.zeros_like(dens) grady = np.zeros_like(dens) if u[0] > 0.: gradx[2:, :] = (3*dens[2:, :] ...
a90bf3678115246556cf8c63cd603d57007bd182
3,600,573
def load_labels_as_index(label_filename): """ Load a set of labels (with no attached vectors) from a text file, and represent them in a pandas Index. """ labels = [line.rstrip('\n') for line in open(label_filename, encoding='utf-8')] return pd.Index(labels)
950cd2dae2f920e4afe894c91328fecaea05c078
3,600,575
def omp_get_dynamic(): """Return the value of the dyn-var ICV, which determines whether \ dynamic adjustment of the number of threads is enabled or disabled. This routine returns 1 if dynamic adjustment of the number of threads is enabled for the current task; it returns 0, otherwise. If an i...
1a93b85905be8397ba6077b031903d36b519f93d
3,600,576
def MACD(ds, count, fastperiod=-2**31, slowperiod=-2**31, signalperiod=-2**31): """Moving Average Convergence/Divergence""" ret = call_talib_with_ds(ds, count, talib.MACD, fastperiod, slowperiod, signalperiod) if ret is None: ret = (None, None, None) return ret
4a917ffcf070d7cacd831dc7873f2e5d34bdba81
3,600,577
import math def plot_all_params(predictions_dict, method='best', weighting='exp'): """Plots mean and variance bar graphs for all the sampled params for different (scenario, config). It is assumed that the user provides a dict with 1st layer of keys as the scenarios and 2nd layer of keys as the con...
c103e306474d425d89804e26d0c8e91a7050b4b1
3,600,578
def Main(): """ :return: """ a = 1 b = 2 c = a + b return c
6482b416105d1ba23f564d6a47a52b7cba9c38bc
3,600,579
def input_stream(fd, sze, url, params): """Opens a StringIO whose data is everything after the url scheme. For example, `raw://hello_world` would return `hello_world` when read by the task. """ return (cStringIO.StringIO(url[6:]), len(url) - 6, url)
d0c0af167669bfd5755de15e6cc091df6637152c
3,600,580
def _describe(in_fc): """Simply return the arcpy.da.Describe object. **desc.keys()** an abbreviated list:: 'OIDFieldName'... 'areaFieldName', 'baseName'... 'catalogPath', 'dataType'... 'extent', 'featureType', 'fields', 'file'... 'hasM', 'hasOID', 'hasZ', 'indexes'... 'lengthFieldName'... 'name', ...
58bcad583514ff82e7ef3e8ce3f678f1081d28fd
3,600,581
def users_login(): """ Login page """ if current_user.is_authenticated(): return redirect(url_for('gallery_home')) form = LoginForm() if form.validate_on_submit(): user = User.find_by_name(form.username.data) if user is None or not user.is_valid_password(form.password.data): ...
62d2e4a8eedd32e7b57f919bb23acba34cffae8e
3,600,582
def trim_walkers(res, threshold=-1e4): """Remove walkers with probability below some threshold. Useful for removing stuck walkers """ good = res['lnprobability'][:, -1] > threshold trimmed = {} trimmed['chain'] = res['chain'][good, :, :] trimmed['lnprobability'] = res['lnprobability'][good,...
ba8e3ebbb2c6948be06d4d1bbd3871011763d71c
3,600,583
def train_step(model, optimizer, batch, n_actions): """1 step optimize policy.""" obsers, actions, weights = batch actions_mask = tf.one_hot(actions, n_actions) with tf.GradientTape() as tape: # log(a|s) R(tau) logits = model(obsers) log_probs = tf.reduce_sum(actions_mask * tf....
ce86de0759669460fc6c2acd6f859755b8aac417
3,600,584
import copy def printcc (lst,extra=2): """ Prints a list of lists in columns, customized by the max size of items within the columns (max size of items in col, plus 'extra' number of spaces). Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines, respectively. Usage: printcc (lst,extra=2) R...
c432de7c0213e370c1f565b20579f691b716e4cd
3,600,585
def get_zip_location_map(): """make dictionaries taking zip code to province and municipality """ bmap = pd.read_csv("../Belgium-Geographic-Data/dist/metadata/be-dictionary.csv",error_bad_lines=False) bmap["PostCode"] = bmap["PostCode"].astype(int,errors='ignore') pro = {} mun = {} fn = { "...
2f2064dd73d809b0fabf01bf6e8930b5371639a3
3,600,586
def _str_eval_true(eval, act, ctxt) : """Returns false.""" return [False]
eb0fd9b576b55133319752f86750159c9684ba0c
3,600,587
def CalculateMaxAtomTypeEState(mol): """ ################################################################# Calculation of maximum of E-State value of specified atom type res---->dict type Usage: result=CalculateMaxAtomTypeEState(mol) Input: mol is a molecu...
ecdb2eb9db340eef0725941fd22eeba1b6a73933
3,600,588
def swapaxes(dat, ax1, ax2): """Swap axes of a Data object. This method swaps two axes of a Data object by swapping the appropriate ``.data``, ``.names``, ``.units``, and ``.axes``. Parameters ---------- dat : Data ax1, ax2 : int the indices of the axes to swap Returns ---...
576ec10826c3ab92465052edcadf38cf04952c02
3,600,590
def update_weight(y, unsupervised_weight, next_weight): """update weight of the unsupervised part of loss""" y[:, -1] = next_weight unsupervised_weight[:] = next_weight return y, unsupervised_weight
c961714c248ba4c0f752be568115e444e1d963e2
3,600,591
def pad(image, ts=0, bs=0, ls=0, rs=0, color=(0, 0, 0)): """Pads the image through adding pixels to each side of the image. params: image: A numpy ndarray, which has 2 or 3 dimensions ts: An integer, which is the amount to pad the top side of the image bs: An integer, which i...
6acc2b3f97a4aeaf98a524434d646fa12c2eb6c5
3,600,592
import re def find_slug(url, prefix, postfix): """Извлекает slug из url по известным границам prefix, postfix""" pattern = f'{prefix}.+{postfix}' slug = re.search(pattern, url).group() return slug.lstrip(prefix).rstrip(postfix)
7fb0b99989ef05f83b370b0c40c7e82c05e51ab7
3,600,593
def initial_basin_chain(HB_gdf, cl_gdf, buf_wid=0.1): """ Finds the chain of drainage basins from the upstream-most centerline point to the sink (e.g. ocean). Parameters ---------- HB_gdf : GeoDataFrame [description] cl_gdf : GeoDataFrame Centerline coordinates buf_wid :...
30141717fe7e0ae6218492a1c97271867107ee5a
3,600,594
def send_dronelog(dronelog): """Post the drone log to the central server.""" try: post_dronelog = RES_CS.find_suitable_operation( SCHEMA.AddAction, CENTRAL_SERVER.DroneLog) resp, body = post_dronelog(dronelog) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.re...
9e3f901bc41182620e8d90809be75b930213ddb9
3,600,595
def data_augmentation(original_image, original_mask): """进行样本和掩膜的随机增强 Args: original_image: 原始图片 original_mask: 原始掩膜 Return: image_aug: 增强后的图片 mask_aug: 增强后的掩膜 """ original_height, original_width = original_image.shape[:2] augmentations = Compose([ Ho...
b6436b895d5657c75a8e892caea51996225347e8
3,600,596
import re def is_url(value): """Return whether or not given value is a valid URL.""" regex = re.compile( r"^" # startchar < r"<?" # protocol identifier r"(?:(?:https?|ftp)://)" r"(?:" r"(localhost)" r"|" # host name r"(?:(?:[a-z\...
3a50e541a9e62156a89693d15d248080abb3718f
3,600,598
import random def greedy_file_select(aud_len, aud_files): """ Select x number of files greedily till aud_len is satisfied Args: Returns: """ len_sofar = 0 files_sofar = [] total_aud_ixs = list(range(len(aud_files))) while True: rand_ix = random.sample(total_aud_ixs, 1)[...
da947a88e43af576c3aeb6fc23bb9c072f612872
3,600,599
def get_targets(words, idx, window_size=5): """ 获取input word(idx下标对应的word)对应的上下文words :param words: 单词列表 :param idx: input word的下标 :param window_size: 窗口大小 :return: """ target_window = np.random.randint(1, window_size + 1) start_point = idx - target_window if (idx - target_window) > ...
a7b6cf14fc0fffb53cbf7d8fa4cd2e0785468018
3,600,600
def sanitize_value(p_value): """Returns p_value or its part if it represents a sane simple value, else returns 'None'""" if isinstance(p_value, STR_TYPES): match = SIMPLE_VALUE_RE.match(p_value) if match: return match.groups()[match.lastindex - 1] else: return 'No...
21133a4810209f284da8ed3de1110c92f27dd7e9
3,600,602
def ysum_ysq_count(ysum, ysq, counts): """ calculate mean and error given accumulated sum of val and sq Args: ysum (np.array): accumulated sum of values, (nentry,) ysq (np.array): accumulated sum of squares, (nentry,) counts (np.array): number of hits for each entry, (nentry,) Return: (np.array, ...
ecdb04c291b28bb2ad8385be3b09a45a32a72c05
3,600,603
def array_to_image(array, image_float=False): """ """ normalized_data = normalize_data(array) rgba = from_data_to_pixel_value(normalized_data, image_float) return rgba
01712bb81cfe15ca03ec99a4e76e0bb3fdc7c781
3,600,605
import textwrap def format_function_call(name, pdict): """ Formats a function call with named parameters. @param pdict dictionary @return string .. runpython:: :showcode: from mlinsights.helpers.parameters import format_function_call d = dict(...
efcadb3a41a6059faf778fc459658a480c98e539
3,600,606
def _get_profile_image_urls(name, storage, file_extension=PROFILE_IMAGE_FILE_EXTENSION, version=None): """ Returns a dict containing the urls for a complete set of profile images, keyed by "friendly" name (e.g. "full", "large", "medium", "small"). """ def _make_url(size): url = storage.url( ...
bd98d22a154a5bb48b3e084c39de1640daf2e9cb
3,600,608
def load_torch_resnet152(scopes, return_fn=_assign): """Converted from the [Torch ResNets][5].""" filename = 'resnet_152_cpu.pth' weights_path = get_file( filename, __model_url__ + 'resnet/' + filename, cache_subdir='models', file_hash='3339f6aca7f746f8ae7f6ce577efc0c0') values =...
80e981ce53540e3c145320a8cb7dcebc2526f849
3,600,609
from typing import Iterable def merged_codepoints(cps: Iterable[CodePoint]): """return a list of codepoints (start, end) for inclusive ranges""" cps = sorted(cps, key=lambda cp: cp.codepoint) if not cps: return [] ranges = [(cps[0], cps[0])] for cp in cps[1:]: last_range = ranges[-...
e28c7f0a0a1298812f1770eb43f55f7573fd4304
3,600,610
def is_bool_type(type_): """ Checks if the given type is a bool type. :param type_: The type to check :return: True if the type is a bool type, otherwise False :rtype: bool """ return type_ in _get_types(Types.BOOL)
2c947f1dc4207f85908b8cdb71e16dd86f353a6f
3,600,611
def train (param): """ ************************************************************************** This function returns a Handle to the training process The training process is running in the background after the functions ends. ***********************************************************************...
7ceb97548a7155632234d7fa1a93b31fc2e24355
3,600,612
import json def pretty(ob, lexer=None): """ Return a pretty console text representation of 'ob'. If 'ob' is something else than plain text, specify it in 'lexer'. If 'ob' is not string, Json lexer is assumed. Command line switches can be used to control highlighting and style. """ if lex...
216c1457161c0b10ff98c1227408ce2238bf3f53
3,600,614
from typing import Optional from typing import List def browse_results( data: pd.DataFrame, severities: Optional[List[str]] = None, **kwargs ) -> SelectItem: """ Return TI Results list browser. Parameters ---------- data : pd.DataFrame TI Results data from TIProviders severities :...
c7d8bc6fe5bca86de81a186ff4d25a58e2d8c9d6
3,600,615
def infection_rate_symptomatic_10x80(): """ Real Name: b'infection rate symptomatic 10x80' Original Eqn: b'Susceptible 80*Infected symptomatic 10x80*contact infectivity symptomatic 10x80*(self quarantine policy SWITCH self 80\\\\ *self quarantine policy 80+(1-self quarantine policy SWITCH self 80))/non cont...
76522534c07d798608ed24da15b15054a832ae8b
3,600,616
import functools def _make_modules(is_train): """Returns modules, with split based on the boolean `is_train`.""" return { 'swr_p_sequence': functools.partial( swr_prob_sequence, is_train=is_train, sample_range=_SWR_SAMPLE_COUNT), 'swr_p_level_set': functools.partial( swr_prob_level...
675b30495080df5e8d2b57cf9f9dcb1f155b9c70
3,600,617
import ctypes def DMAR(val): """Create class based on decode of an DMAR table from address or filename.""" base_length = ctypes.sizeof(dmar_factory(list())) addr = val if isinstance(val, str): data = open(val).read() buf = ctypes.create_string_buffer(data, len(data)) addr = cty...
9c3cedf4b52d078e15488c683f39b594e4e6313d
3,600,618
def validate_device_name_text(device_name): """Extends the validate_device_name function with a return text if the validation fails. Can be used with the validate option of the questionary package. Args: device_name: Device name to validate as string. Returns: True if the given string ...
9957e9c8ebd91bf6d1dcce43a4b4d2fab3b2edeb
3,600,619
from datetime import datetime def get_chat_metadata_for_header(transcript, duration, wait): """Will generate the section that comes before the transcript on the HTML page. It contains metadata information such as Duration and Wait Time of the chat Args: transcript ([type]): [description] ...
6206e7a54d32b61a96d3615ef0475f946cb0c85a
3,600,620
def index(): """Main page.""" return render_template("index.html")
d776731cc585dd3006ca7aeb0f1dd2565106049c
3,600,622
import collections import random def gen_undirected_graph_rand(nodes = 1000, edge_factor = 3, costs = (1,1)): """ generates an undicrected graph with `nodes` nodes and up to `edge_factor` edges per node @param nodes amount of nodes @param edge_factor up to `edge_factor` edges per node @param ...
96947e153d235cad9b900492693cfb316eaff32d
3,600,623
import json def append_users(channel: str, *users_to_add: str): """ Appends users to the specified channel's user list. """ c = Channel.query.get(channel) if not c: return no_channel users = json.loads(c.users) for user in users_to_add: if user not in users: use...
2425f1abb0e621389b8db5d41de5c584a4cf7603
3,600,624
def symmetrized_csiszar_function(logu, csiszar_function, name=None): """Symmetrizes a Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The symmetrized Csiszar-function is defined as: ```none f_g(u) = 0.5 g(u) + 0.5 u g (1 / u) ``` wher...
931094ace56953e31cf65a78c1015dd1d1de59bd
3,600,626
def _int2farray(ftype, num, length=None): """Convert a signed integer to an farray.""" if num < 0: req_length = clog2(abs(num)) + 1 objs = _uint2objs(ftype, 2**req_length + num) else: req_length = clog2(num + 1) + 1 objs = _uint2objs(ftype, num, req_length) if length: ...
9be8cf28a3f379235d07718df8db9dff7e223d2f
3,600,627
def pick_coupons(user): """ Choose the coupons which would be used in redemptions by the user. There should be at most one coupon per program in the output. The heuristic is currently: - choose attached coupons over automatic coupons - choose the coupon which has been most recently attached, ...
886f3224f7925dfdbc7caace65903bf9ecbec741
3,600,628
def closer_ang(x,a,dir=0): """ find angle y (==x mod 2*PI) that is close to a dir == 0: minimize absolute value of difference dir == 1: y > x dir == 2: y < x """ if dir == 0: return a + smaller_ang(x-a) elif dir == 1: return a + (x-a)%(2*PI) elif dir =...
c87bf0976e87d195e10c4886be62ca9ee473702f
3,600,629
def make_name(name): """ Converts a given name to a lower snake case :param name: Name to convert :return: Lower snake case """ return to_snake_case(name)
1950402f193b1b8c4d14fa5e0e5e332b72b83891
3,600,630
import re def update(): """Find up to 10 places within view.""" # ensure parameters are present if not request.args.get("sw"): raise RuntimeError("missing sw") if not request.args.get("ne"): raise RuntimeError("missing ne") # ensure parameters are in lat,lng format if not re....
18967e68dbea1b5d3c274005c9dfd92ae6c1295a
3,600,632
def _riccati_bessel_y(degree, argument): """ Riccati-Bessel function of first kind and derivative """ return (np.array(special.riccati_jn(degree, float(argument))) - 1j * np.array(special.riccati_yn(degree, float(argument))))
65162b85a0c2058702377fd209207b2d80e9c739
3,600,633
def fit_vfa_nonlinear(s, fa, tr): """Return T1 based on VFA signals using NLLS fitting. Parameters ---------- s: ndarray 1D array of signals. fa: ndarray 1D array of flip angles (deg). tr: float Repetition time (s). Returns ------- ...
667c4ac86a844bc110bcfcd0c89d51ec106e42a4
3,600,634
def newsletters(request, context): """back to balafon newsletters""" if request and request.user.is_authenticated and request.user.is_staff: view_name = 'admin:{0}_{1}_changelist'.format(get_model_app(Emailing), get_model_name(Emailing)) return make_link( reverse(view_name), _('Email...
5d220d1b5c5856c68a56354eb7d7f1e85a7f7389
3,600,635
def commands_overlap(first, second): """ Returns True if the two given commands overlap in their output targets (regardless of color) """ if isinstance(first, SetAll) or isinstance(second, SetAll): # SetAll will conflict with whatever return True if isinstance(first, SetStrand) or i...
b292d8b5f3bceb4e55a2a6e5b49448ecf662f73f
3,600,636
from functools import reduce def problem(): """ Solve the problem. 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Answer: 232792560 ...
442be80c10b9317c2fc4223ec55123a39c633da9
3,600,637
def overhang(wall): """Calculate the overhang parameter as a function of y along the wall. See _overhang() for details. Parameters ---------- wall : pandas.DataFrame or datautil.DomainWall Location of the zero crossing of Mz. Returns ------- np.ndarray or list of np.ndarray ...
25605af6628a237eae64724e473539c03ab873ff
3,600,638
def ssh_tailc(address:str, filename:str, **kwargs)->Popen: """tail cat and follow via ssh""" proc = Popen(f'ssh {address} "tail -Fc+0 {filename}"', stdout=PIPE, shell=True, **kwargs) return proc
051b244ca17f5b56ebdea30a7f05b82754f08309
3,600,639
def raj_logfact(n): """Ramanujan approximation of log(n!)""" f1 = n*np.log(n) f2 = -n f3 = np.log(n*(1+4*n*(1+2*n)))/6 f4 = np.log(np.pi)/2 return f1 + f2 + f3 + f4
ca5c93f83bb8b4956eb616d89f5697fa6be439c1
3,600,641
def post_permission_webhook_view(request): """ Permission webhook used for created or removed permission events. """ event = ar.get_multiformat_body(request, "event") ax.verify_param(event, param_name="event", param_compare=ValidOperations.values(), is_in=True...
c20b1f93ba8e973a608c4405300b870f75c46ce1
3,600,642
def convmtx2_valid(H, M, N): """ 2d convolution matrix with the boundary condition 'valid', i.e., only filter within the given data block. :param H: 2d filter :param M: input signal dimension is M x N :param N: input signal dimension is M x N :return: """ T = convmtx2(H, M, N) s_...
522beb76a5744534c5a5a4bfce707fcd680d8a93
3,600,643
def api_get_theme_display_data(): """ GET: 1.获取主题展示用的多媒体数据 conditions:<array:dict>, Such as:[{'type':<str>, 'names':<array>, 'name_regex':''}] 说明: type-可以是"text", "image", "video", "audio" names-数组,指定要获取数据的name name_regex-字符串,获取匹配此正则的me...
b0c0b75f4294e6d06d45bac250c419b10a7c9521
3,600,644
def parse_netscape_bookmarks(bookmarkHTMFile): """Extract bookmarks and return them in a list of dictionaries formatted in the following way: [ {"url":"http://...", "title":"the title", "private":"0"/"1", "tags":"tag1,tag2,...", "posix_timestamp"="<unix time>", "note":"description"}] Raise a ValueError if the for...
03fbf11ea59bff898a25c9d1198a93a60cc447b3
3,600,646
def remote_call(method): """Decorator to set a method as callable remotely (remote call).""" method.remote_call = True return method
ab276cbdb190185c7e46c5205df25f022a56a097
3,600,647
from typing import Union from typing import Iterable def np_str_len(str_arr: Union[np.ndarray, Iterable[str]]) -> np.ndarray: """ Fast way to get string length in a numpy array with datatype string. Args: str_arr: Numpy array of strings with arbitrary shape. Returns: Numpy array of s...
f74a08d707431a56578a4d2eb84d4b7531d02a97
3,600,648
import functools def nodeop(target=None, **kwargs): """ Decorator for creating nodes from functions. """ # This is called when the decorator is used with arguments if target is None: return functools.partial(nodeop, **kwargs) # This is called when the decorator is used without argumen...
c66544db52749e306384495a42217d07eef28c80
3,600,650
def get_last(utdt, longitude): """ Local Apparent Sidereal Time (LAST) """ gast = get_gast(utdt) last = gast + longitude/15. last %= 24. return last
8ba1304a32b7eb9785da02b43450d9f81b30d1ff
3,600,651
import re def get_user_by_email(user_to_search: str) -> dict: """ Searches for a user when given the user's email. Args: user_to_search: the user's email we are searching for. Returns: Formatted user results if a user is found. """ if not re.match(emailRegex, user_to_search): ...
c4e6240c20e9d9481ca89d36157b80262de7788a
3,600,653
def prep_petroleum_water_intensity(): """ Takes county level petroleum-production values and determines the water intensity for the given county for both unconventional and conventional petroleum production. :return: Dataframe of county-level petroleum water intensity...
cbb5d458af89765374854a8156f0acc60a90b68d
3,600,654
from pathlib import Path def node(ph5, path, class_name): """ Get the node handle of a given path and class name :param ph5: an open ph5 object :type ph5: ph5 object :param path: path to node :type path: string :param class_name: name of class to get :type class_name: st...
2a8090952fdec3dda7490844990f41c8e154c3af
3,600,655
def delete_payload(): """ Invokes the ControlPlane APIs with a DELETE request. Supports IAM Authentication. Returns: Controlplane API result. """ return invoke_destination_api("DELETE", app.current_request.uri_params['proxy'])
16ce295d3b9acf30db24d405be25e1f86fb00412
3,600,657
def indian_word_currency(value): """ Converts a large integer number into a friendly text representation. Denominations used are: Hundred, Thousand, Lakh, Crore Examples: 1000 becomes 1 Thousand 15000 becomes 15 Thousands 15600 becomes 15.60 Thousands 100000 becomes 1 Lak...
d162725f588d96a7dc3ead80b5278d71187bf4c1
3,600,658
def cutout(image, size=16, color=None, name=None): """This is an implementation of Cutout as described in "Improved Regularization of Convolutional Neural Networks with Cutout" by DeVries & Taylor (https://arxiv.org/abs/1708.04552). It applies a random square patch of specified `size` over an `image` ...
1653f9df3bd91579c00868e7659fd06425a37895
3,600,659
from typing import Union from typing import Tuple import requests def fetch_nab(ts: str, return_X_y: bool = False ) -> Union[Bunch, Tuple[pd.DataFrame, pd.DataFrame]]: """ Get time series in a DataFrame from the Numenta Anomaly Benchmark: https://github.com/numenta/NAB. Parame...
c20c13c3836ad4391ba8cb4461e95141e6be6eb6
3,600,660
def get_equips(equipments): """ Join all properties needed """ itens = [] for equip in equipments: equip_dict = prepares_equips(equip) itens.append(equip_dict) return itens
c642dee1582da1cd0d108aa3a3d991bc833c826a
3,600,662
def annual_NAIP(year, region): """Create an NAIP mosaic of a specified year for a specified region. Args: year (int): The specified year to create the mosaic for. region (object): ee.Geometry Returns: object: ee.Image """ start_date = ee.Date.fromYMD(year, 1, 1) end_...
ff9f1c54ce56869846baa8c59d08dd2bb1d370f2
3,600,663
import torch def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in cen...
f523fb0d905aba612cf67816d6aa0ec549dbebce
3,600,664
def make_protocol(protocol_name, device): """Make a protocol object factory function.""" return protocol2object[protocol_name](device)
0d830962c47dcb4fe926a4d37d4503f76ad67749
3,600,665
def create_parser() -> OptionParser: """Initialize parser with options.""" formatter = IndentedHelpFormatter( indent_increment=2, max_help_position=56, width=120, short_first=1 ) parser = OptionParser(usage=USAGE, epilog=EPILOG, version=f'%prog {VERSION}', formatter=forma...
17fa20cb3c2d98696440991f646c6f7343d06ac2
3,600,666
def txfDate(date): """Returns a date string in the TXF format, which is MM/DD/YYYY.""" return date.strftime('%m/%d/%Y')
fd1f19b4080447379ec3ec57be0f2af047099673
3,600,667
from typing import Tuple async def check_audio_support(try_install: bool = False) -> Tuple[bool, bool, bool]: """Check if sox and/or ffmpeg are present.""" cache_key = "audio_support_cache" if cache := globals().get(cache_key): return cache # check for SoX presence returncode, output = awa...
5c8defaa5a7e20d9b8934532516388c879a1916a
3,600,668
from typing import Optional def clamp( data: NodeInput, min_value: ScalarData, max_value: ScalarData, name: Optional[str] = None ) -> Node: """Perform clamp element-wise on data from input node. @param data: Input tensor. One of: input node, array or scalar. @param min_value: The lower bound of the <...
4f45e1f2c2560ff60669f80e76bb969f88a03d97
3,600,669
def get_arcis_makeai_params(path_to_file): """ Returns dict {'param':value} """ params = np.genfromtxt(path_to_file, usecols=np.arange(0,3), skip_header=1, dtype='str') params[:,2] = params[:,2] params = params[:, [0,2]] params = dict(params) for key in params: params[k...
22a14c1d10311cf27b5eef89026a5c7634a74f62
3,600,670
import datetime def sobject_to_dict(obj, key_to_lower=False, json_serialize=False): """ Converts a suds object to a dict. Includes advanced features. :param json_serialize: If set, changes date and time types to iso string. :param key_to_lower: If set, changes index key name to lower case. :param ...
5915fdd52bee26a0f4bfac67fc1140ab3d6a49a3
3,600,671
def check_assist(exp): """ :param exp: expression string :return: True if assist operator """ return exp in Types.AssistOp
2d2a943d577e0a106839a2ae5dd952e0b9c19b25
3,600,672
from datetime import datetime def get_account_oldest_balance(account: Account) -> ty.Tuple[float, datetime]: """Compute and return the oldest possible account balance.""" current_balance: float = account.get_solde() now = datetime.now() long_before = now - timedelta(weeks=100 * 52) operations = l...
a0b853ff180ac3378cdb0e0e0a4753725f70f406
3,600,673
def _make_msa_df(chain_features: pipeline.FeatureDict) -> pd.DataFrame: """Makes dataframe with msa features needed for msa pairing.""" chain_msa = chain_features['msa_all_seq'] query_seq = chain_msa[0] per_seq_similarity = np.sum( query_seq[None] == chain_msa, axis=-1) / float(len(query_seq)) per_seq_g...
f2ec656d211adb4174596ae86a563b5fadc69726
3,600,674
def get_snapshot(connection, snapshot_id): """Returns a snapshot with *snapshot_id*.""" res_set = get_snapshots(connection, [snapshot_id]) if not res_set or len(res_set) != 1: raise Exception('unexpected result from get_snapshots') snapshot = res_set.pop() return snapshot
09df168af900ed16b593fe476f02dea70a3bc9cb
3,600,675
def rgba(r, g, b, a = 255) : """Create Rgba instance based on r,g,b,a values""" return Rgba( [r, g, b, a] )
4e4c05054836124acc6858aa4b4bb5472a07b7ab
3,600,676
import numpy def getgridparams(): """ return grid parameters in a python friendly way Output: [ Xul, Yul, xsize, ysize, rows, cols] - xul - x upper left centre - yul - y upper left centre - xsize - size of a cell in x direction - ysize - size of a cell in ...
efd3506699984ce5ad140f7f0a0a1ea6a8a938f7
3,600,677
def get_hospitals_current(): """ Return all Hospitals Developments """ hospitals = db.session.query(HospitalDevelopment).all() return jsonify(__as_feature_collection(hospitals)), 200
89c37beb196a70ada8934e33fba88e459efb8378
3,600,678
from typing import Iterable from pathlib import Path def to_multi_path(paths: Iterable[Path]) -> Path: """Returns a multi-path object from all given paths and their sub-paths. .. versionadded:: 0.17 """ multi_path = Path() for p in paths: multi_path.extend_multi_path(p) return multi_...
f247379e4d36502909b3593d7ea116bb77366e90
3,600,680
def aligned_malloc(shape, dtype, alignment=16): """allocates numpy.array of specified shape, dtype and memory alignment such that array.ctypes.data is an aligned memory pointer shape is numpy.array shape dtype is numpy.array element type alignment is required memory alignment in bytes """ ...
9d5734f78a69e914279b21b8a0889fe26fa2c9b5
3,600,681
import cv2 from PIL import Image import io import base64 def embed_image_html(imgBGR, target_width=TARGET_WIDTH, target_height=TARGET_HEIGHT): """ Creates an image embedded in HTML base64 format. """ if target_width is not None: imgBGR = _resize(imgBGR, t_width=target_width) elif target_height is...
c117bb180f832872386965dde420ebda691e5309
3,600,682
def create_pitch(dff, strategy=None): """Creates the whisky returns by pitch chart""" data = [] if strategy == 2: xcol = 'annual_return' xtitle = 'Annual % return' ycol = 'APR_5%' ytitle = 'Compound Annual Return, %' else: xcol = 'days_to_close_spread' xti...
2ece1f812ecb3a7c3b3e1f127b88a5d8eb1abbaa
3,600,683
def get_institutes(variable): """Return the institutes given the dataset name in CMIP6.""" dataset = variable['dataset'] project = variable['project'] try: return CMOR_TABLES[project].institutes[dataset] except (KeyError, AttributeError): return []
1dc946496ff4b0ff6830adc7d2452378c1154b82
3,600,684
def unet(height, width, channels, classes, features=64, depth=4, temperature=1.0, padding='valid', batchnorm=False, dropout=0.0): """Generate U-Net model introduced in "U-Net: Convolutional Networks for Biomedical Image Segmentation" O. Ronneberger, P. Fischer, T. Brox (2015) Arbitrary numb...
b2b3c1a8ba5213b34ba8e1b7dc40a378a23cea9b
3,600,685
def construct_attrs_table(sub_layers_list, node_name2sub_layers=None, module_name=None): """ 构造不同属性的表格。 """ def get_node_name(sub_layers): for k, v in node_name2sub_layers.items(): if v == sub_layers: node_name = k break return node_name sub_la...
224ae069b013cafa51d2547825020e584f1bcb69
3,600,687
def diffuse_colors(n, l, dark, light): """ Shader calculation for a normal and a light vector and light and dark colors. Args: n(numpy.array): Unit normal vector l(numpy.array): Unit vector in the direction to the light dark(numpy.array): RGB dark color light(numpy.array)...
1644022d302299bb3288bd7bd113cf381bb35645
3,600,688