content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _process_motion_command(command, opts): """ Process motion command. :param command: Command tuple :param opts: UserOptions tuple :return: """ motion_data_type = None motion_data = [] # empty data container # Interpret linear motion command if opts.Use_linear_motion: ...
1aad247544414b71cb411ce5e00f1ecacefadb6b
3,632,900
import re def prepare_term_id(config, vocab_ids, term): """REST POST and PATCH operations require taxonomy term IDs, not term names. This funtion checks its 'term' argument to see if it's numeric (i.e., a term ID) and if it is, returns it as is. If it's not (i.e., a term name) it looks for the ...
a8b53d9a7c2c649482a760e3ab6fa4016cb2f9af
3,632,901
import re def simple_string(value: str) -> str: """ Returns a simplified value for loose comparison """ if not value: return "" value = strip_string(value) # Remove quotes value = value.rstrip("\\") # Remove trailing backslashes value = value.lower() # Lowercase value = re.s...
090566d21a9cfbe4dedd699aea9b332cd6af2057
3,632,902
def current_name() -> str: """Return the current dataset name, with an empty name in default.""" return _current_name_context.get().name
11252f5ebbb43dae0343de877a328e04d7f4069a
3,632,903
def open_zarr(path): """ Utility to open an xarray dataset from either dir that pytest might be called from. If called from root the path will be different than in the test dir """ return xr.open_zarr(str(dir_.joinpath(path)))
64afd33299057d65fa23535eb6ee737341e57a2e
3,632,904
def iid_log_probs(ids, batch_index, sequence_index, logp): """ Stacks the ids into a matrix that allows you to extract the corresponding logp from the iid samples from the decoder. :param ids: [B,T] tensor of ids in vocab :param batch_index: [B,T] tensor of the batch size repeated for seq len :p...
8a18e6652881fcad79ebd58ae0fec8f35be566f0
3,632,905
import re def get_format_from_path(path): """ Returns tuple of format , extension, unpacking function or None""" if re.search(r'(\.tar\.gz$)|(\.tgz$)', path): return ('gztar', 'tgz', unpack_tar) elif path.endswith('.zip'): return ('zip', 'zip', unpack_zip) elif re.search(r'(\.tar\.bz2...
0d07d835a009379c598f5af840c4a0d8a7bd0ff8
3,632,906
def tag(name, open=False, **options): """ Returns an XHTML compliant tag of type ``name``. ``open`` Set to True if the tag should remain open All additional keyword args become attribute/value's for the tag. To pass in Python reserved words, append _ to the name of the key. For att...
ec110a733ca5b40ceef4d3de92c3e74dc209f19b
3,632,907
import sys def CMDarchive(parser, args): """Archives data to the server. If a directory is specified, a .isolated file is created the whole directory is uploaded. Then this .isolated file can be included in another one to run commands. The commands output each file that was processed with its content hash...
2820bd9c4676b75d2763f38100b0d4a9249f7d20
3,632,908
import requests import re def get_ludo_user_id(ludo_username): """Returns the user id (number) for a given username in Ludopedia""" session = requests.Session() result = session.get(f'{LUDOPEDIA_USER_URL}/{ludo_username}') match_id = re.search(LUDOPEDIA_USER_ID_REGEX, result.text) if match_id: ...
53d1dc51c7020b918130ae4c978a398ba9817781
3,632,909
def operations_get_notification_list_post(inline_object19=None): # noqa: E501 """operations_get_notification_list_post # noqa: E501 :param inline_object19: :type inline_object19: dict | bytes :rtype: TapiNotificationGetNotificationList """ if connexion.request.is_json: inline_o...
840daf5edcc30bddb4f21296d29d613971078d1a
3,632,910
def project_block_to_graph(block_sizes, block_level_vals): """ Projects a set of values at the level of blocks to the nodes in the graph. """ full_graph_values = [] for k, n in enumerate(block_sizes): current_block = [] for q in range(n): current_block.append(block_le...
f61ed9ab8b11533ecda77db26349eae78e4db3e4
3,632,911
from ._common import generators def _write_gener(parameters, simulator="tough"): """Write GENER block data.""" # Format label_length = max( [ len(generator["label"]) if "label" in generator else 0 for generator in parameters["generators"] ] ) label_length =...
f014c9157bd93bf243a35b3b94b268771b611aa6
3,632,912
def _find(condition): """Returns indices where ravel(a) is true. Private implementation of deprecated matplotlib.mlab.find """ return np.nonzero(np.ravel(condition))[0]
34f0bbeda3c7e8309ab990579d2a57014c78c93e
3,632,913
def get_weekends(): """ Gets weekends from user input """ user_reply = input("What days of the week are your weekends? ") days = weekday_dict.keys() ret = [] for day in days: if day.lower() in user_reply.lower(): ret.append(day) if confirm_input(ret): return r...
152c90a12fa11915ec553df8e722a9f50279963e
3,632,914
def get_non_utf8_tables_columns(mysql_db_name, mysql_username, mysql_password): """Return two lists: the names of tables and columns that do not use the UTF-8 character set.""" sqlalchemy_url = 'mysql://%s:%s@localhost:3306/information_schema' % (mysql_username, mysql_password) info_schema_engine = create_e...
15452ff9737d765b3175c50a4758269b27c6da80
3,632,915
import os import time import urllib import base64 import shutil import hashlib import warnings def _fetch_file(url, data_dir=TEMP, uncompress=False, move=False,md5sum=None, username=None, password=None, mock=False, handlers=[], resume=True, verbose=0): """Load requested dataset, downloading it if ...
97950d9109c4644accbd691a3cba1e5294d399b5
3,632,916
def dataframe_from_dictionary(entry): """Create Pandas DataFrame from list of dictionary.""" return pd.DataFrame(entry)
e3d62626575aa5c685945b94395c74056bdd7d6a
3,632,917
def label_skew_process(label_vocab, label_assignment, client_num, alpha, data_length): """ params ------------------------------------------------------------------- label_vocab : dict label vocabulary of the dataset label_assignment : 1d list a list of label, the index of list is the index associat...
f63cad40d07f7f188f61b127b6af67a66bccbd5b
3,632,918
def can_item_circulate(item_pid): """Return True if Item can circulate.""" item = Item.get_record_by_pid(item_pid) if item: return item["status"] == "CAN_CIRCULATE" return False
9cf6c5cca54849d030b32e6caffd5ce2a74dcd32
3,632,919
def GetFocusThreadPB(filename): """ Get the focus thread for a pinball. If the pinball log file format is version 2.4, or lower, the focus thread info will be in a *.result file. However, as of version 2.5, this info is now in the *.global.log file. @return integer with focus thread @retu...
a8b0ea399f8ecf9dcf8b5a4e2ffdc1ba6805b5a9
3,632,920
def refpoint(matrix, objectives, weights): """Execute reference point MOORA without any validation.""" # max and min reference points rpmax = np.max(matrix, axis=0) rpmin = np.min(matrix, axis=0) # merge two reference points acoording objectives mask = np.where(objectives == Objective.MAX.value...
da82d2350cb205ece9d59651bc7142653252495f
3,632,921
from typing import Optional from typing import List def init_fabric_device_step1(device_id: int, new_hostname: str, device_type: str, neighbors: Optional[List[str]] = [], job_id: Optional[str] = None, scheduled_by: Optional[str] = ...
f7f74578d62d0097c481ea239ec0d3ddeb1de949
3,632,922
def architecture_is_32bit(arch): """ Check if the architecture specified in *arch* is 32-bit. :param str arch: The value to check. :rtype: bool """ return bool(arch.lower() in ('i386', 'i686', 'x86'))
a0cfaef4b03bc8cf335f0d19a3e46457db7574a9
3,632,923
def solve_captcha(): """request the captcha solving from the website 2captcha.com""" # Uses the API Key stored in the .env file (If you are not the developer you need to insert it) load_dotenv() data_sitekey = getenv('DATA_SITEKEY') cap_key = getenv('CAP_KEY') if cap_key == '' or data_sitekey =...
8c925475b75d4cd9fa9fb1c6d2118a3771732a89
3,632,924
def StandardMajScale(frequency): """Takes one arguement, frequency. Returns an array of 8 frequencies from 12 TET chromatic scale""" EightSteps = [] freqArray = Create12TETChromatic(frequency) steps = (0, 2, 4, 5, 7, 9, 11, 12) for i in steps: scale = freqArray[i] EightSteps.append(s...
094949fe9188f50a1fea203ab977a1e740163ab6
3,632,925
def interpolate_observing_conditions( timestamps: np.ndarray, df: pd.DataFrame, parameter_key: str, ) -> np.ndarray: """ Take the values of the observing conditions in the data frame ``df`` and interpolate them temporally so that we get values for the timestamp of each frame. The interp...
8e7385f2d265203454d8e7503691820b9695f985
3,632,926
def _mn_min_ ( self , maxcalls = 5000 , tolerance = 0.01 , method = 'MIGRADE' ) : """Perform the actual MINUIT minimization: >>> m = ... # >>> m.fit() ## run migrade! >>> m.migrade () ## ditto >>> m.fit ( method = ...
138fc2dd31e85836ba0e5b4a62f5749fb8aad85c
3,632,927
def old_func4(self, x): """Summary. Further info. """ return x
7417bc8b52ec36a510a73cc8669a92b3603e6169
3,632,928
def sensible_pname(egg_name): """Guess Debian package name from Egg name.""" egg_name = safe_name(egg_name).replace('_', '-') if egg_name.startswith('python-'): egg_name = egg_name[7:] return "python-%s" % egg_name.lower()
3b7446bcae90c249104431d56a4025efcbe993db
3,632,929
def shuffle_split_data(X, y): """ Shuffles and splits data into 70% training and 30% testing subsets, then returns the training and testing subsets. """ # Shuffle and split the data X_train, X_test, y_train, y_test = crossval.train_test_split(X, y, test_size=0.30, random_state=101) # Retur...
03527b0bd24ed4b642ca223dde3faba4a4a8cea2
3,632,930
import copy def get_agent_params(): """Gets parameters passed to the agent via kernel cmdline or vmedia. Parameters can be passed using either the kernel commandline or through virtual media. If boot_method is vmedia, merge params provided via vmedia with those read from the kernel command line. ...
283f9e881587aff4838e81c06dccdd0e90575d5b
3,632,931
def wrap_maya_ui(mayaname): """Given the name of a Maya UI element of any type, return the corresponding QWidget or QAction. If the object does not exist, returns None :param mayaname: the maya ui element :type mayaname: str :returns: the wraped object :rtype: QObject | None :raises: No...
341ad84f85806070202df3a2e20bdc823b6a3608
3,632,932
def FloatSpin(parent, value=0, action=None, tooltip=None, size=(100, -1), digits=1, increment=1, **kws): """FloatSpin with action and tooltip""" if value is None: value = 0 fs = fspin.FloatSpin(parent, -1, size=size, value=value, digits=digits, increment=inc...
45f515195ab209f19b59ba1d44693d97ff45cfab
3,632,933
def generate_config(context): """ Entry point for the deployment resources. """ resources = [] project_id = context.env['project'] bucket_name = context.properties.get('name') or context.env['name'] # output variables bucket_selflink = '$(ref.{}.selfLink)'.format(bucket_name) bucket_uri = ...
5ceca9cf90b5435368ffdb9bdcf1532eec31ec64
3,632,934
def get_vaccine_admin_summary(): """Returns DataFrame about COVID-19 vaccine administration in Italy (summary version) Parameters ---------- None Raises ------ ItaCovidLibConnectionError Raised when there are issues with Internet connection. Returns ------- ...
5296d24d2926599aa8168e89137b1f1f834e6e56
3,632,935
from typing import IO def _get_atlassian_plugin_xml_from_jar_bytes(jar_bytes: IO[bytes]) -> str: """Opens the jar on the provided path and tries to find the atlassian-plugin.xml in this file Args: path (pathlib.Param): the path to the jar file Returns: str: the content of atlassian_plu...
550120b6fad9f70dda6f101d5edbb930d1826590
3,632,936
def get_objects(si, args): """ Return a dict containing the necessary objects for deployment. """ # Get datacenter object. datacenter_list = si.content.rootFolder.childEntity if args.datacenter_name: datacenter_obj = get_obj_in_list(args.datacenter_name, datacenter_list) else: ...
93f7e036523245d3a2d07c3e7bda9ca177dd38ab
3,632,937
def isPulledMayaReference(dagPath): """ Verifies if the DAG path refers to a pulled prim that is a Maya reference. """ _, _, _, prim = getPulledInfo(dagPath) return prim and prim.GetTypeName() == 'MayaReference'
86bab6b200b55b58c5968b61cfffcbf61c0ece75
3,632,938
import re def _read_record7(fid, key1, key2, line, data): """ Saves metadata to ``data.stations[key]`` and ``data.recording[key]`` that is used to preallocate arrays for data recording for ``fort.7#`` type ADCIRC output files :param fid: :class:``file`` object :param string key1: ADCIRC Outpu...
b50e6aa6dcec631ec45ff905557f1dddea5a9b8b
3,632,939
def tw_mock(): """Returns a mock terminal writer""" class TWMock: WRITE = object() def __init__(self): self.lines = [] self.is_writing = False def sep(self, sep, line=None): self.lines.append((sep, line)) def write(self, msg, **kw): ...
a843503d3e360ed4412a020a4ec37f302ec4edaa
3,632,940
import sqlite3 def sql_get_user(mitarbeiter_id): """ SQL module for compiling user information. Name, Surname [and Mail Address] :param mitarbeiter_id: :return: """ conn = sqlite3.connect(db) c = conn.cursor() c.execute("SELECT name, nachname FROM mitarbeiter WHERE id_mitarbeiter=?", (...
4f6bf235499222437235959dd8a444b031c64cdc
3,632,941
def matsubtraction(A,B): """ Subtracts matrix B from matrix A and returns difference :param A: The first matrix :param B: The second matrix :return: Matrix difference """ if(len(A)!=len(B) or len(A[0])!=len(B[0])): return "Subtraction not possible" for i in range(len(...
e10ca0e218d7995c0052928b4be96c2bae8959e7
3,632,942
from typing import OrderedDict def order_keys(order): """ Order keys for JSON readability when not using json_log=True """ def processor(logger, method_name, event_dict): if not isinstance(event_dict, OrderedDict): return event_dict for key in reversed(order): ...
b3ddc250dc6a7e76b8d980ab81fbf4a9de3d6268
3,632,943
import os def get_backend(): """ Returns the currently used backend. Default is tensorflow unless the VXM_BACKEND environment variable is set to 'pytorch'. """ return 'pytorch' if os.environ.get('VXM_BACKEND') == 'pytorch' else 'tensorflow'
ae93dcf95c5712189d603a9a12f32298c32937b5
3,632,944
def _combine_concat_plans(plans, concat_axis: int): """ Combine multiple concatenation plans into one. existing_plan is updated in-place. """ if len(plans) == 1: for p in plans[0]: yield p[0], [p[1]] elif concat_axis == 0: offset = 0 for plan in plans: ...
1bcdace5c947c7f93dc71bbd24b28eec6cb0e9c1
3,632,945
def burn(lower_rgb, upper_rgb): """Apply burn blending mode of a layer on an image. """ return np.maximum(1.0 - (((1.0 + np.finfo(np.float64).eps) - lower_rgb) / upper_rgb), 0.0)
1c1bd80de5bcc7d2e46747a206924af2f9096f2c
3,632,946
from typing import Callable from re import T import inspect def paramCheck(function: Callable[..., T], allow_none: bool = True) -> Callable[..., T]: """ Return a decorator that performs runtime checks on the input types. :param function: function to be checked against its typing annotations :param al...
b49ff50ca1b085db18701bf12a911f9ac831eeed
3,632,947
def fixture_org(context: RBContext, org_id: str) -> RBOrganization: """Get RBOrganization.""" return RBOrganization(context, org_id)
6d92018c51738e3631263434c6430078790ac239
3,632,948
import csv def load_proxies_from_csv(path_to_list): """ Функция, которая загружает прокси из CSV-файла в список.      Входные данные: путь к CSV-файлу, содержащему прокси, описываемый полями: «ip», «port», «protocol».      Выходы: список, содержащий прокси, хранящиеся в именованных кортежах. """ Pr...
8082add1f69e6d4cb4c2bbb4971757224a6366db
3,632,949
def mpls_label_group_id(sub_type, label): """ MPLS Label Group Id sub_type: - 1: L2 VPN Label - 2: L3 VPN Label - 3: Tunnel Label 1 - 4: Tunnel Label 2 - 5: Swap Label """ return 0x90000000 + ((sub_type << 24) & 0x0f000000) + (label & 0x00ffffff)
f0235d1cd8baaf601baf0db43b81417d3d5823ac
3,632,950
import logging def compare_results(out_dict, known_problems_dict, compare_warnings): """Compare the number of problems and warnings found with the allowed number""" ret = 0 for key in known_problems_dict.keys(): try: if out_dict[key]['problems'] > known_problems_dict[key]['problems...
96cde5d5202d62a7cf135eb6af9b84bee64e22aa
3,632,951
def compute_accuracy(ground_truth, predictions, display=False, mode='per_char'): """ Computes accuracy :param ground_truth: :param predictions: :param display: Whether to print values to stdout :param mode: if 'per_char' is selected then single_label_accuracy = correct_predicted...
3414970a6c98245dc630a9dfac8677978ad6283d
3,632,952
import re def is_decodable(s1): """ try hard to decode the input chemical formula useful for recognizing those strings from nist database """ for s in ['-','=','#',]: s1 = remove_element(s1, s) if ('(' in s1) and (')' in s1): while True: if not ('(' in s1): ...
4629aa560369e191550ef7c8c5cce81499596332
3,632,953
def ensure_int_vector(I, require_order = False): """Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ...
9234442631e13462df6c4d557cda8cee14a06035
3,632,954
def lgt_to_gt(lgt, la): """A method for transforming Local GT and Local Alleles into the true GT""" return hl.call(la[lgt[0]], la[lgt[1]])
1d655f561c6b38c935b856862d568c277e5925b1
3,632,955
def ascat(scan_nb, scan_points=None): """ASCAT make two scans one to the left and one to the right of the sub-satellite track. """ if scan_points is None: scan_len = 42 # samples per scan scan_points = np.arange(42) else: scan_len = len(scan_points) scan_angle_inner =...
ef7748283d41a4a2a15d55dd07d27dda146cdb91
3,632,956
from typing import Optional from typing import Mapping from typing import Any def ensure_csv( key: str, *subkeys: str, url: str, name: Optional[str] = None, force: bool = False, download_kwargs: Optional[Mapping[str, Any]] = None, read_csv_kwargs: Optional[Mapping[str, Any]] = None, ): ...
91fc051fd712bed0cb7cda44b7c022607f28fc98
3,632,957
def energy_scan(sim_func, sim_kwargs, energies, parallel=False): """ This function provides a convenient way to repeat the same simulation for a number of different electron beam energies. This can reveal variations in the charge state balance due to weakly energy dependent ionisation cross sections or ...
30c1fa9d85832ca27354297815ea57f0701c856d
3,632,958
import random def random_walk_memory(world_state, pose, visited): """ Returns a random valid neighboring cell that is not recently visited. Can return visited cells if there is no other option """ nbors = get_orthogonal_nbors(world_state, pose) # Get neighbors that aren't recently visited new_...
00b75c1e0f8635874c505b9d19b15be19e45f5ab
3,632,959
def run_file_mask(fmask, fname, fbase=0): """extract temporal data from file name """ if fbase and fname.startswith(fbase): fname = fname[fname.index(fbase) + len(fbase) + 1:] output = { "year": "".join([x for x,y in zip(fname, fmask) if y == 'Y' and x.isdigit()]), "month": ""....
f13bff19ae7b3a3bbef258c7bf5830a6b1114b1a
3,632,960
import torch def get_spin_interp(zeta: torch.Tensor) -> torch.Tensor: """Compute spin interpolation function from fractional polarization `zeta`.""" exponent = 4.0 / 3 scale = 1.0 / (2.0 ** exponent - 2.0) return ((1.0 + zeta) ** exponent + (1.0 - zeta) ** exponent - 2.0) * scale
b1abced09aead7394be773d93d59a621cda98d14
3,632,961
import inspect def get_interpolator(func, varname, df, default_time, docstring): """Creates time interpolator with custom signature""" #extract source code from time_interpolator src = inspect.getsource(time_interpolator) #create variable-dependent signature new_src = (src \ .format(do...
998429f17e74a76d440020552d0da7d43fda026a
3,632,962
def inverse_cdf_coupling(logits_1, logits_2): """Constructs the matrix for an inverse CDF coupling.""" dim, = logits_1.shape p1 = jnp.exp(logits_1) p2 = jnp.exp(logits_2) p1_bins = jnp.concatenate([jnp.array([0.]), jnp.cumsum(p1)]) p2_bins = jnp.concatenate([jnp.array([0.]), jnp.cumsum(p2)]) # Value in b...
e5ad6b35ea0625b5416f0c1bf746206ca02ffcf1
3,632,963
import os def get_all_datasets(all_logdirs, legend=None, select=None, exclude=None): """ For every entry in all_logdirs, 1) check if the entry is a real directory and if it is, pull data from it; 2) if not, check to see if the entry is a prefix for a real directory, and ...
158fcb8cb181cb71eade93bf8b113db82b0525b6
3,632,964
def certificate(): """ Certificates Controller """ mode = session.s3.hrm.mode def prep(r): if mode is not None: r.error(403, message=auth.permission.INSUFFICIENT_PRIVILEGES) return True s3.prep = prep if settings.get_hrm_filter_certificates() and \ not auth.s3_ha...
9317c7f60728a1c9230d831e4161fefe4845bda5
3,632,965
import asyncio import logging async def _run_given_tasks_async(tasks, event_loop=asyncio.get_event_loop(), executor=None): """ Given list of Task objects, this method executes all tasks in the given event loop (or default one) and returns list of the results. The list of the results are in the same or...
296ce85a5f806f52a3965d6d1ac259fe3095c8d4
3,632,966
def fileno(): """ Return the file number of the current file. When no file is currently opened, returns -1. """ if not _state: raise RuntimeError("no active input()") return _state.fileno()
eedcba17c20d9de81c5435c0689efabab861b49a
3,632,967
def word_show(vol, guess, store): """ param vol: str, the word from def random_word param guess: str, the letter user guessed param store: str, the string showing correct letters user guessed return: str, answer """ answer = '' if guess == '': for i in vol: answer += ...
65178dda52c61abbae682878dcf2439f20e51b5f
3,632,968
def convert_yt_music(input_url: str) -> str: """ Convert a YouTube Music link to a YouTube link. YouTube Music videos share the same `v` URL parameter as their YouTube counterparts and hence can be processed like YouTube URLs after making changes to the URL This function replaces the `music.youtube...
77e09438498e5fbab52d8da29fdde8508e6d10cc
3,632,969
import torch def get_feature_attributions(args, model_list, data_x_list, data_y_list, col_names, is_mgmc): """Get feature attributions. Get feature attributions for given list of saved Pipeline models and output dataset lists from get_train_test_dataset_list(). Args: ...
5b5167b4f271e5355cdfba485a22acea7e843b63
3,632,970
def bspline_fit(x,y,order=3,knots=None,everyn=20,xmin=None,xmax=None,w=None,bkspace=None): """ bspline fit to x,y Should probably only be called from func_fit Parameters ---------- x: ndarray y: ndarray func: str Name of the fitting function: polynomial, legendre, chebyshev, bsplin...
a7db0bef96e3c0211cc380d33db179efa2786e73
3,632,971
def request(s): """ Returns a :class:`Request` object for the given string. :param str s: The string containing the request line to parse :returns: A :class:`Request` tuple representing the request line """ try: method, s = s.split(' ', 1) except ValueError: raise ValueError...
7e057d425ee76c6986c71f0a4c572e632063cd98
3,632,972
def _gradual_sequence(start, end, multiplier=3): """Custom nodes number generator The function gives the list of exponentially increase/decrease integers from both 'start' and 'end' params, which can be later used as the number of nodes in each layer. _gradual_sequence(10, 7000, multiplier=5) gives ...
8b42931600cb14b84621f6619ef695f1adee641c
3,632,973
import requests def get_group_clusters(group_name): """ Returns list of clusters administered by group :return: list """ access_token = get_user_access_token(session) query = {'token': access_token} group_clusters = requests.get( slate_api_endpoint + '/v1alpha3/groups/' + group_na...
f926105e28f2bdf18036f0f41ca0969551f63c47
3,632,974
import array def Q_continuous_white_noise(dim, dt=1., spectral_density=1.): """ Returns the Q matrix for the Discretized Continuous White Noise Model. dim may be either 2 or 3, dt is the time step, and sigma is the variance in the noise. Parameters ---------- dim : int (2 or 3) dimen...
0bc0e1ebcc91eca5d79ded101739e7266dd77f29
3,632,975
import time def timeit(func): """calculate time for a function to complete""" def wrapper(*args, **kwargs): start = time.time() output = func(*args, **kwargs) end = time.time() print('function {0} took {1:0.3f} s'.format( func.__name__, (end - start) * 1)) ...
13a86c9475ce547a7b5e7e54ad7373f833920b41
3,632,976
from typing import Tuple def make_test_label_and_intensity_images_no_internal_2d() -> Tuple[ np.ndarray, np.ndarray, np.ndarray, np.ndarray ]: """Create 2D test data where label 2 has no internal pixels""" label_image = np.zeros((40, 40), dtype=int) label_image[10:20, 10:20] = 1 label_image[25:27,...
9bda083fe43cee45e3e2157a19264ee40e6282b6
3,632,977
import os def get_mock_image(): """ Return a canned test image (1 band of original NetCDF raster) """ nc = os.path.join(script_dir, 'resources/HadGHCND_TXTN_anoms_1950-1960_15052015.nc') with open(nc, 'rb') as ncfile: return ncfile.read()
77fdb4acd4e8b660a5dde458f266e186fc175675
3,632,978
from typing import Optional def get_database_acl(instance_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseAclResult: """ Gets information about the RDB instance network Access Control List. ## Example Usage ```python import pulum...
06d05a544dfa5ee3992f2798f406cd81394660be
3,632,979
import sys import subprocess def run_suite(project, suite_name): """Run a suite. This is used when running suites from the GUI""" script_name = sys.argv[0] if script_name[-5:] != 'golem' and script_name[-9:] != 'golem.exe': if sys.platform == 'win32': script_name = 'golem' else...
d737076b516574780d33e5c028e4694993ad0049
3,632,980
def get_cancellations(es_cfg): """Calls external scheduler and returns task cancellations.""" req = plugin_pb2.GetCancellationsRequest() req.scheduler_id = es_cfg.id c = _get_client(es_cfg.address) resp = c.GetCancellations(req, credentials=_creds()) return resp.cancellations
bceadcfe984b5338e9c2a9010ce4cd60f256c5d4
3,632,981
def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 j = 0 len_n = len(nums) for i in range(len_n): if nums[j] != nums[i]: nums[j + 1] = nums[i] j += 1 return j + 1
3020be29ad6499dfcb1dcfae6a09b91a11ccfc38
3,632,982
def GetUserGender(user_url: str) -> int: """获取用户性别 Args: user_url (str): 用户个人主页 Url Returns: int: 用户性别,0 为未知,1 为男,2 为女 """ AssertUserUrl(user_url) AssertUserStatusNormal(user_url) json_obj = GetUserJsonDataApi(user_url) result = json_obj["gender"] if result == 3: #...
474db93e37092999ff04358530b3945c92da5be7
3,632,983
def do_menu_action(action): """Execute menu action!""" return { 'help': help, 'inventory': print_inventory, 'game': print_game_status, 'quit': save_game, }.get(action, (lambda: ''))()
be03cdf66fb80a1c67ec7eac653d70e151f242f2
3,632,984
def test_mixed_optimization(): """ Checks if variables with mixed constraints are optimized correctly together. """ def get_loss(mean): def loss(x, y, z): return (x + y + z - mean) ** 2 return loss # Fix seed tf.random.set_seed(42) # Create variables v1 =...
e0e62d320785e0f0e10e057cfb26f3c96d644368
3,632,985
def SepConv_BN(x, filters, prefix, stride=1, kernel_size=3, rate=1, depth_activation=False, epsilon=1e-3): """ SepConv with BN between depthwise & pointwise. Optionally add activation after BN Implements right "same" padding for even kernel sizes Args: x: input tensor filters...
c7d71cad82d26f4afdde67455f18508970f15fca
3,632,986
from functools import reduce def dot_prod_numpy(T): """Calculate dot product over last two axis of a multi dimensional matrix""" # reverse along domain axis, see comment in next function return np.array([reduce(np.dot, Tn) for Tn in T[:, ::-1, ...]])
9e4ff3ab5b66ffad18557e3bf20ef3bbfad3b527
3,632,987
def create_pretrain_mask(tokens, mask_cnt, vocab_list): """ masking subwords(15% of entire subwords) - mask_cnt: len(subwords) * 0.15 - [MASK]: 80% of masking candidate token - original token: 10% of masking candidate token - another token: 10% of masking candidate token """ candidate_id...
98364c713ab00644e0deb30b69d06ea1e00e0097
3,632,988
def string2token(t,nl,nt): """ This function takes a string and returns a token. A token is a tuple where the first element specifies the type of the data stored in the second element. In this case the data types are limited to numbers, either integer, real or complex, and strings. The types...
23fd5da01a49076b1fcf474fbe1047329ad7471a
3,632,989
def fitness_func(loci, **kwargs): """ Return how fit the locus is to describe a quarter of circle. It is a minisation problem and the theorical best score is 0. Returns ------- float Sum of square distances between tip locus bounding box and a defined square. """ # Locu...
c0ae31416acfc62726f47db1b2dc6de52e609df7
3,632,990
def get_div(integer): """ Return list of divisors of integer. :param integer: int :return: list """ divisors = [num for num in range(2, int(integer**0.5)+1) if integer % num == 0] rem_divisors = [int(integer/num) for num in divisors] divisors += rem_divisors divisors.append(integer) ...
4c40a2b2da1d9681c1d7ca69a53975dd27c7bdb8
3,632,991
def ifuse(inputs): """Fuse iterators""" value, extent = 0, 1 for i, ext in inputs: value = value * ext + i extent = extent * ext return (value, extent)
42c65ec62e637b668125ed27aad517d3301a7aff
3,632,992
def filtered_list_gen(raw_response, term=None, partial_match=True): """ Iterates over items yielded by raw_response_gen, validating that: 1. the `path` dict key is a str 2. the `path` value starts with starts_with (if provided) >>> r = [{ >>> 'checksum': { >>> 'md5': 'd9...
167da6e68c0450eb76ccb3697beee87de5dae4fb
3,632,993
import random def occlude_with_pascal_objects(im, occluders): """Returns an augmented version of `im`, containing some occluders from the Pascal VOC dataset.""" result = im.copy() width_height = np.asarray([im.shape[1], im.shape[0]]) im_scale_factor = min(width_height) / 256 count = np.random...
1a60aa501b7424de454d6d8fba6c5926ab90240d
3,632,994
def check_job_access_permission(request, job_id): """ Decorator ensuring that the user has access to the job submitted to Oozie. Arg: Oozie 'workflow', 'coordinator' or 'bundle' ID. Return: the Oozie workflow, coordinator or bundle or raise an exception Notice: its gets an id in input and returns the full o...
80e8c7e610c96e275aed23f4e24ad96520da171e
3,632,995
from typing import get_origin def is_dict_type(tp): """Return True if tp is a Dict""" return ( get_origin(tp) is dict and getattr(tp, '_name', None) == 'Dict' )
3b9992b7b131e936472d4d0e2994ac476f0d0f76
3,632,996
def shape(pyshp_shpobj): """Convert a pyshp geometry object to a flopy geometry object. Parameters ---------- pyshp_shpobj : shapefile._Shape instance Returns ------- shape : flopy.utils.geometry Polygon, Linestring, or Point Notes ----- Currently only regular Polygons, LineStrin...
39e6152c680a4358e980095d090a0e724bc9338c
3,632,997
def compute_nbr(image, sensor): """ Compute nbr index NBR = (NIR-SWIR2)/(NIR+SWIR2) """ bands = cp.sensors[sensor]["bands"] nir = image.select(bands["nir"]) swir2 = image.select(bands["swir2"]) doy = ee.Algorithms.Date(ee.Number(image.get("system:time_start"))) yearday = ee.Number...
005b965e93d0f4455e01a7aae949631b94e13b16
3,632,998
def unbroadcast(array): """ Given an array, return a new array that is the smallest subset of the original array that can be re-broadcasted back to the original array. See http://stackoverflow.com/questions/40845769/un-broadcasting-numpy-arrays for more details. """ if array.ndim == 0: ...
e7a205a325dc3000a920df441c5b861f66c8c3c8
3,632,999