content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from typing import Callable def register_scale( convert_to: Dict[str, Callable] = None, convert_from: Dict[str, Callable] = None ) -> Callable[[Callable], Callable]: """Decorator used to register new time scales The scale name is read from the .scale attribute of the Time class. ...
3adcd0d53a3c1622f81a1c444da19c4f2b332d14
31,100
import torch def get_top_down_ground_truth_static_ego(env_id, start_idx, img_w, img_h, map_w, map_h): """ Returns the ground-truth label oriented in the global map frame :param env_id: :param start_idx: :param img_w: :param img_h: :param map_w: :param map_h: :return: """ pa...
3987d91e903eff2bd48e331f33b9c0ea583ff5e0
31,101
def read_project(config_path, timesheet_path=None, replicon_options=None): """ Read a project dictionary from a YAML file located at the path ``config_path``, and read a project timesheet from the path ``timesheet_path``. Parse these files, check them, and, if successful, return a corresponding Project inst...
b3b13bd1594f3d1ba0ba3b53af5f8546c59f39ee
31,102
from typing import Union from typing import Tuple def _parse_query_location( location: Union[Tuple[float, float], Point, MultiPoint, Polygon] ) -> str: """Convert given locations into WKT representations. Args: location (QueryLocation): Provided location definition. Raises: ValueErro...
17e57b9521144c61c6069d52a8ebcad6101882aa
31,103
def getuniqueitems(userchoices): """return a list of unique items given a bunch of userchoices""" items = [] for userchoice in userchoices: if userchoice.item not in items: items.append(userchoice.item) return items
a7885556604153cf756fb6a29c2e870c27d47337
31,104
def _as_array(arr, dtype=None): """Convert an object to a numerical NumPy array. Avoid a copy if possible. """ if arr is None: return None if isinstance(arr, np.ndarray) and dtype is None: return arr if isinstance(arr, integer_types + (float,)): arr = [arr] out = np.a...
d0336a8cedcd324d5dd26a7b98f59d70f691cf1d
31,105
def stitch_together_target_regions(cluster, flanking=500, logger=None, circular=False, revcomp=False): """ given a single LociCluster object containing Locus objects (usually) of length 3 (16,5,and 23 rR...
4ec89a7d9d88874f3a1b8fb42abafec5d65633d1
31,106
def add_region(): """ add a region page function """ # init variables entry = Region() # creates a model.py instance, instance only has a name right now error_msg = {} form_is_valid = True country_list = Country.query.all() if request.method == 'GET': return render_template('regio...
0798a7bec6474cf83dd870b6529e8f57b69bc882
31,107
import six def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ This function was excerpted from Django project, modifications have been applied. The original license is as follows: ``` Copyright (c) Django Software Foundation and individual contributors. All rights reserv...
e4040ea31669acbdbfee5db9f6ce30acdc40bae1
31,108
def get_host(hostname): """ Get information about backups for a particular host """ print(f"\nSearching for host '{ hostname }'...\n") backuppc_data = get_backup_data() for host in backuppc_data: if host['hostname'] == hostname: return host
5b017be557d9b5340e44905a49ea6ee2b1ea30b3
31,109
def gazebo_get_gravity() -> Vector3: """ Function to get the current gravity vector for gazebo. :return: the gravity vector. :rtype: Vector3 """ rospy.wait_for_service("/gazebo/get_physics_properties") client_get_physics = rospy.ServiceProxy("/gazebo/get_physics_properties", GetPhysicsProp...
8ec560e1fd276be9d2677f94dc5d9b5017e81d23
31,110
def make_mock_device(): """ Create a mock host device """ def _make_mock_device(xml_def): mocked_conn = virt.libvirt.openAuth.return_value if not isinstance(mocked_conn.nodeDeviceLookupByName, MappedResultMock): mocked_conn.nodeDeviceLookupByName = MappedResultMock() ...
80b9b51f586c2b373478020b2a08276e97a6d5ba
31,111
from typing import Union def load_file(file_name: str, mode: str = "rb") -> Union[str, bytes]: """Loads files from resources.""" file_path = get_resource_path(file_name) with open(file_path, mode) as file: return file.read()
ed535b091f3ae853e60610022ef01bb38c67b41e
31,112
def path_graph(n, create_using=None): """Returns the Path graph `P_n` of linearly connected nodes. Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. create_using : NetworkX graph construct...
53eabfd815b3c37f6b7e8e8e54e1a0357c0fcca9
31,113
def numpy_shift(array: np.ndarray, periods: int, axis: int, fill_value=np.nan) -> np.ndarray: """ numpy implementation for validation """ assert axis in range(-array.ndim, array.ndim) copy_src_indices = [slice(None)] * array.ndim copy_dst_indices = [slice(None)] * array.ndim fill_indices = ...
3ffc61a61abc5bdc3547822c0715a81efb9d0b4d
31,114
def draw_rect(im, cords, color = None): """Draw the rectangle on the image Parameters ---------- im : numpy.ndarray numpy image cords: numpy.ndarray Numpy array containing bounding boxes of shape `N X 4` where N is the number of bounding boxes and the boundin...
02c52166f0f9c25d9f9ad61f7083d7ee733759aa
31,115
from typing import List def _setup_entities(hass, dev_ids: List[str]): """Set up CAME light device.""" manager = hass.data[DOMAIN][CONF_MANAGER] # type: CameManager entities = [] for dev_id in dev_ids: device = manager.get_device_by_id(dev_id) if device is None: continue ...
5c9deb213b5df197aaf075f62a68c1472951a3e0
31,116
import binascii import os def image_url_salt(): """Helper function that generates salt to append to an image URL to prevent browser caches from loading old images""" return binascii.b2a_hex(os.urandom(4)).decode('us-ascii')
0b8c803682ff21b56c039a12da184d699ffc47e7
31,117
def check_doa(geometry, doa, online=False): """ Check value of the DoA """ if not online: doas = [doa] else: doas = doa for doa in doas: if doa < 0: return False if geometry == "linear" and doa > 180: return False if geometry == "ci...
ae2be5c478968358a9edf6e7da63e586af39eed8
31,118
def reconnect(force=False, **kwargs): # pylint: disable=unused-argument """ Reconnect the NAPALM proxy when the connection is dropped by the network device. The connection can be forced to be restarted using the ``force`` argument. .. note:: This function can be used only when running...
5150041bdf62c01335b8fb1e25639afc2e7256b2
31,119
import sys def ask_user_for_half_life(access_key): """Ask the user for a half life value""" day_choice = "One day" hour_choice = "One hour" week_choice = "One week" forever_choice = "forever" while True: choice = ask_for_choice_or_new("What half life do you want for this key? ({0})".f...
b91a70eb11450f772bd12ff39d061204c34f860b
31,120
def _trim_orderbook_list(arr: list, ascending: bool, limit_len: int = 50) -> list: """trims prices up to 4 digits precision""" first_price = arr[0][0] if first_price < 0.1: unit = 1e-5 elif first_price < 1: unit = 1e-4 elif first_price < 10: unit = 1e-3 elif first_price <...
557dceab9b11836b2f884ebc40d1e66769f5eb4c
31,121
from corpkit.process import make_name_to_query_dict def process_piece(piece, op='=', quant=False, **kwargs): """ Make a single search obj and value """ if op not in piece: return False, False translator = make_name_to_query_dict() target, criteria = piece.split(op, 1) criteria = c...
2d79455fcc27e0b3b9a81209cdc28089a7b73f5a
31,122
import random def normal220(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(bb1)...
d83408e8d5ec18d0a6de2aee62ca12aa5f1561b8
31,123
def sigma_voigt(dgm_sigmaD,dgm_gammaL): """compute sigma of the Voigt profile Args: dgm_sigmaD: DIT grid matrix for sigmaD dgm_gammaL: DIT grid matrix for gammaL Returns: sigma """ fac=2.*np.sqrt(2.*np.log(2.0)) fdgm_gammaL=jnp.min(dgm_gammaL,axis=1)*2.0 fdgm_sigm...
27581dc61e04d2f5b1411cb64093e03378bb8297
31,124
def zigzag2(i, curr=.45, upper=.48, lower=.13): """ Generalized version of the zig-zag function. Returns points oscillating between two bounds linearly. """ if abs(i) <= (upper-curr): return curr + i else: i = i - (upper-curr) i = i%(2*(upper-lower)) if i < (u...
a51624af520121eb7285b2a8a5b4dc5ffa552147
31,125
def get_len_of_range(start, stop, step): """Get the length of a (start, stop, step) range.""" n = 0 if start < stop: n = ((stop - start - 1) // step + 1); return n
4c43f502efe7ad0e20a9bc7624e6d47e208a94a7
31,126
def generate_tap(laygen, objectname_pfix, placement_grid, routing_grid_m1m2_thick, devname_tap_boundary, devname_tap_body, m=1, origin=np.array([0,0]), transform='R0'): """generate a tap primitive""" pg = placement_grid rg_m1m2_thick = routing_grid_m1m2_thick # placement itapbl0 = ...
59f3ceeee74e8b99690e86b671cbd1e503fe4121
31,127
from typing import Union from typing import Optional def multiply( x1: Union[ivy.Array, ivy.NativeArray], x2: Union[ivy.Array, ivy.NativeArray], out: Optional[Union[ivy.Array, ivy.NativeArray]] = None, ) -> ivy.Array: """Calculates the product for each element ``x1_i`` of the input array ``x1`` with ...
53ce0b715933b59b40abd7f51d7bb104874e54db
31,128
def discriminateEvents(events, threshold): """ Discriminate triggers when different kind of events are on the same channel. A time threshold is used to determine if two events are from the same trial. Parameters ---------- events : instance of pandas.core.DataFrame Dataframe containing ...
0078548ea463c01d88b574185b3dcb5632e5cd13
31,129
def whiten(sig, win): """Whiten signal, modified from MSNoise.""" npts = len(sig) nfreq = int(npts // 2 + 1) assert (len(win) == nfreq) # fsr = npts / sr fsig = fft(sig) # hl = nfreq // 2 half = fsig[: nfreq] half = win * phase(half) fsig[: nfreq] = half fsig[-nfreq + 1:] ...
0c6e4300d7bebc466039ee447c7f6507d211be1c
31,130
def create_slice(request): """ Create a slice based on a pattern. User has to be the "production_request" owner. Steps should contain dictionary of step names which should be copied from the pattern slice as well as modified fields, e.g. {'Simul':{'container_name':'some.container.name'}} :param produ...
c01f15b6b369d9159b02c06ce6e2bc9c63dac50e
31,131
def get_reverse_charge_recoverable_total(filters): """Returns the sum of the total of each Purchase invoice made with recoverable reverse charge.""" query_filters = get_filters(filters) query_filters.append(['reverse_charge', '=', 'Y']) query_filters.append(['recoverable_reverse_charge', '>', '0']) query_filters.a...
95b24a90230675ffda80760d073705f5da823bc8
31,132
import hashlib def load_data(url_bam): """Load ``MetaData`` from the given ``url_bam``.""" if url_bam.scheme != "file": raise ExcovisException("Can only load file resources at the moment") with pysam.AlignmentFile(url_bam.path, "rb") as samfile: read_groups = samfile.header.as_dict().get("...
e5c17b6ad236ebcbd4222bbe5e3cbdb923965325
31,133
import random import string def generate_room_number(): """ Generates a room number composed of 10 digits. """ return "".join(random.sample(string.digits, 10))
133e7463106df89fb68de6a7dfa7c718bc1bc5ba
31,134
def is_noiseless(model: Model) -> bool: """Check if a given (single-task) botorch model is noiseless""" if isinstance(model, ModelListGP): raise ModelError( "Checking for noisless models only applies to sub-models of ModelListGP" ) return model.__class__ in NOISELESS_MODELS
d1b5cfee5713cc44d40a7d0d98542d0d2147a9a3
31,135
def random_sampling_normalized_variance(sampling_percentages, indepvars, depvars, depvar_names, n_sample_iterations=1, verbose=True, npts_bandwidth=25, min_bandwidth=None, max_bandwidth=None, bandwidth_values=None, scale_unit_box=True, n_th...
a340659a363760c01d38dd21b2a439b346751a23
31,136
def classify_data(X_train, Y_train, X_test): """Develop and train your very own variational quantum classifier. Use the provided training data to train your classifier. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. The nu...
7af9c56490a782fb32f289042a23871bfb5f0a85
31,137
def preprocess_embedding(z): """Pre-process embedding. Center and scale embedding to be between -.5, and .5. Arguments: z: A 2D NumPy array. shape=(n_concept, n_dim) Returns: z_p: A pre-processed embedding. """ # Center embedding. z_p = z - np.mean(z, axis=0, ...
6927e606ec61b0504e91b5b19e84a819d3e86274
31,138
import os def get_folders_from_path(path): """ Gets a list of sub folders in the given path :param path: str :return: list<str> """ folders = list() while True: path, folder = os.path.split(path) if folder != '': folders.append(folder) else: ...
4f03c0a1316572c0ab1095ed948c91750a495653
31,139
def T_from_Ts(Ts,P,qt,es_formula=es_default): """ Given theta_e solves implicitly for the temperature at some other pressure, so that theta_e(T,P,qt) = Te >>> T_from_Tl(282.75436951,90000,20.e-3) 290.00 """ def zero(T,Ts,P,qt): return np.abs(Ts-get_theta_s(T,P,qt,es_formula)) return optim...
ae2431127a3d0924da4b1e45d98c72a2c42b7a6c
31,140
import argparse def _get_cli_parser(): """ mideu argparse parser create :return: parser """ parser = argparse.ArgumentParser( description="MasterCard IPM file formatter ({version})".format( version=_version.get_versions()['version']) ) parser.add_argument("--version", ...
fe9294257c8fec87e0705fe8920a8585bea00465
31,141
from typing import Tuple def find_global_peaks_integral( cms: tf.Tensor, crop_size: int = 5, threshold: float = 0.2 ) -> Tuple[tf.Tensor, tf.Tensor]: """Find local peaks with integral refinement. Integral regression refinement will be computed by taking the weighted average of the local neighborhood ...
22529379fdf1e685b33319e0432a95ee51973575
31,142
def test_data(test_data_info, pytestconfig): """Fixture provides test data loaded from files automatically.""" data_pattern = pytestconfig.getoption(constants.OPT_DATA_PATTERN) if test_data_info.subdirs: return list( list(loader.each_data_under_dir( test_data_info.datadi...
639c9b16b9f6e1a4bbb5422d0ce29850535a267b
31,143
def load_maggic_data(): """Load MAGGIC data. Returns: orig_data: Original data in pandas dataframe """ # Read csv files file_name = 'data/Maggic.csv' orig_data = pd.read_csv(file_name, sep=',') # Remove NA orig_data = orig_data.dropna(axis=0, how='any') # Remove labels orig_data = o...
b4d1c219ef892c9218fd45aba22c859c96954853
31,144
def create_res_hessian_computing_tf_graph(input_shape, layer_kernel, layer_stride): """ This function create the TensorFlow graph for computing hessian matrix for res layer. Step 1: It first extract image patches using tf.extract_image_patches. Step 2: Then calculate the hessian matrix by outer product...
aaf5f52b32f1f8f67d54d70c10c706dc26b91a75
31,145
def loadUiType(uiFile): """ Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. http://tech-artists.org/forum/showthread.php?3035-PySide-in-Maya-2013 """ parsed = xml.parse(ui...
2b5bfcdefb0d1c0fb361a4d080eea0b0cc927599
31,146
def ldns_native2rdf_int8(*args): """LDNS buffer.""" return _ldns.ldns_native2rdf_int8(*args)
21e295dcd9a67018bd673dc5ff605e80707d9736
31,147
import re def _ListProcesses(args, req_vars): # pylint: disable=W0613 """Lists processes and their CPU / mem stats. The response is formatted according to the Google Charts DataTable format. """ device = _GetDevice(args) if not device: return _HTTP_GONE, [], 'Device not found' resp = { 'cols':...
636f91e3dcf6b236081787096c12eadf956c9024
31,148
def _runForRunnerUser(resourceDB: ResourceDB, user: User) -> TaskRun: """Returns the task run accessible to the given user. Raises AccessDenied if the user does not represent a Task Runner or the Task Runner is not running any task. """ # Get Task Runner. if not isinstance(user, TokenUser): ...
e3b89ed95bea8c50be885ef56578e23919a7a25c
31,149
def narrow(lon='auto',lat='auto',ax=None,lfactor=1,**kwargs): """ Plot north arrow. Parameters: lon: Starting longitude (decimal degrees) for arrow lat: Starting latitude (ecimal degrees) for arrow ax: Axes on which to plot arrow lfactor: Length factor to increase/decrea...
8d3162ab05366472b607ff953811caf2796c1e3e
31,150
from typing import List from pathlib import Path def dump_content_descriptor(artifact_manager: ArtifactsManager) -> ArtifactsReport: """ Dumping content/content_descriptor.json into: 1. content_test 2. content_new 3. content_all Args: artifact_manager: Artifacts ma...
e39bc38c72cd3f7b555d410d037ef1df3c747933
31,151
def parse_movie(line, sep='::'): """ Parses a movie line Returns: tuple of (movie_id, title) """ fields = line.strip().split(sep) movie_id = int(fields[0]) # convert movie_id to int title = fields[1] return movie_id, title
9d7a13ca3ddf823ff22582f648434d4b6df00207
31,152
def make_plot(dataset, plot_label, xlabel, ylabel, legend): """ Generates a MatPlotLib plot from the specified dataset and with the specified labeling features. make_plot(dataset, plot_label, xlabel, ylabel, legend) -> plt @type dataset: list of list @param dataset: formatted dataset. ...
0e5ff583c65dcd3751354a416d9940a12871e37d
31,153
def flatten_list(in_list: typ.List) -> typ.List: """Flattens list""" result = [] for item in in_list: if isinstance(item, list): result.extend(flatten_list(item)) else: result.append(item) return result
9d847fea7f1eb30ecbd51dd1d001c8661a502a0d
31,154
import logging def formatMessage(data): """ Format incoming message before passing to Discord """ logging.info("Formatting message payload...") time = (data.occurredAt).split("T") message = [":alarm_clock: __**Meraki Alert**__ :alarm_clock: "] message.append(f"**Device:** {data.deviceName}...
21d7a50951aeecb6917479622f4131b7ddcfda00
31,155
def _convert_nearest_neighbors(operator, container, k=None, radius=None): """ Common parts to regressor and classifier. Let's denote *N* as the number of observations, *k* the number of neighbours. It returns the following intermediate results: top_indices: [N, k] (int64), best indices for ...
c328d2f78467df05ddcfd83186e0704e234eabd8
31,156
import click def interface_alias_to_name(config_db, interface_alias): """Return default interface name if alias name is given as argument """ vlan_id = "" sub_intf_sep_idx = -1 if interface_alias is not None: sub_intf_sep_idx = interface_alias.find(VLAN_SUB_INTERFACE_SEPARATOR) if ...
6cac69be850a65dda505999616e4d21d0a8c9438
31,157
import time def twait(phrase, tn, tout=-1, logging='off', rcontent=False, screenprint=False): """ telnetlib wait with optional timeout and optional logging""" # Adding code to allow lists for phrase finalcontent = ' ' #This is the time of the epoch startTime = int(time.time()) while True: ...
9c4308e873321fd556d8eec2668981fc2843ae87
31,158
def process_ob(obs : dict) -> dict: """ Processes an individual post :param obs: video observation metadata :returns: processed post metadata based on tags in posts_titles """ metadata = {tag: obs[tag] for tag in obs_tags} metadata.update(process_obs(obs["children"], obs["history"])) metad...
e5200443d6ba6e69d49fb56d377f4a9992f157bb
31,159
from beta import calc_beta_eta def calc_detectable_frac(gen, model, args, gen2=None, swap_h0_and_h1=False, verbose=0): """ :param gen: sample generator :param model: NN model :param args: parameters object (should contain alpha and beta attributes) :param gen2: if gen2 is not None gen output is u...
6844abc148cee69453eb3136e018a40eccb40334
31,160
import numpy as np from typing import Tuple def similarity_std( buffer: NumpyNDArray, wav_file: WavFile, rate: int, threshold: float ) -> Tuple[bool, float, float]: """Check the similarity of a recorded sound buffer and a given wav_file. Use a correlation check using the standard deviation.""" _, ...
8900495860f59b39be3f5f3808bb321e0275bc81
31,161
def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs): """ Sample grids at specified (x,y) locations. Grdtrack reads one or more grid files and a table with (x,y) [or (lon,lat)] positions in the first two columns (more columns may be present). It interpolates the grid(s) at the positi...
ed6a09c4f925321520c99e2a941602e82852bec3
31,162
def add(x, y): """add two number""" return x+y
9c5fe5867e0c345bd3e7439b8fc76c21b20b2c35
31,163
def is_exponential(character: str) -> bool: """ Whether an IPA character is written above the base line and to the right of the previous character, like how exponents of a power are written in mathematical notation. """ return character in exponentials
0d263a0969454ad9d8e7a3a53e393b55b5c8d45c
31,164
def _union_items(baselist, comparelist): """Combine two lists, removing duplicates.""" return list(set(baselist) | set(comparelist))
782f325960db2482afc75e63dbc8a51fea24c8d0
31,165
import os def setLanguage(languageName): """ setLanguage(languageName) Set the language for the app. Loads qt and pyzo translations. Returns the QLocale instance to pass to the main widget. """ # Get locale locale = getLocale(languageName) # Get paths were language files are qtTransP...
0b70e774636936f6c4df68440605c369788676fd
31,166
def broadcast_state(state=current_state, ip=ip_osc, port=port_client): """ Broadcasts state """ print("Called Broadcast State Function") #client = udp_client.UDPClient(ip, port,1) #builder = osc_message_builder.OscMessageBuilder(address='/status') #for k,v in state.items(): # builde...
be8b391cbd033b7271796ec47529b8ca78f85bd5
31,167
def make_gaussian(shape, var): """returns 2d gaussian of given shape and variance""" h,w = shape x = np.arange(w, dtype=float) y = np.arange(h, dtype=float)[:,np.newaxis] x0 = w // 2 y0 = h // 2 mat = np.exp(-0.5 * (pow(x-x0, 2) + pow(y-y0, 2)) / var) normalized_img = np.zeros((h, w)) ...
88500f08c43b446ea073fef322f2007ea4032875
31,168
from typing import Optional from typing import Callable import os def add_button(_editor: Editor, /, *, # Keyword-only arguments icon: Optional[str] = None, cmd: Optional[str] = None, # Defaults to calling get_unique_cmd func: Callable[[Editor], None], ...
bb4c740823fc15d8897d09abdf4dfbdf4938be43
31,169
def analysis_iou_on_miyazakidata(result_path, pattern="GT_o"): """对最终4张图片统合的结果进行测试""" ious = [] pattern1, pattern2 = pattern.strip().split("_") pattern1 = pattern_dict[pattern1] pattern2 = pattern_dict[pattern2] for i in range(1, 21): image1 = get_image(result_path, i, pattern1) ...
5099cde71284c0badae64e701a2362b30f87ad4c
31,170
def min_max_rdist(node_data, x: FloatArray): """Compute the minimum and maximum distance between a point and a node""" lower_bounds = node_data[0] upper_bounds = node_data[1] min_dist = 0.0 max_dist = 0.0 for j in range(x.size): d_lo = lower_bounds[j] - x[j] d_hi = x[j] - upper_...
03f80210ada3530c692ce24db3bb92f0156a2d6f
31,171
def strip_newlines(s, nleading=0, ntrailing=0): """strip at most nleading and ntrailing newlines from s""" for _ in range(nleading): if s.lstrip(' \t')[0] == '\n': s = s.lstrip(' \t')[1:] elif s.lstrip(' \t')[0] == '\r\n': s = s.lstrip(' \t')[2:] for _ in range(ntrai...
cd9c55d4ac7828d9506567d879277a463d896c46
31,172
def xyz_to_lab(x_val, y_val, z_val): """ Convert XYZ color to CIE-Lab color. :arg float x_val: XYZ value of X. :arg float y_val: XYZ value of Y. :arg float z_val: XYZ value of Z. :returns: Tuple (L, a, b) representing CIE-Lab color :rtype: tuple D65/2° standard illuminant """ x...
c2478772659a5d925c4db0b6ba68ce98b6537a59
31,173
def get_core_v1_api(): """ :return: api client """ config.load_kube_config() core_api = client.CoreV1Api() return core_api
2169b3dfe7a603c1d870c0100d96640f4688023c
31,174
def ssbm(n: int, k: int, p: float, q: float, directed=False): """ Generate a graph from the symmetric stochastic block model. Generates a graph with n vertices and k clusters. Every cluster will have floor(n/k) vertices. The probability of each edge inside a cluster is given by p. The probability of an...
f849bb41afe617e6d66e043280b4606e1d5390c4
31,175
import torch def get_norm(norm, out_channels): """ Args: norm (str or callable): either one of BN, SyncBN, FrozenBN, GN; or a callable that takes a channel number and returns the normalization layer as a nn.Module. Returns: nn.Module or None: the normalization layer """ if out_channels ...
63821ac90fdb6f9d9442a885e54d5569aa78f1ae
31,176
def std_normal_dist_cumulative(lower, upper): """ Find the area under the standard normal distribution between the lower and upper bounds. Bounds that aren't specified are taken at infinity. """ return find_distribution_area(stats.norm, lower, upper)
210a16d29d8e07949dbe67c7486e9fea1656ce76
31,177
def ann_pharm_variant(dataframe, genome, knowledgebase, variant_type): """query with chr, start, stop, ref, alt, genome assembly version. Returns all the drugs targeting the observed variant. """ all_direct_targets = {} rows = get_variant_list(dataframe) for r in rows: direct_target_list = ...
cf1b8be54bf5ccb1bfa29afbe2af5020246ac7ea
31,178
from typing import List from typing import Tuple def to_pier_settlement( config: Config, points: List[Point], responses_array: List[List[float]], response_type: ResponseType, pier_settlement: List[Tuple[PierSettlement, PierSettlement]], ) -> List[List[float]]: """Time series of responses to pi...
48879533d392f89cb39e7bea4b6565b8ff172279
31,179
def subtract_something(a, b): """ Substracts something from something else. a: add-able First thing b: add-able Second thing. Returns: -------- Result of adding the two. """ return a - b
e090d09fc3fd35b080b12584d663519b39ed24c9
31,180
from pathlib import Path def last_rådata(datafil, track=None): """Last inn rådata fra en gpx-fil eller en GPSLogger csv-fil. """ datafil = Path(datafil) if datafil.suffix == '.gpx': sjekk_at_gpxpy_er_installert() return last_rådata_gpx(datafil, track=track) elif datafil.suffix == '...
c0e7d638c858ef97cde7c8c0ce2ea9796ff4c7de
31,181
from datetime import datetime def getAverageStay(date1, date2, hop): """ The average number of days a patient stays at a hospital (from admission to discharge) if hop is None it calculates the stat system wide """ count = 0 num = 0 for visit in Appointment.objects.all(): doc = Doct...
9044d415d6231e51ee4eecb5e00e3a531fb209fb
31,182
def classify(inputTree,featLabels,testVec): """ 决策树分类函数 """ firstSides = list(myTree.keys()) firstStr = firstSides[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) for key in secondDict.keys(): if testVec[featIndex]==key: if type(secondDict[k...
3daee2b72332c14eab41fd00bf781f00b4e1e633
31,183
def update(sql, *args): """ 执行update语句,返回update的行数 :param sql: :param args: :return: """ return _update(sql, *args)
700a155dbdcc77d824ce14eb95b7f041a0dda261
31,184
def videoSize(): """ videoSize() -> (width, height) Get the camera resolution. Returns: A map with two integer values, i.e. width and height. Parameters: This method does not have any parameter. Usage: width, heigh = SIGBTools.videoSize() size = SIGBTools.videoSize() """ ret...
58757851dbbde75a1e1fef201d3ed2decee8cd06
31,185
import hashlib def generate_md5_token_from_dict(input_params): """ Generate distinct md5 token from a dictionary. 初衷是为了将输入一个函数的输入参数内容编码为独一无二的md5编码, 方便在其变动的时候进行检测. Parameters ---------- input_params : dict Dictionary to be encoded. Returns ------- str Encoded md5 token...
2faf66679a72c6fd4f2e02f3ddef728b3bab687e
31,186
import re def create_range(range_, arrayTest, headers_suppresed = True): """ Creates a range string from a start and end value 'A1','A4' becomes 'A1,A2,A3,A4' """ result_string = [] first_cell = range_.split(':')[0] last_cell = range_.split(':')[1] column_start = re.search(r'[a-zA-Z]+'...
5aff1450946ee12ab943a24491a9947e6d2fa830
31,187
def find_largest_helper(n, maximum): """ :param n: int, the number to find the largest digit :param maximum: int, the largest digit :return: int, the largest digit """ if n % 10 > maximum: maximum = n % 10 if n / 10 == 0: return maximum else: return find_largest_helper(n // 10, maximum)
ddd49839be6a3ab6ece7cabde41f3978df1ba6f3
31,188
def global_align(seq1_1hot, seq2_1hot): """Align two 1-hot encoded sequences.""" align_opts = {'gap_open_penalty':10, 'gap_extend_penalty':1, 'match_score':5, 'mismatch_score':-4} seq1_dna = DNA(dna_io.hot1_dna(seq1_1hot)) seq2_dna = DNA(dna_io.hot1_dna(seq2_1hot)) # seq_align = global_pairwise_align_nucleo...
35cc261f43c116a96fbec9e409875b8131ff76a3
31,189
import math def get_points_dist(pt1, pt2): """ Returns the distance between a pair of points. get_points_dist(Point, Point) -> number Parameters ---------- pt1 : a point pt2 : the other point Attributes ---------- Examples -------- >>> get_points_dist(Point((4, 4)),...
c517833dec161585c336289149a8c56461fe7642
31,190
def get_source_type(*, db_session: Session = Depends(get_db), source_type_id: PrimaryKey): """Given its unique ID, retrieve details about a single source type.""" source_type = get(db_session=db_session, source_type_id=source_type_id) if not source_type: raise HTTPException( status_code=...
31eeda78aa3dff35618cc2e57092449e47645702
31,191
import os def get_namefiles(pth, exclude=None): """Search through a path (pth) for all .nam files. Parameters ---------- pth : str path to model files exclude : str or lst File or list of files to exclude from the search (default is None) Returns ------- namefiles : l...
c80da9dba1dbea8505d119ba61745c7c43b4f25b
31,192
def load_data(messages_filepath, categories_filepath): """ Get the messages and categories from CSV files. """ messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) return messages.merge(categories, on='id', how='left')
7efafc6a51b1e3dd02e3df8926fbf4ea92f8cb39
31,193
def apply_meth(dna, meth): """Transforms DNA sequence to methylated DNA sequence Input: dna (np.array): array of DNA sequence meth (np.array): Methylation labels (len == len(dna)) Output: dna_meth (np.array): array of methylated DNA sequence """ dna_meth = dna.copy() img ...
e835047651970dd3add0a463a235209b772411fd
31,194
def apply_affine_3D(coords_3d, affine_matrix): """ Apply an affine transformation to all coordinates. Parameters ---------- coords_3d: numpy 2D array The source coordinates, given as a 2D numpy array with shape (n, 3). Each of the n rows represents a point in space, given by its x, y and z ...
2b06901c4428075800e919579ab07c7577c6d9a0
31,195
def weighted_degree_kernel_pos_inv(x1, x2, K=4, var=8, beacon=None, bin=None): """ Weighted degree kernel with positional invariance :param x1: Sequence of characters. :param x2: Sequence of characters. :param K: K-mers to be scanned. :param beacon: Beacon sequen...
01403c7ca780c272b7b6ea37d291d79f2515edb6
31,196
import ast def is_valid_block_variable_definition(node: _VarDefinition) -> bool: """Is used to check either block variables are correctly defined.""" if isinstance(node, ast.Tuple): return all( _is_valid_single(var_definition) for var_definition in node.elts ) retur...
9be2e583353bed1910b2dfe70bba2dfd9fe96328
31,197
def julian_day_to_gregorian(julian_day): """Converts a Julian Day number to its (proleptic) Gregorian calendar equivalent Adapted from: https://en.wikipedia.org/wiki/Julian_day#Julian_or_Gregorian_calendar_from_Julian_day_number Note that the algorithm is only valid for Julian Day numbers greater than or ...
1544f6cd5abee1f5cef3b5befbf24f82c8d26e44
31,198
def isnotebook(): """Identify shell environment.""" try: shell = get_ipython().__class__.__name__ if shell == 'ZMQInteractiveShell': return True # Jupyter notebook or qtconsole if shell == 'TerminalInteractiveShell': return False # Terminal running IPython ...
4620d8275c10f5aeb8e13406c897b5b93313de97
31,199