content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def group_lane_parameters(flowcell_info): """ goup lanes that can share GERALD configuration blocks. (The same species, read length, and eland vs sequencing) """ lane_groups = {} for lane_number, lane_contents in flowcell_info['lane_set'].items(): for lane_info in lane_contents: ...
aa0a429b1371c97041cdcb021145c21ba25c6f72
80,862
from typing import Optional async def retrieve(ref: ImageRef, token: Optional[str] = Header(None)): """ Return generated image from the model """ validate_token(token) image_byte_array = BytesIO() image = Image.open(IMAGE_PATH.joinpath(ref.image_id, "1.png")) image.save(image_byte_array, format=im...
b2400e6674a5cd8b0ec5bdf848a5af1fd890b8d7
80,863
def scharr_h(image, mask=None): """Find the horizontal edges of an image using the Scharr transform. Parameters ---------- image : 2-D array Image to process. mask : 2-D array, optional An optional mask to limit the application to a certain area. Note that pixels surrounding...
18cf3af56cbac497a9e87afeced06b69e631e16f
80,864
def generate_decoder_stub(payload_len, key): """Returns the decoder stuff which decodes the encoded payload. """ # Calculate the offset of encoded payload # from the retrieved PC. # FPU instruction + fnstenv = 2 + 4 bytes offset_to_encoded_payload = 6 # Offset for fnstenv to write on t...
472f3504e99f2cfb4fa349b9068bb4d006727ce3
80,865
def discretize(x, cuts, side='right', error_on_larger=False): """Discretize x to cuts. Arguments: x {np.array} -- Array of times. cuts {np.array} -- Sortet array of discrete times. Keyword Arguments: side {str} -- If we shold round down or up (left, right) (default: {'right...
70c95c699e7d593570e6a7ace03facd93ee2d190
80,866
import numpy def upcontinue(gz, height, xp, yp, dims): """ Upward continue :math:`g_z` data using numerical integration of the analytical formula: .. math:: g_z(x,y,z) = \\frac{z-z_0}{2\pi}\int_{-\infty}^{\infty}\int_{-\infty}^ {\infty} g_z(x',y',z_0) \\frac{1}{[(x-x')^2 + (y-y')^2 +...
152d88c9dce4349fa808b6420009e54a889455d0
80,867
import pathlib def make_subdirectory(directory, append_name=""): """Makes subdirectories. Parameters ---------- directory : str or pathlib object A string with the path of directory where subdirectories should be created. append_name : str A string to be appended to the directory ...
7403f309c0ace7da748c81ccbd1fd9ff07676014
80,868
def method(row_i): """ """ # row_i = df_slab_old.iloc[0] atoms = row_i.slab_final num_atoms = atoms.get_number_of_atoms() return(num_atoms)
06e759a22343bb0ecfb0e16a354c10096f28a237
80,869
def parse_path(value): """Parse and validate an incoming Path attribute value. """ value = strip_spaces_and_quotes(value) assert valid_path(value) return value
a791111e75802283abbfed4f718c99876f147fda
80,870
def isi_distance_multi(spike_trains, indices=None, interval=None): """ Specific function to compute the multivariate ISI-distance. This is a deprecfated function and should not be called directly. Use :func:`.isi_distance` to compute ISI-distances. :param spike_trains: list of :class:`.SpikeTrain` ...
fee8bca13311c9e110925311f8bd239680072223
80,871
import six def patch_prediction_copy(model): """Patch a Keras model to copy outputs to a kludge during training. This is necessary for mask updates to a region during training. Parameters ---------- model : keras.engine.Model """ model.train_function = None model.test_function = None...
8ff559ed69cd6c1f13f8f7894339d66af2f884d1
80,872
import unicodedata import re def django_slugify(value): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dash...
6a9d9f2e597207ed257a377590942a453c6958bf
80,873
from typing import Union from typing import Literal from typing import Any def cctf_encoding( value: FloatingOrArrayLike, function: Union[ Literal[ "ACEScc", "ACEScct", "ACESproxy", "ALEXA Log C", "ARIB STD-B67", "Blackmagic Film ...
d11b5559ee96a05196c230e48bffed31098bb3b0
80,874
from typing import Callable def check_same_units_and_convert(func) -> Callable: """Verify that the simulation and the reference have the same units. If not, it converts the simulation to the units of the reference. """ @wraps( func ) # in order to keep the docstring of the function wher...
9f0bbeda0c200ec755af34970fbf6057df978d74
80,876
def svn_prop_is_boolean(*args): """svn_prop_is_boolean(char prop_name) -> svn_boolean_t""" return _core.svn_prop_is_boolean(*args)
2ca534620494503abd605e0aff96993a241b8b14
80,877
def draw_boxes(image, boxes, class_names, scores, max_boxes=10, min_score=0.15): """ Overlay labeled boxes on an image with formatted scores and label names. """ colors = list(ImageColor.colormap.values()) try: font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSansNa...
7c8b85ffafcead587c13527c89e94af90f2abe43
80,879
from typing import Tuple def KAK(U:np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]: """ This function is an implementation of the KAK decomposition. It takes a 4x4 unitary matrix U and decomposes it into local gates wrapped around a Canonical gate Parameters ---------- ...
4bbf5a60d92caedff679dffb8d4e1f9b2f84ac5e
80,881
def go_to_matching_pair(editor): """ Moves caret to matching opening or closing tag @param editor: Editor instance @type editor: ZenEditor """ content = editor.get_content() caret_pos = editor.get_caret_pos() if content[caret_pos] == '<': # looks like caret is outside of tag pair caret_pos += 1 tag...
2f083a0cd3a56fe52ef926c27fca265ef54d0604
80,882
def _linkRevision(revision, changes=False): """Return a link tag to the source browser for this revision.""" try: revision = int(revision) except: return revision link = '<a href="%s?rev=%d">%d</a>' % (_source_browser_url, revision, revision) if changes: link += ' [%s]' % _li...
90fb554ab10c4e9fa7d22b52d0ed44d8b850a06a
80,884
def hashable(robot: np.ndarray) -> str: """ Returns a hashable representation of a robot. Args: robot (np.ndarray): array specifing the voxel structure of the robot. Returns: str: string representation of the robot. """ out = "" for i in range(robot.shape[0]): f...
693adcb35c43cd1e0a77347d4dcc282d35183c94
80,885
import hashlib def validate_file(fpath, md5_hash): """Validates a file against a MD5 hash. # Arguments fpath: path to the file being validated md5_hash: the MD5 hash being validated against # Returns Whether the file is valid """ hasher = hashlib.md5() with open(fpath...
8244003fe23b6c1b7e5ab3cd0337dee056e0a970
80,887
def dateToZulu(x): """Return date in Zulu format NOT IMPLEMENTED. """ return x;
018af6b11c015d6441c9f2ebeda8e6ebb01c127d
80,888
from typing import Optional def positional_features_linear_masks( positions: tf.Tensor, feature_size: int, seq_length: Optional[int] = None, bin_size: Optional[int] = None, ): """Exponentially increasing point focuses.""" del bin_size # Unused. del seq_length # Unused. distances = tf...
540ad86972abd5f4cb1417b76a70069f6266661e
80,890
def delete_property_option(request, product_id, option_id): """Deletes property option with passed option id. """ try: property_option = PropertyOption.objects.get(pk=option_id) product = Product.objects.get(pk=product_id) except ObjectDoesNotExist: pass else: propert...
0c5198135e542c30937f6d875db8a3232cef005f
80,892
def insert_cmd(args): """insert command""" (username, token) = load_auth_token() client = HostDirectory(username, token) host = Host() for arg in args: if arg.startswith("--hostId="): host.host_id = arg[len("--hostId="):] elif arg.startswith("--hostName="): host.host_name = arg[len("--hos...
05ac8192ec567ccfc946227aa32e1320e445839d
80,893
import socket import ipaddress import multiprocessing def scan_server(timeout=0.05): """Scan lan raspi_io server :param timeout: scan timeout :return: server address list """ in_queue = Queue() out_queue = Queue() def connect_device(address): try: ws = websocket.creat...
e405f98171c828bb3eca5e112ebc3fcb7370e046
80,894
def infotodict(seqinfo): """Heuristic evaluator for determining which runs belong where allowed template fields - follow python string module: item: index within category subject: participant id seqitem: run number during scanning subindex: sub index within group """ t1w = create_key(...
bc9561a0a454fc40353103484de360f267cf9757
80,895
from datetime import datetime def Write_Space(Variable, f): """Function to Convert None Strings to Strings and Format to write to file with Space""" if isinstance(Variable, str) == False: if isinstance(Variable, datetime.datetime) == True: return f.write(f"{Variable.strftime('%Y-%m-%d')}\...
2b9fbb2450e97c51601dbf7b8791751001d9d2a3
80,896
def find(elements_list: list, match_pattern: str) -> list: """ Return indexes of a list that matches with pattern. Similar to MATLAB find function """ indexes = [i for i in range(len(elements_list)) if elements_list[i] == match_pattern] return indexes
9bfa1c4a9d018378aa117dd35a7e4bb947f4a83d
80,897
def polar_to_cartesian(radius, angle_deg): """Converts polar coordinate sample to cartesian coordinates :param radius: :param angle_deg: """ theta = np.deg2rad(angle_deg) x = radius * np.cos(theta) y = radius * np.sin(theta) return(x, y)
c11633ff84907fd7719ebb81695babe97cf03eaa
80,898
def mon_decorateur(fonction): """Notre décorateur : il va afficher un message avant l'appel de la fonction définie""" def fonction_modifiee(): """Fonction que l'on va renvoyer. Il s'agit en fait d'une version un peu modifiée de notre fonction originellement définie. On se conten...
5c4ad105613da1884e98375187bb712996342300
80,899
def subdivide(verts, faces): """Subdivide each triangle into four triangles, pushing verts to the unit sphere""" triangles = len(faces) for faceIndex in xrange(triangles): # Create three new verts at the midpoints of each edge: face = faces[faceIndex] a,b,c = (Vector3(*verts[ver...
0206fa3f70e5c943d808f78de9fd061b79d64d68
80,900
def plot_angular_resolution_per_off_pointing_angle(true_alt, true_az, reco_alt, reco_az, alt_pointing, az_pointing, res_degree=False, bins=10, ax=None, **kwargs): """ Plot the angular resolution as a function o...
dabb3a08c456108ff3dbce0e3bfcc0331677d3b4
80,901
def get_service(resource_root, name, cluster_name="default"): """ Lookup a service by name @param resource_root: The root Resource object. @param name: Service name @param cluster_name: Cluster name @return: An ApiService object """ return _get_service(resource_root, "%s/%s" % (SERVICES_PATH % (cluster_...
2499043a7e25607a4eaeaadc629b37ce05a96aba
80,902
def _parse_header(fname): """Get parsed header Return ------ header : dict { 'columns': list of strings, 'Analyzer.Energy': float, } """ with open(fname) as f: lines = f.read().splitlines() header_lines = [line[2:] for line in lines if line[0] == '#']...
bb2fd418439f22aa271be9ec07454e21014e8300
80,904
import warnings import copy def draw_net(config, genome, view=False, filename=None, node_names=None, show_disabled=True, prune_unused=False, node_colors=None, fmt='png', avg=False): """ Receives a genome and draws a neural network with arbitrary topology. """ # Attributes for network nodes. i...
16f2c72866ceaf5b926ba83e0d4e0ac8e6d83943
80,906
def _maybe_pandas_label(label): """ Extract internal data from pd.DataFrame for DMatrix label """ if isinstance(label, DataFrame): if len(label.columns) > 1: raise ValueError('DataFrame for label cannot have multiple columns') label_dtypes = label.dtypes if not all(dtype.na...
47e44e5175303a0e03cb25205f61318686df0ce9
80,907
def parameter_stats(parameter_dictionary): """ Performs mean and standard deviation, minimum and maximum operations on all the parameter lists for each generation. @param parameter_dictionary: @type parameter_dictionary: @return: @rtype: """ new_dict = {} for key, par_dict in parameter_dictionary.items(): ne...
fd7ce57cfb349024c7ce47d423f191c7862521d3
80,908
def construct_base_url(bible, text): """Return the base URL for BIBLE and TEXT. BIBLE is 'KJV' or 'LEB' TEXT is 'xml' or 'json' or 'txt' """ base_url = 'http://api.biblia.com/v1/bible/content/' url = base_url + bible + '.' + text return url
aa4ab823808d186a2830f1531706919ef0afd98f
80,909
def generate_colored_word(guess: str, answer: str) -> str: """ Builds a string of emoji codes where each letter is colored based on the key: - Same letter, same place: Green - Same letter, different place: Yellow - Different letter: Gray Args: word (str): The word to be colored ...
f9a3305fceeaec6c3994e4e36b38ac4c475ed7f9
80,910
import threading def main(args): """ Main func. """ thread1_done =threading.Event() thread1_done.clear() thread2_done =threading.Event() thread2_done.clear() print("Main thread start.... ") t1 = MyThreading(target=thread_1, args=(thread1_done,), name="T1" ) t2 = MyThreading(target=thr...
78c60db4ee2a3a705113495c43bddaf28ad2bcc3
80,912
def Fit(Data, Bounds = None, Graph = False, TFI = 10, TRI = -2, classification = False): """ Parameters ---------- Data : Data Frame Data Frame of light curve data Bounds : list, optional Set custom bounds for each parameter for fitting. The default is None. Bound Synta...
b6415d2214e25c93307f9479b73386f008ecd4a2
80,913
def dsu_sort(idx, seq): """Sorts a list of tuples according to the idx column using a Decorate-Sort-Undecorate method""" for i, e in enumerate(seq): seq[i] = (e[idx], e) seq.sort() seq.reverse() for i, e in enumerate(seq): seq[i] = e[1] return seq
a20f28aa10522d9653a85421104755f31861218c
80,914
def tm_player_data(url, currency='EUR'): """ Extracts metadata, market value history, and transfer history for a given player Parameters: url (string): path of transfermarkt player currency (string): desired currency to return for values Returns: dict: player metadata list: market ...
c99a400f3cc26a0af8e29413dabdbe9e6c8a8ee5
80,915
import json def _prettify_genotype(genotype): """Get more human-readable display name and grouping for a given genotype.""" pretty = genotype group = 'others' alleles = json.loads(genotype) if len(alleles) == 2: g1, g2 = sorted(alleles) if g1 == 0 and g2 == 0: pretty = REF group = 'main'...
aa028a934d6390a5d8a32ff27134d0ec73474383
80,916
def _alf1_zeros(l): """ Zeros of the associated Legendre function of degree l and order 1. """ # we know there is a zero at 0 if l is even zeros = [1, *([0] * even(l))] if l <= 2: return np.sort(zeros) # solve for positive intervals only and use 0-symmetry intervals = alf1_zero_...
3d166f950fd9d4081f8c925d64250c8d82872029
80,917
def calculate_face_normals(op=None, points=None, polys=None): """ Builds a list of face normals and polygon midpoints from *op* or the specified *points* and *polygons* lists. # Parameters op (c4d.PolygonObject): points (list of c4d.Vector): polys (list of c4d.CPolygon): return (tuple of (list of c4d.V...
3d285ef973255ac7aee61e96e21f05fbb9e4acd8
80,918
def _(val, **kwargs): """ Before hashing a float, convert to a string (via rounding) and with a fixed number of digits after the comma. Note that the `_single_digest` requires a bytes object so we need to encode the utf-8 string first """ return [_single_digest('float', float_to_text(val, sig=AIIDA_...
947a521b33286eba8be148c33925262f7f0d074c
80,919
import numbers def np_check_random_state(seed): """Turn seed into a np.random.RandomState instance Parameters ---------- seed : None | int | instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance...
d3656940136afb8d66833db233bd2f169b37d979
80,920
def _make_dispatcher(app_config): """Make a new dispatcher with the given ApplicationConfigurationStub.""" return dispatcher.Dispatcher( app_config, 'localhost', 1, 'gmail.com', 1, node_config=None, php_config=None, python_config=None, java_config=None, go...
6873c0ab26fa4ca82ef2bfe97ca1c0c462d57abe
80,921
def remove_script_needed(host): """ take Host Object and list of scripts needed for audit, then return result of fabric command executed. :param: host: Host Object currently audited. :param: scripts: list of scripts needed. :type: host: Host Object :type: picklename: str :re...
9b36062cb1c79d39ba8133fd4182fdc65aa15a71
80,922
def import_html(html, url, only_main, download_image, image_path): """ @param html: html内容 @param url: 链接 @param only_main: 值提取页面正文 @param download_image: 要下载页面上的图片到本地 @rapm image_path: 图片存放路径 """ html = get_url_html(html, url) if html is None: return message("warning", "", "...
8a6477442394bef1c23a759dc6da52ce42bcbac0
80,923
def get_Sp(N=16, dt=0.1): """ INPUTS N (int): is the length of the preview horizon; dt (float): time step size; OUTPUTS Sp: size [N, 3] matrix; """ Sp1 = np.ones((N, 1)) Sp2 = np.arange(1, N + 1).reshape(N, 1) * dt Sp3 = (np.arange(1, N + 1) ** 2).reshape(N, 1) * (dt ** 2) / 2 ...
e60b6d4ce24988ab5f59354e982ff6f61f3dee69
80,924
def get_unique_filename(fname): """ Try to return a unique filename. Not safe for race conditions. """ counter = 1 uname = fname while check_file(uname,timeout=0.01): uname = fname + '_' + str(counter) counter += 1 return uname
0cbcf271336a53881b8542a4874093d9b4e34c4b
80,925
def any_user(UserFixture, app, database): """A user without privileges or memberships.""" u = UserFixture( email=f"anyuser@anyuser.org", password="anyuser", ) u.create(app, database) # when using `database` fixture (and not `db`), commit the creation of the # user because its imp...
3497a6987a30d834199acabe97709d91703a266a
80,926
def is_SimplicialComplexMorphism(x): """ Returns ``True`` if and only if ``x`` is a morphism of simplicial complexes. EXAMPLES:: sage: from sage.homology.simplicial_complex_morphism import is_SimplicialComplexMorphism sage: S = SimplicialComplex([[0,1],[3,4]], is_mutable=False) sag...
bad83ca93ffdf7d9ff1d3804f792d7b2ebe08197
80,927
import json def put_request(url, token, url_path, body): """Small helper function to do PUT requests.""" headers = {"Content-Type": "application/json", "Accept": "application/json", "X-Auth-Token": token} _, net_location, path, _, _ = urlparse.urlsplit(url) full_path = "{0}/{1}".format(path, url_path)...
cf18d8368ebbe386c4d7c83a94ea6787f2d0a97c
80,928
import threading def run_thread(func, args, result_queue): """ Run a thread which runs func(args), putting each yielded result in queue. Return the thread. """ def thread(): try: for result in func(*args): result_queue.put(result) except Exception as er...
8df8625a0da700d1b34d02cbfdf47a84e96d7b86
80,929
def grant(privileges, type: PgObjectType, target, grantee, grant_option=False, schema=None, arg_types=None, quote_subname=True): """GRANT statement that may be executed by SQLAlchemy. Parameters: privileges: List of privileges (or ``'ALL'``). type: PostgreSQL object type. targ...
9e960939582c9514d72a5a9725447f5ed7435dd8
80,930
def generate_general_parameter( regions, narratives, sim_yrs ): """Based on narrative input, calculate the parameter value for every modelled year Arguments --------- regions : list Regions narratives : List List containing all narratives of how a mod...
ff90de694e5844b0056df834d0907aa976f20867
80,931
def polygon_size(poly): """ Calculates size / area of polygon Parameters ---------- poly : iterable of 2d points e.g. [[1, 3], [1, 4], [2, 4], [2, 3]] Returns float, polygon size """ poly = _preprocess_polygon(poly) return poly.area
2598319ed9a6cedf45ff2932e90c3347e81c6fe7
80,932
from typing import Union def calculate_CCDF(data: Union[list, dict]) -> dict: """计算 Complementary Cumulative Distribution Function (CCDF) Args: data: 数据。 Returns: 每个key对应计算的互补累计频率。 """ return {k: 1 - v for k, v in calculate_CDF(data).items()}
3146a3bfa73723fb4029b5c50c4a119959a27807
80,933
def design_matrix(gtab, bval, dtype=None): """ Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a) Parameters ---------- gtab : array with shape (3,g) Diffusion gradient table found in DICOM header as a numpy array. bval : array ...
c29e6e8a62ebac5ae65f7a74a118e6759fba5331
80,934
import toml def get_toml_config(path: str) -> dotdict: """Return Settings object made from toml.""" with open(path) as fd: config = dotdict(toml.load(fd)) return config
c68f3f9249b70a3288fef2c417557679d5fdfe09
80,936
def _is_line_from_candidate(line: str, from_imports: list, import_str: str) -> bool: """ Check if line has from import :param line: the line to check :param from_imports: the from imports list :param import_str: the import string :return: True if the line has from import to replace """ i...
04e2d20985fde1a08a9090ac733aafa8c3911968
80,937
def get_general(xml_tree, ret): """ This function will parse any element in calculatio other than the structures, scsteps""" if 'dimension' in [x.tag for x in xml_tree]: ret['info'] = [] ret['data'] = {} for ielement in xml_tree: if ielement.tag == 'field': ...
8e623a0c5bacd9ae5102bbfd3db2fb05198b7460
80,938
def GetMachineType(required=True): """Gets the --machine-type flag.""" help_text = """\ The type of machine (name only) which has a fixed number of vCPUs and a fixed amount of memory. This also includes specifying custom machine type following `custom-number_of_CPUs-amount_of_memory` pattern, e.g. `custom-32-29440`...
149462e08b41231606f817f4573293c710c01211
80,939
def txt_bld_para(val, padding_left=Decimal(0), **kwargs): """Return a chunk of text with a bold font""" padding_top = kwargs.get('padding_top', Decimal(0)) return Paragraph(val, font=BASIC_FONT_BOLD, font_size=BASIC_FONT_SIZE, padding_top=paddi...
84579d17a61b023736665eba7304e5eee808e052
80,940
def remote_judge_update_fetch(ok: bool, uuid: str, client_session_id: str, hj2_problem_id: str, result: dict = None, message: str = ""): """ 更新添加题目状态,评测端调用 """ if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") if not ok: emit("server_response", {"ok": False, ...
c9e5ed5a612c7df8c3a53cfc0d2968e35da44370
80,942
def get_vdif_num_frames(filename,packet_limit=-1,forced_packet_size=0,offset_bytes=0,\ only_offset_once=1,v=1): """ Get information from vdif file by processing headers. As many headers as packet_limit are processed. Each of the output parameters are vectors with all the possible val...
0389d9e63f939ecd16d05d06644667fa7609f5d1
80,943
def check_cubic_window(window): """Check whether ``window`` is represents a cubic window. Args: window (:py:class:`~structure_factor.spatial_windows.BoxWindow`): Raises: TypeError: ``window`` must be a :py:class:`~structure_factor.spatial_windows.BoxWindow`. ValueError: ``window.bo...
4f31c390945208bd03766966b3a232b7e9b98dd3
80,944
import torch def to_numpy(tensor: torch.Tensor, switch_channels: bool = None) -> np.ndarray: """Tensor to numpy, calls .cpu() if necessary :param tensor: Input tensor :param switch_channels: Boolean determining whether the channels are moved from the first to the last dimension, defaults to ``Fal...
e4f136467ebae1ed3d22d0bc99c1d4042998d930
80,945
from datetime import datetime def gen_today_file_name() -> str: """ generate today json filename Returns: today_in_history-*.json """ now = datetime.now().strftime('%m-%d') file_today: str = 'today_in_history-%s.json' % now return file_today
37991e761021a1d5742b82359fbdf88d1d58f975
80,946
def read_from_memory_Ccode_onept(gfname,idx, FDparams): """ :param gfname: gridfunction name; a string :param idx: Grid index relative to (i0,i1,i2,i3); e.g., "0,1,2,3" -> (i0,i1+1,i2+2,i3+3); later indices ignored for DIM<4 :param FDparams: Parameters used in the finite-difference codegen :return:...
633d685d4cafd70589f5064e6652be263091b0b9
80,947
def shuffle_data(data: dict) -> dict: """Returns uniformly random permutation of <data>.""" np.random.seed(SEED) # set seed to get reproducible result shuffler = np.random.permutation(len(data['X'])) return {'X': data['X'][shuffler], 't': data['t'][shuffler]}
d87490a406bc0756e68acac1d6757b10e77651d8
80,948
def is_fractional_sv(input_str): """ This function takes the given text and checks if it is a fraction. Args: input_str (str): the string to check if fractional Returns: (bool) or (float): False if not a fraction, otherwise the fraction """ if input_str.endswith('ars', -3): ...
fc5b15b449e9209a8836f809796ce9e3a5b27247
80,949
def part1(): """ The tree is made up of nodes; Specifically, a node consists of: A header, which is always exactly two numbers: The quantity of child nodes. The quantity of metadata entries. Zero or more child nodes (as specified in the header). One or more metadata entries (as specified in the header). ...
efadc3ae94ea1827e30efd8aa27941627276d4a6
80,950
import requests def get_last_tag(github_config, owner, repo): """Get the last tag for the given repo""" tags_url = "/".join([github_config.api_url, "repos", owner, repo, "tags"]) tags_response = requests.get(tags_url, headers=github_config.headers) tags_response.raise_for_status() tags_json = tags...
e45a64ed279d65f03e604d710ba0028144da46f6
80,951
def _clean_slice(key, length): """ Validates and normalizes a cell range slice. >>> _clean_slice(slice(None, None), 10) (0, 10) >>> _clean_slice(slice(-10, 10), 10) (0, 10) >>> _clean_slice(slice(-11, 11), 10) (0, 10) >>> _clean_slice(slice('x', 'y'), 10) Traceback (most recent ...
6bb399a1d07d3f13282a3e24598354473cc562b8
80,952
def euclidean_length(vec: np.array) -> np.float: """ Calculates the euclidean length of an n-dimensional vector :param vec: vector :return: length """ return np.sqrt(np.sum(vec**2, axis=1))
094c29d39b944dc770984f791e7fb4bc1b9507f2
80,953
import torch def collate_fn(data): """Creates mini-batch tensors from the list of tuples (image, caption). We should build custom collate_fn rather than using default collate_fn, because merging caption (including padding) is not supported in default. Args: data: list of tuple (image, captio...
0d1a42fb5cd5574b5d1c1bbeef2350733eb1c248
80,954
def _chisq(data, model, modelcov=False): """Like chisq but assumes data is already standardized.""" if modelcov: mflux, mcov = model.bandfluxcov(data['band'], data['time'], zp=data['zp'], zpsys=data['zpsys']) diff = (data['flux'] - mflux) totcov =...
fd360368fdcb63f0101c62e81dba8e7ad3b65e3f
80,955
def func_formatter_log_1(x, pos): """ gets a normal input and formats it to log with 1 decimal """ if x == 0.0: return "" else: x = np.log10(x) return "{:.1f}".format(x)
5957b0381a74661af65fd82a55645ce0d4108f1c
80,956
def signedarea(poly): """ get the signed area of the polygon """ p = ndarray(poly) return sum(np.hstack((p[0, 1::], p[0, 0:1])) * (np.hstack((p[1,2::], p[1,0:2])) - p[1, :])) / 2.
91189d37c0b90a186fc3bd4fd74b6a127e207489
80,957
from typing import List from typing import Dict import regex def _generate_metadata_contributor_xml(contributors: List[Dict], contributor_type: str) -> str: """ Given a list of contributors, generate a metadata XML block. INPUTS contributors: A list of contributor dicts contributor_type: Either `author`, `trans...
7ac6df1f654ba032a6d9ec4e8bcb763c634b0240
80,958
def decompose_clifford_ag(clifford): """Decompose a Clifford operator into a QuantumCircuit. Args: clifford (Clifford): a clifford operator. Return: QuantumCircuit: a circuit implementation of the Clifford. """ # Use 1-qubit decomposition method if clifford.num_qubits == 1: ...
16074814f78786816539e3a40f3423b83e06d0c1
80,959
from typing import Tuple def hxltm_carricato__cod_ab_levels( caput: list, data: list, numerordinatio_praefixo: str = '1603_45_16' ) -> Tuple[list, list]: """hxltm_carricato__cod_ab_levels filter cod_ab_index into a list of levels Args: caput (list): _description_ data (list): _description...
17786992c901273d65634d84051e4850671cd0aa
80,960
def get_valid_messages(log, expiry): """ Return only the messages that haven't expired. """ valid = [] for message in log: try: timestamp = int(message.get('timestamp', 0)) if timestamp > expiry: valid.append(message) except ValueError: ...
d24e9bc5e6d0a2c0efd9442f0d36f6e248b51137
80,961
def find_eigenvalues_from_sixMT(sixMT): """Function to find ordered eigenvalues given 6 moment tensor.""" # Get full MT: MT_current = sixMT # And get full MT matrix: full_MT_current = get_full_MT_array(MT_current) # Find the eigenvalues for the MT solution and sort into descending order: w,v...
49189d27b60ed5b7514b05c319db9a8d1ffcc1a1
80,962
import math def computeMACS(xs, T, a=None, useCovariance=True, covariance=None, normalize=False): """ Compute the Maxwellian average cross section (MACS): .. math:: MACS(kT) = {\\frac{2}{\sqrt{\pi}}} {\\frac{a^2}{(kT)^2}} \int_0^{\infty}dE_n^{lab} \sigma(E_n^{lab})* E_n^{lab}*\...
43ed1cc6c6bf24ab36ef468155dbaec2d3877674
80,963
def svn_wc_process_committed_queue(*args): """ svn_wc_process_committed_queue(svn_wc_committed_queue_t * queue, svn_wc_adm_access_t * adm_access, svn_revnum_t new_revnum, char const * rev_date, char const * rev_author, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_process_committed_queue(*a...
7293c43b711b20786f4ebb73b7c449588d58216b
80,964
def model_average(X, penalization): """Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion matrix. NOTE: This returns precision_ proportions, not cov, prec estimates, so we return the raw proportions for "cov" and the threshold support estimate for prec. ...
71bb5b19a5d1d264c717c58dde3e22b6a7e98de7
80,967
def get_path_from_tokens(token): """ Just yanks the path out of a list of template tokens. Ignores any additional arguments. """ tokens = token.split_contents() if len(tokens) > 1: # At least one argument. Only interested in the path, though. return tokens[1].strip("\"'") el...
3d17c4943b34607eaf8ac5554c713ddac1cbc628
80,968
from typing import Union def get_input_types(obj: Union[InferRequestBase, CompiledModelBase]) -> dict: """Map all tensor names of all inputs to the data types of those tensors.""" def get_inputs(obj: Union[InferRequestBase, CompiledModelBase]) -> list: return obj.model_inputs if isinstance(obj, Infer...
60308153a289167a45948fff924071f84c6eee93
80,970
def emits_event(function, expected_event): """ Recursively check whether a function emits an event Parameters ---------- function : slither.core.declarations.Function expected_event : Signature Returns ------- bool """ for event in get_events(function): if ( ...
6e71d202651b22bb68a8603018f4f28603146943
80,971
def _pedantic_settings(pedantic): """ Controls the pedantic parser settings. Based on the bool passed in to pedantic, create a config to be passed to astropy parsing to raise exceptions or ignore them on pedantic errors. Parameters ---------- pedantic : bool When `True`, raise ...
7cd8d1d6b68c8523290b3556ca160e7a38e6775a
80,972
import pandas def get_similar(data, n=10): """" Given an item data, returns: - predicted value, - similar n items in the testset - similarity values related to the n similar items """ dataset = trainset.append(testset, ignore_index=False) data = fix_mis...
efa115bda0b6e99ee32820688f664c674b52c35d
80,973
def is_no_auth(request): """Check condition for needing to authenticate the user.""" no_auth_list = ["/status", "openapi.json", "/metrics"] no_auth = any(no_auth_path in request.path for no_auth_path in no_auth_list) return no_auth or MASU or SOURCES
c99597d173016da618e2b23dfc24af525a0374a0
80,974
def create_perturbation(pert_info): """Create perturbation.""" pert = pert_info[3](pert_info[1], None, pert_info[2]) return pert
22c5fdcdf7e8e1745b5d717794d39135d7e278ea
80,975
from kikit.panelize_ui import splitStr def readParameterList(inputStr): """ Given a string, read semicolon separated parameter list in the form of `key: value; key: value`. You can escape via `\\` """ if len(inputStr.strip()) == 0: return {} try: values = {} for i, pai...
05623f0c83f1f7006c994aa50b06e22c9d087807
80,977