content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def _create_agents(num_frames: int, num_agents: int, label: int = 1) -> List[List[Box3D]]: """ Generate dummy agent trajectories :param num_frames: length of the trajectory to be generate :param num_agents: number of agents to generate :param label: agent type label. Typica...
44a4ab4fef1ed29a0b3861e354357bbd3d2ff44f
40,629
def get_ℓ_prior(points): """Calculates mean and sd for InverseGamma prior on lengthscale""" distances = pdist(points[:, None]) distinct = distances != 0 ℓ_l = distances[distinct].min() if sum(distinct) > 0 else 0.1 ℓ_u = distances[distinct].max() if sum(distinct) > 0 else 1 ℓ_σ = max(0.1, (ℓ_u -...
673e71206c08c815543888d045fc2255ef323816
40,630
from re import DOTALL def parse_wars(content): """ Second part of the main parser. Reads all relevant information about wars from the savegame. Returns a list of all wars, as well as a dictionary about the participants in each war.""" previous_wars = content.split("previous_war={")[0].split("active_war={")[1:] + ...
13b6a168d17118d9ac71e41979a31abcc3999d0b
40,631
from typing import Sequence from typing import Type from typing import Union def unique_fast( seq: Sequence, *, ret_type: Type[Union[list, tuple]] = list ) -> Sequence: """Fastest order-preserving method for (hashable) uniques in Python >= 3.6. Notes ----- Values of seq must be hashable! See...
c41c6b298e52bd3069414206cf9ada4766ea8f4d
40,632
import time def verify_signed_url(url, salt=None): """ Check a signed URL is valid and unexpired. """ salt = salt or _DEFAULT_SALT m = _SIGNED_URL_RE.match(url) if not m: return None url = m.group(1) signature = m.group(2) expiry = int(m.group(3)) if expiry <= int(tim...
347770eef1fdddc70ef7aef754f20b30d554acfb
40,634
def yices_type_is_function(tau): """Returns 1 if tau is a function type, 0 otherwise.""" return libyices.yices_type_is_function(tau)
5078fbe3777b230297df0553d983c8cb7a1df8c3
40,635
import torch def kumaraswamy_sample(conc1, conc0, sample_shape): """ Sample from the Kumaraswamy distribution given the concentrations :param conc1: torch tensor: the a concentration of the distribution :param conc0: torch tensor: the b concentration of the distribution :param batch_shape: scalar: the batch sha...
41869f17bdc1e9d439f5277b26d4ed50e4d9f0f1
40,636
def parse_atom_ids(input_list, mol): """ List of the form id,id,isotope,addHs e.g. 1,2,104,True :param input_list: :param mol: :return: """ spl_list = input_list.split(",") bond_ids = [] atom_ids = [] bond_colours = {} for i, data in enumerate(spl_list): list_len ...
8939aa5ad2ef8d2de73a1c3595426602742aa758
40,637
def cluster_hierarchically(active_sites): """ Cluster the given set of ActiveSite instances using a hierarchical algorithm. # Calls to agglomerative clustering algorithm housed in another script Input: a list of ActiveSite instances O...
feedfaec13387c6f2534c82110fe3e348e106d85
40,638
def _is_container_running(duthost, container_name): """ Checks if the required container is running in DUT. Args: duthost (SonicHost): The target device. container_name: the required container's name. """ try: result = duthost.shell("docker inspect -f \{{\{{.State.Running\}}...
2653a82f65170a04f5d2a6ddf6137272e27e298d
40,639
def slow_closest_pair(cluster_list): """ Compute the distance between the closest pair of clusters in a list (slow) Input: cluster_list is the list of clusters Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] have minimum dist...
473aaa90b644da69a72db6f88e19f3000641ad9e
40,640
def is_retaincase(bunchdt, data, commdct, idfobject, fieldname): """test if case has to be retained for that field""" thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname) return "retaincase" in thiscommdct
1164376ea22ca97238623e65b3081b75900e37ac
40,641
def test_multiple_forks(scheduler: Scheduler) -> None: """ Ensure multiple handle forks are recorded. """ @task() def task1(conn): return conn @task() def main(): conn = DbHandle("conn", "data.db") conn = task1(conn) conn = task1(conn.fork("a").fork("b").for...
b53c25c1035fc9473d5e75ccebdd9296b2666209
40,642
def add_run_number(bids_suffix, run_no): """ Safely add run number to BIDS suffix Handle prior existence of run-* in BIDS filename template from protocol translator :param bids_suffix, str :param run_no, int :return: new_bids_suffix, str """ if "run-" in bids_suffix: # Preserve...
8f8d4cd036c7ba63ec7aaf2562a638e59d842598
40,643
def logout(): """Log user out.""" # forget any username session.clear() # redirect user to login form return redirect(url_for("login"))
0c2ce69eb27291ef15b98ad6e1a6a02d37b00119
40,644
def complement(clr): """ Returns the color opposite on the color wheel. The complementary color contrasts with the given color. """ if not isinstance(clr, Color): clr = Color(clr) return clr.rotate(180)
c340b3a2cefc22a8d99b04bf58911bf9600ef0b2
40,645
from re import S def get_file_info(pipeline_context, filename): """Return a dictionary of CRDS information about `filename`.""" return S.get_file_info(pipeline_context, filename)
cfb469bb96049fe0c387ce9a3818c74b4e967098
40,646
def parse_colors(sequence): """Return escape codes from a color sequence.""" return ''.join(ESCAPE_CODES[n] for n in sequence.split(',') if n)
a2c32b861440136afc7a9495ef762206a98984fd
40,647
def intersect(s1, s2): """ Returns the intersection of two slices (which must have the same step). Parameters ---------- s1, s2 : slice The slices to intersect. Returns ------- slice """ assert (s1.step is None and s2.step is None) or s1.step == s2.step, \ "Only i...
13841ceddd3bb5c73a29bd4067a751579bc04e9b
40,648
def apply_hpso_parameters(o, hpso, hpso_pipe): """ Applies the parameters for the HPSO pipeline to the parameter container object o. :param o: The supplied ParameterContainer object, to which the symbolic variables are appended (in-place) :param hpso: The HPSO whose parameters we are applying :para...
a859c7598e8b5dc40aee24bafa654a439fff02d4
40,649
def checkpoint_get_group_command(client: Client, identifier: str) -> CommandResults: """ Show existing group object using object name or uid. Args: client (Client): CheckPoint client. identifier(str): uid or name. """ result = client.get_group(identifier) printable_result = buil...
4a0d6e6696385a5b844ce4070ff55655fa23e830
40,650
def remove_duplicate_indices(data: pd.DataFrame, keep="first") -> pd.DataFrame: """Function that removes duplicate indices Args: data: The data frame for which duplicate indices need to be deleted keep: Determines which duplicates (if any) to mark. See pandas.DataFrame.index.duplicated document...
d5288bfa5e7b7ab34a2b7a3ac58ce43595f825d8
40,651
def rdkit_molecule(gra): """ Convert a molecular graph to an RDKit molecule. This is mainly useful for quick visualization with IPython, which can be done as follows: >>> from IPython.display import display >>> display(rdkit_molecule(gra)) :param gra: the graph :returns: the RDKit molecule...
dfab20957deffb27f0e05c73d53eb77f213cda48
40,652
def make_filename_template(**kwargs): """Generate a filename template snippet from the schema, based on specific filters. Parameters ---------- kwargs : dict Keyword arguments used to filter the schema. Example kwargs that may be used include: "suffixes", "datatypes", "exten...
6aafb5791d3314a7baa885c080bdbd194a0a9717
40,653
import torch def compute_entropy_bernoulli(logit: torch.Tensor): """ Compute the entropy of the bernoulli distribution, i.e. H= - [p * log(p) + (1-p) * log(1-p)] """ p = torch.sigmoid(logit) one_m_p = torch.sigmoid(-logit) log_p = F.logsigmoid(logit) log_one_m_p = F.logsigmoid(-logit) entropy ...
e1a01541e3fd6673a1d53f834c16256581b0dd6d
40,654
def domain_from_url(url): """Returns the website part of a given url :param url: str the URL for which the website is needed :returns: the website extracted from the url value :rtype: str (or None) """ if url is None: return None try: parsed = urlparse(url) if parsed...
21e2998052782718e388571642fa3f216bc52806
40,655
def check_event_attr(logpath): """ Checks for existence of event attributes, given the path of event log. Parameters: logpath (str): Path of event log Returns: attr (List of str): List of event attributes """ log = importer.apply(logpath) log_df = log_converter.apply(log, v...
49291864b387cadc5e2777342ba55d415a97aa08
40,657
def is_word_guessed(word, guesses): """ This function will check if the user has guessed all of the letters in the word. """ # Loop through the word. for letter in word: # Check if the letter has been guessed. if letter not in guesses: # The user has not guessed the letter. return False # The user has ...
7ab3ad07a5588745dc4a9f01dac89c788cc688f5
40,658
def solve(start, end, min_studios): """Solve an instance of the grid, given start and end gate locations. min_studios is an integer specifying the minimum number of studio squares that must be visited. """ # We may attempt the same gates multiple times. Memoize to improve speed. memo_key = (start, end, min...
e124340639a8c8a2463c0fd98d6bed9fcf52e688
40,659
def unpack_seven(inbytes): """ Reconstruct a number from the seven-bit representation used in the SysEx message data. Takes a bytes-like object, where each byte is seven bits of the number (big-endian byte order) Each byte must have its high bit zero, or else ValueError is raised. """ va...
ce3084126b1851015cb0323b6aae2b1acd46b971
40,661
def h(node1, node2, l1, l2, *, g): """If node has 8 neighbors""" g_n = g(node1) path = node1.path parent = next(path) try: parent = next(path) except StopIteration: pass g_p = g(parent) if g_p <= g_n: w = l1 else: w = l2 h_n = euclid(node1, node2) ...
d4cb4620147f550424711632f6bdfc43ee8c2cd2
40,662
def nativestr(x): """Return the decoded binary string, or a string, depending on type.""" return x.decode("utf-8", "replace") if isinstance(x, bytes) else x
c4474e3c1953331fee46d29e59777494d626f660
40,664
def seperate(df, column, new_names, sep=".", remove=False): """Verb: split strings on a seperator. Inverse of :func:`unite` Parameters ---------- column : str or pd.Series column to split on (Series.name is named in case of a series) new_names : list list of new column names ...
026eeb557d395ffab748fc0a164b20ad3f4ed506
40,665
def listdetail(filename, itemtype, name='', tablefmt='simple', header='default'): """List nodes and metadata in output file. Parameters ---------- {filename} {itemtype} name : str Optional specific name to print only that entry...
70636b05a975b76da17c8f00abafe61b22a136d9
40,666
def template_match_hashes(template_hashes, source_hashes, match_percent=0.6): """ Takes in array of template fingerprint hashes, and an array of hashes to search through. Looks through the search array for the template, and registers a match so long as the percent of matches exceeds the provided match_perce...
7bb37c315b62aa3116e5019a5c2d9b22cf65976c
40,667
import io def unparse(tree: typed_ast.ast3.AST, *args, **kwargs) -> str: """Unparse AST based on typed_ast.ast3 with nodes as defined in horast.nodes into code.""" assert isinstance(tree, typed_ast.ast3.AST), type(tree) stream = io.StringIO() Unparser(tree, *args, file=stream, **kwargs) return str...
2e97e4bd8f79d90651f942ec83c57c3c7fcbbd5f
40,668
import re def Clean_price(post_price): """This function takes out the price range used by the website""" if re.search('\-.*', post_price): pos = re.search('\-.*', post_price).start() return post_price[:pos] else: return post_price
a84a4d0bf2c20640f92e7d56ac672316412a30fc
40,669
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ uniques = [] for dummy_idx in list1: if dummy_idx not in uniques: uniques...
ddb0fb01760ddf58f2d7e178ec7556d6083ff271
40,670
def extract_single_image(img_path, lab_path, voxel_picker_class, patch_picker_class, cent_picker_class, patch_size, scales, n_voxels): """Sample and extract feature from an image. Argume...
304ab035b3a0ea4c69c8583d2453e59ac7cdc5e9
40,671
def fitness_function(solution, answer): """fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters.""" score =0 for i in range(len(answer)): score += (abs(solution[i]-answer[i])) retu...
059924beb07d0e0e1892783f515061ffcf714d43
40,672
import scipy import itertools def rr_order_patterns( signal1: "np.ndarray[np.int32]", signal2: "np.ndarray[np.int32]", m: int, tau: int ) -> float: """ Parameters ---------- signal1 : signal2 : m : int Embedding dimension. tau : int Time delay parameter. Not...
ad3219d46563a2cb8c926b295e4cf91bcccc51b6
40,673
def adjust_cruise_no(cruise): """If shipc should be mapped we map cruise_no as well.""" if len(cruise) > 7: return '_'.join((cruise[:4], cruise[4:8], cruise[8:])) else: return cruise
a83a35cb0a1bad17778f3b39756c431237254a51
40,674
def update_uas_class_admin(class_id=None, comment=None, default=None, public_ip=None, image_id=None, priority_class_name=None, namespace=None, ...
adba5a1027f21dc233abb29c013c0f33bbe85126
40,675
def test_batch_execution_of_gradient_tf(device, shots, mocker): """Test that the output of a parallelized execution of batch circuits to evaluate the gradient is correct in comparison to default.qubit when using the tf interface.""" tf = pytest.importorskip("tensorflow", minversion="2.4") qubits = 2 ...
385c5dbfebf99f1f7e471d39f394fac53918c859
40,677
def get_glconfig(): """Returns a GLConfig to be used for OpenGL widgets initialisation.""" global __old_glconfig if __old_glconfig == None: # Query the OpenGL extension version. # Configure OpenGL framebuffer. # Try to get a double-buffered framebuffer configuration, # if no...
c09ebcdca7aca7cb9338b8b79ce6b0e8449c6415
40,678
import uuid from typing import Literal import requests def newOrder(idProds): """ Creates a new order with the idProd :return: """ product_ids = idProds.split(',') order_id = uuid.uuid4() order = agn['order_' + str(order_id)] graph_message = Graph() graph_message.add((order, RDF.t...
7d2c4c485862feed495fff0cde5571110f61ac70
40,679
def Demographic_Parity(pred_labels, true_labels, groups, priv_group=None): """ A fair algorithm would have an equal rate of positive outcomes :math:`(\\hat{Y}=1)` in privileged group :math:`(A=0)` and unprivileged groups :math:`(A=1)`. :math: :math:`P(\\hat{Y} = 1|A=0) = P(\\hat{Y} = 1|A=1)` :return:...
7dfecac35b8241404520dba17718716cbbca7cc8
40,680
def decode(k, key_length): """ Decodes a klv message """ key = k[:key_length] val_length, ber_length = decode_ber(k[key_length:]) value = k[key_length + ber_length : key_length + ber_length + val_length] return key, value
b5be5af3425fbb36958695d0620d4ab489f232ff
40,681
from typing import List def bmeow_to_bio(tags: List[str]) -> List[str]: """Convert BMEOW tags to the BIO format. Args: tags: The BMEOW tags we are converting Raises: ValueError: If there were errors in the BMEOW formatting of the input. Returns: Tags that produce the same sp...
883f93eca51fb83f97daa5a46832d7efb805044a
40,683
def signature(word: str) -> str: """Return a word sorted >>> signature("test") 'estt' >>> signature("this is a test") ' aehiisssttt' >>> signature("finaltest") 'aefilnstt' """ return "".join(sorted(word))
a17e006dcd9f55cfc57d7cd0140489c7be518dc7
40,684
def decision_tree(tree, inputs, method="predict", value_transform=None): """ Creates a SKAST expression corresponding to a given SKLearn Tree object. Kwargs: inputs: a list of AST nodes to be used as inputs to the model. method: 'predict' (for classifier and regressor models), ...
1bdb366edc5550c70ccec711032bfd3e1bb2e0ad
40,685
import itertools def plot_spark_error(xdat,ydat, error, filename='plot.eps', save=True, show=False, color='#47d147'): """Generic plotting function for (multiple) xy datasets. Based on matplotlib spark_line function defined here: https://markhneedham.com/blog/2017/09/23/python-3-create-sparklines-using-mat...
775f2b563d5f8b238d5d20769eaf5ed7161fe1d3
40,686
def get_object(bucket: str, key: str) -> bytes: """Gets the object at key in the passed bucket Wraps the Acquire get_object function Args: bucket: Bucket containing data key: Key for data in bucket Returns: bytes: Object from store """ return ObjectStore.get_object(buck...
073d48c7134c3dce60e57c8d70a8debb91bd58ec
40,687
def get_radius(box, element, dr, n=1, ratio=0.5): """Get the radius of a bubble. Radius is determined to be r with closest value of n_element / n_atoms to ratio, i.e. within radius, n_element / n_atoms should be as close to ratio as possible. n specifies number of radiuses to return, i.e. n radiuses...
85cb05f81a2ae70f230ec1be385a6f6f0acd480e
40,688
def _get_extra_price_id(items, key_name, hourly, location): """Returns a price id attached to item with the given key_name.""" for item in items: if not utils.lookup(item, 'keyName') == key_name: continue for price in item['prices']: if not _matches_billing(price, hourl...
d9ba4bcdc50b2bb79d2e284a98a733cd6b65adb7
40,689
from typing import Generator from typing import Dict def test_validate_generator(): """Test that generator replacement for validation in config doesn't actually replace the returned value.""" @my_registry.schedules("test_schedule.v2") def test_schedule(): while True: yield 10 ...
c65d67a65420ce2463905b9dc14397f996e5f107
40,690
def plot_det_label(image, anno, labels): """ 目标检测类型生成标注图 Args: image: 图片路径 anno: 图片标注 labels: 图片所属数据集的类别信息 """ catid2color = {} img = cv2.imread(image) img, scale_value = resize_img(img) tree = ET.parse(anno) objs = tree.findall('object') color_map = get_colo...
99885b7677533c2cb6da4194d68687e28eee28de
40,691
def getHeaders(lst, filterOne, filterTwo): """ Find indexes of desired values. Gets a list and finds index for values which exist either in filter one or filter two. Parameters: lst (list): Main list which includes the values. filterOne (list): A list containing values to find indexes of in the main list...
0aa3612b15114b0e0dcdf55eb3643df58157239b
40,692
def get_binary_clf_scores(y_true, y_pred, y_score=None, sample_weight=None, level=1): """ Scores a binary classifiers. Parameters ---------- y_true: array-like, (n_samples, ) The ground truth labels. y_pred: array-like, (n_samples, ) The predicted labe...
de9a66be676e308894ec9e7e7cb1d6401f37c73f
40,693
def historylog_with_tab(historylog, mocker, monkeypatch): """Return a fixture for a history log with one tab. The base history log is a plugin widget. Within the plugin widget, the method add_history creates a tab containing a code editor for each history file. This fixture creates a history log with...
0da05ee2f7831771984b9eab4a727a6378929256
40,694
from bs4 import BeautifulSoup from datetime import datetime def get_audio_uris(uri): """ Fetches HTML of a File page and returns an array of URIs to the audio files on that page :param uri: URI to a File page full of audio players :return: A list of dictionaries with the date, index, and ...
268b2fea021f6a0e6f757194b38ef0c0ae2aa192
40,695
def overlap_compress(X, n_components, window_size): """ Overlap (at 50% of window_size) and compress X. Parameters ---------- X : ndarray, shape=(n_samples,) Input signal to compress n_components : int number of DCT components to keep window_size : int Size of wind...
c449f8f0ec4241aa70d058aed4aeab8e19ae49e0
40,696
import array def lcsubstrings(seq1, seq2, positions=False): """Find the longest common substring(s) in the sequences `seq1` and `seq2`. If positions evaluates to `True` only their positions will be returned, together with their length, in a tuple: (length, [(start pos in seq1, start pos in seq2)..]) Other...
3241de831be64334cac21c2bc2a3ac8e2a5d5443
40,698
def n_max_numbers(in_iter, n=2): """Get N maximal numbers from iter. >>> n_max_numbers([]) [] >>> n_max_numbers([1, 2, 3]) [2, 3] >>> n_max_numbers([4, 2, 3]) [3, 4] >>> n_max_numbers([1, 2, -1, 0], 3) [0, 1, 2] """ max_numbers = list() for number in in_iter: ...
5cac858891f3c76d51bda473a743ab9700db334c
40,699
from pathlib import Path def main(logger, args): """ Main function Args: logger: logger object args: arguments from command line Returns: None """ # variables train_data_path = args.train_data_path output_data_path = args.out_process_path logger.info('initi...
e678444f0d248670853c0f3ed351a10453321948
40,700
import requests def weather_data( latitude: float, longitude: float, date_: date, weather_stations: pd.DataFrame ): """ Get weather data for given location and date using the closest weather station Args: latitude (float): Latitude longitude (float): Longitude date_ (date): Da...
6bee1852e0e84ae7c126078eafbc199ede578649
40,702
import re def separate_words(text, min_word_return_size): """ Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must h...
ca6bf51740ecf6f20bd35d0931dcd885f052a141
40,703
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None: """ Print and log control's properties. control: `Control` or its subclass. depth: int, current depth. showAllName: bool, if False, print the first 30 characters of control.Name. """ def getKeyName(theDict, t...
af97e8385de97b6b6f912601e9e151ca16508cb1
40,704
def getSelectedObjectChannels(oSel=None, userDefine=False, animatable=False): """Get the selected object channels. Arguments: oSel (None, optional): The pynode with channels to get userDefine (bool, optional): If True, will return only the user defined channels. Other channels will...
f9dbd53585c2f07798b4a5658eb4301677ba1df2
40,705
def admin_urlify(column, help_text=None): # pragma: no cover """ Can be used to add a link to a model referenced in another admin. Example: fields = [admin_urlify("user")] """ def inner(*args): if len(args) > 1: obj = args[1] else: obj = args[0] _obj = getattr(obj, column) if _obj is None: ret...
34df5e572ec8fce70f2479759b95708fe7c848fe
40,706
def getMS(start, stop): """ Get time difference in milliseconds """ diff = stop - start return getMSDiff(diff)
68161813b37bbb79baae5ea5b42f0e313f4333fe
40,707
def allowedExperiments(reagents, maxConcentration, minConcentration=None): """ Find the allowed ConvexHull given the reagent definitions and max/min concentration. Note that, relative to the Mathematica code, the location of max and min concentration in the function arguments are swapped. This allows for the ...
b24fae4216456c8620d56e73132b6c1ee370027d
40,708
def basicauth_dump_request_endpoint(request): """ Dump a HttpRequest to files in a directory. """ uname, passwd, user = _basicauth(request) print(uname, passwd, user) if user is None: # Either they did not provide an authorization header or # something in the authorization attem...
5ff855e39b4cc88502b3d9d199e49dbcf7a630c5
40,709
import time def load_metadata(paths, quiet=False): """ --> makes hashtable -> filepath : fcs file class instance meta_keys == all_keys w any new keys extended replaced -> meta_keys = ['FILEPATH'] with 'SRC_FILE' Arg: paths: iterable of fcs filepaths Returns: fcs_o...
3c3453d12970f7993c0910718d6201dfb080c40d
40,710
from typing import Callable from typing import Any from typing import Tuple import inspect def combine_args_kwargs( func: Callable[..., Any], *args: Any, **kwargs: Any ) -> Tuple[Any, ...]: """ Combine args and kwargs into args. This is needed because we allow users to pass custom kwargs to adapters,...
03e5c310462b3d15e3ab69cf6d8717744a95caa4
40,711
def get_tensor_backend(tensor): """ Determine the tensor backend for a given tensor. Args: tensor: A tensor type of any of the supported backends. Return: The backend class which providing the interface to the tensor library corresponding to ``tensor``. Raises: :py...
cbad0351c81816c6ecb5fc3e56b54c9a4bf358ff
40,712
import math def generate_primes_up_to(max_prime): """Generates an array of prime numbers up to @max_prime""" primes = [2, 3] i = 4 while i < max_prime: prime = True for divisor in xrange(2, int(math.sqrt(i)) + 1): if i % divisor == 0: prime = False break if prime is True: primes.append(i) ...
b18faf069e01d722e66fe7817016ae081a4821fd
40,713
import json def get_package_list_arch(repo, arch): """Return all packages in a repository with given architecture.""" filters = _filters_from_args(request.args) filters['repo'] = repo filters['arch'] = arch pkgs = pkgdb.find(**filters) _json = list(map(_json_from_pkg, pkgs)) return json.du...
2055be354197d708ee13b7e1d38b96f425c95483
40,716
def h(k, n, td, tb, tau): """Term in Eq. 35 in Zhang+95.""" # Typo in Zhang+95 corrected. k * tb, not k * td if k * tb < n * td: return 0 return (k - n*(td + tau) / tb + tau / tb * Gn((k * tb - n * td)/tau, n))
4d744bf9efd4121d82333151cf53f163a5c429be
40,717
def definers (ioc, name) : """Return the classes defining `name` in `mro` of `ioc`""" try : mro = ioc.__mro__ except AttributeError : mro = ioc.__class__.__mro__ def _gen (mro, name) : for c in mro : v = c.__dict__.get (name) if v is not None : ...
f5d90118ca1ad719d47143d0260bfcbda2749124
40,718
def dict_to_yaml_snippet (dictionary, indent = ' ', level = 2, newline = '\n'): """Convert a dataframe Dictionary to a formated yaml snippet Parameters ---------- dictionary : dict dictionary with keys INDEX, ORDER, and the values of INDEX and ORDER indent : str, optional level : int ,...
34f02c497e68558506e495b90b3f93aa02ab3955
40,719
def datetime_display_renderer(widget, data, value=None): """Note: This renderer function optionally accepts value as parameter, which is used in favor of data.value if defined. Thus it can be used as utility function inside custom blueprints with the need of datetime display rendering. """ value...
7a24364118997bc64df0ffc1ed1c9175515a1239
40,720
def get_bbc_dataset(): """Extract a return the train and test data for the bbc corpus.""" dataset = pd.read_csv('bbc_dataset.csv', index_col=0) dataset_train = dataset[dataset.set == 'train'] dataset_test = dataset[dataset.set == 'test'] X_train = dataset_train[['Utterance']] y_train = dataset_...
46504ca8ff5050f5bb810fea0382e984383d51d9
40,721
def get_course_url(course_id, course_json, platform): """ Get the url for a course if any Args: course_id (str): The course_id of the course course_json (dict): The raw json for the course platform (str): The platform (mitx or ocw) Returns: str: The url for the course i...
22865459e0a0636f1f116630bab50cb3157f008b
40,722
from typing import Any def load_model(helper: PredictHelper, config: PredictionConfig, path_to_model_weights: str) -> Any: """ Loads model with desired weights. """ return ConstantVelocityHeading(config.seconds, helper)
0cda0cd393a7221a628739753aebbc45aad02904
40,723
import torch from typing import Union from typing import Callable from typing import Optional from typing import Any def create_supervised_trainer( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable, torch.nn.Module], device: Optional[Union[str, torch.device]] = None, ...
918536b588cc5a238621558d792bb9ce7c44f2cc
40,724
def add_dest(df_conc, dest_labware, dest_start=1): """Setting destination locations for samples & primers. Adding to df_conc: [dest_labware, dest_location] """ dest_start= int(dest_start) #try: # dest_labware = dest_labware_index[dest_type] #except KeyError: # raise KeyError(...
d3e066148fc07bd5ed47d496d56c39e24062315c
40,725
def load_ratings_data(path_data='ratings.csv'): """ Returns a list of triples (a, i, r) """ data = [] with open(path_data) as f_data: for line in f_data: (uid, iid, rating, timestamp) = line.strip().split(",") data.append([int(uid), int(iid), float(rating)]) prin...
d5565f0e9c5098f606d3d1dcf4607d2455b43fc1
40,726
def image_has_any_human_annotations(image): """ Return True if the image has at least one human-made Annotation. Return False otherwise. """ human_annotations = Annotation.objects.filter(image=image).exclude(user=get_robot_user()).exclude(user=get_alleviate_user()) return human_annotations.count...
b20dd78c280a92e6b1433cfcd24b7629945ce047
40,727
from typing import Dict from datetime import datetime def build_fix_from_line(line: Dict) -> GpsFix: """ Builds a GpsFix parsing the specified line :param line: The line to parse :return: A GpsFix object """ date = datetime.strptime(line["timestamp"], '%Y-%m-%d %H:%M:%S') latitude = float(...
3773a6ef825a1ef6fd00626036997df99d6a0def
40,728
def top(Q): """Inspects the top of the queue""" if Q: return Q[0] raise ValueError('PLF ERROR: empty queue')
16327db2698fbef4cad1da2c9cb34b71158a2a6c
40,729
def get_valid_handles_domain_only(): """ Define valid domain handles """ return ["cli", "web", "gui", "pub"]
64dc04fbbecbc442b1fd99279161c04461332a87
40,730
def qc_board_and_constraints(board, constraints): """ Purpose: When the board first comes in, do a check to see if any of the fixed values are duplicates @param board The Sudoku board: A list of lists of variable class instances @param constraints The unallowed values for each cell, list of tuples...
82c8013c12eda3fd548295be96e713d760587985
40,731
def spdot(A, x): """ Dot product of sparse matrix A and dense matrix x (Ax = b) """ return A.dot(x)
b44c9434a42974be54e2c4794b6f063f86836707
40,732
def ecef2eci(R_ECEF,time): """ # Function to compute rotation matrix from ECEF to ECI (simple model) # Formulas taken from the US Naval Observatory """ # # T is the Julian Date in julian centuries # d = time - 2451545.0; T = d/ 36525; # # Compute Greenwich Mean s...
c5eb8cade1e4962c6f68756a191f6d85b70daf2d
40,733
def get_months(year: str) -> list[str]: """Make all Prompts dates for a given year into a unique set. For some months in 2017, November 2020, and in 2021 and beyond, there are multiple Hosts per month giving out the prompts. While the individual dates are stored distinctly, we need a unique month l...
04bedefa175efb259188bb55a8604502956cd41b
40,734
def translate_user(user): """ translates trac user to pivotal user """ return user
69a439a12188239a557b69fa9f858473f1509a26
40,735
def _clean_int(value, default): """Convert a value to an int, or the default value if conversion fails.""" try: return int(value) except (TypeError, ValueError), _: return default
7c14156cee3313e605a7b928adca2777ba181924
40,736
import operator def wait_for_first(ds): """ Returns a deferred that is callbacked/errbacked with whatever deferred in `ds` fires first. """ d = defer.DeferredList(ds, fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True) d.addCallback(operator.itemgetter(0)) d.addErrback(get_maybe_first_e...
b12687080d8d3c25fdc5049ba6382dbd443ab721
40,738
import pickle def offline_analysis(data_folder: str = None, parameters: dict = {}, alert_finished: bool = True): """ Gets calibration data and trains the model in an offline fashion. pickle dumps the model into a .pkl folder Args: data_folder(str): folder of the da...
1a6bd7d60f44a0ebd57c48a83bc459f7d644c7fc
40,739