content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_lexicographic_dirname(dirpath: PathLike, first: bool = False) -> PathLike: """ Return the first (or last) subdirectory name ordered lexicographically. :param dirpath: name of the base path whose subdirectories ought to be listed :param first: whether the first or the last element sh...
343e9958401cd2931320e8ce41b3e5f4372bcd8a
3,621,700
async def serverinfo(msg): """ Show information about the Server / Guild this Command was used on. :param msg: The Message invoking the Command :return: The Bot's response """ guild_info = f'**Name**: {msg.guild.name}\n' \ f'**Region**: {msg.guild.region}\n' \ ...
e5ff17a360c098206b1a6706a159c7e7aea7cdab
3,621,701
def find_water_dept_details(lon, lat): """Get or create WaterParcel, WaterAccount for the given lon and lat.""" logger.debug('Getting Water Department data for %f, %f' % (lon, lat)) data = get_point_data(lon, lat) if not data: raise Exception('Could not find Water Department data for %f, %f' % ...
93314bc229f4d4e7130282b09853b726ce357b9a
3,621,702
import argparse def create_parser(prog_name): """ Creates the ArgumentParser object which parses the bash input and stored the required parameters to perfrom the command on the Transaction Family : Category Args: prog_name (str): Name of the Transaction Family Returns: ...
121add0224f641798ec9f2b477ae95f7ab8ab0c2
3,621,703
def _assign_link_resids(res_link, match): """ Given a link at residue level (`res_link`) and a dict (`match`) specifying to which resids the res_link nodes map, create a correspondence dict that maps the higher resolution nodes to the resids specified in` match`. Each `res_link` node by defi...
cfb315a15ebba6e086f340dc7e6db27eadee1d2b
3,621,704
def can_split_pairs(card_one, card_two): """ :param card_one: str - first card in hand. :param card_two: str - second card in hand. :return: bool - if the hand can be split into two pairs (i.e. cards are of the same value). """ if card_one == 'A' or card_two == 'A': split_pairs = card_...
71d4ef9463f5f0dc7a43e48be8ae0c660cda7327
3,621,705
def _get_pos_neg_loss(cls_loss, labels): """get pos neg loss""" # cls_loss: [N, num_anchors, num_class] # labels: [N, num_anchors] batch_size = cls_loss.shape[0] if cls_loss.shape[-1] == 1 or len(cls_loss.shape) == 2: cls_pos_loss = (labels > 0).astype(cls_loss.dtype) * cls_loss.view(batch_s...
1e7c9444c8604e4c0e438f3d80826a2142a5398b
3,621,706
def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple d...
606a10c6954e89b94a47d278c534a4b8b295a3c6
3,621,707
import os def filename_to_calurl(filename, suffix=None, source="irsa", verbose=False, check_suffix=True): """ """ _, date, filtercode, ccd_, qid_, *suffix_ = os.path.basename(filename).split("_") year,month,day = date[:4],date[4:6],date[6:] suffix_ = "_".join(suffix_) caltype = suffix_.split(...
4f328c1dc040cc01937d26f3013f85a02afe941b
3,621,708
import copy def invert(image: Image) -> Image: """Return an inverted copy of image; that is, an image that is a colour negative of the original image. >>> image = load_image(choose_file()) >>> inverted = invert(image) >>> show(inverted) """ new_image = copy(image) # Invert t...
286d6a3de666d356797f1d287b6a4582da30945e
3,621,709
def load(quantum_circuit_object, format: str): """Load external quantum assembly and quantum circuits from supported frameworks into PennyLane templates. .. note:: For more details on which formats are supported please consult the corresponding plugin documentation: https://pennyla...
2b71157b2d870f266e7521705d25e9b749bb34e4
3,621,710
def constrained_sum_sample_nonneg(n, total): """ Integer partitioning of random similar size. NOTE: Return a randomly chosen list of n nonnegative integers summing to total. Each such list is equally likely to occur. ARGUMENTS: ...
aa608441b44e19c6b4e5fff11a73a144fcbf82db
3,621,711
def make_batched_features_dataset(file_pattern, batch_size, features, reader=core_readers.TFRecordDataset, label_key=None, reader_args=None, ...
60edb2837b45e45b05688be8f3876591270782d6
3,621,712
def batch_update(docs, commit_each_doc=True): """ docs Format: [ "Contract (DocType)": { "create": [ { "fieldname": value, "fieldname": value, "fieldname": value } ],...
ccc30566a015d572f731402e2b155f7a5f296af0
3,621,713
import ctypes def disk_util(directory): """" <Purpose> Gets information about disk utilization, and free space. <Arguments> directory: The directory to be queried. This can be a folder, or a drive root. If set to None, then the current directory will be used. <Exceptions> Environ...
96a3dec573aa333eceba970b98e84477c2829a0b
3,621,714
def calculateMinimumTemperature(frd, maj_met, min_met, time, psolid, psolidmap): """ Minimum nodal temperature for a given PSOLID. """ minTemp = None for element in psolidmap[psolid]: temp = frd.results[maj_met][time][min_met][element] if temp < minTemp or minTemp is None: minTem...
c6065c0fee4f97a80fbdd765551987dc9eac1b41
3,621,715
import os import re def _read_wav_batch(dir_path: str, channel: str = 'm') -> MonoAudioBatch: """get a list of wav files in `dir_path` as mono float buffs ## Parameters: - `dir_path`: path to directory containing batch - `channel`: either 'l', 'r', 'm', 's' ## Notes: Outputs are not nor...
79d56b55f272f6d746ffd71700027da88c567276
3,621,716
def test_agegroup_pop(df): """ Compare the age group populations with manually computed sums from the Excel files """ def assert_pop(df, sex, state_name, year, age_group): return(df[sex][(df.StateName == state_name) & (df.Year == year) & (df.AgeG...
a9e4d5a30eef670b916ea13cf5ef328234863cf6
3,621,717
def checkrows(sudoku): """ Checks if each row contains each value only once """ size = len(sudoku) row_num = 0 for row in sudoku: numbercontained = [False for x in range(size)] for value in row: # if placeholder, ignore it if value in range(size): ...
3266eb936b0f3f1e22bd16cd40fbf61753876ce1
3,621,718
def list_is_unique(ls): """Check if every element in a list is unique Parameters ---------- ls: list Returns ------- bool """ return len(ls) == len(set(ls))
a0bc92c2e00b48d80af39020622f31059845fc94
3,621,719
def get_max_value(obj_in): """ Returns the maximum allowed value for a specific object type. :param obj_in: Object :return int: Maximum value of object type """ # TODO: Generalise, and not rely on parsing a string if obj_in.dtype == "uint8": return 255 else: return 2 ** i...
dfd29e411ec0310088902372c2ae2c41f7c36ea2
3,621,720
def shard(digest: str, depth: int, width: int) -> str: """This creates a list of `depth` number of tokens with width `width` from the first part of the id plus the remainder. TODO examine Clojure's Blocks to see if there's some nicer style here. """ first = [digest[i * width:width * (i + 1)] for i in range...
fd4aa35738906a20e0b33c8e8692d6bd4d98280d
3,621,721
import json def bandit( historical_info, type=BANDIT_BLA_ROUTE_NAME, rest_host=DEFAULT_HOST, rest_port=DEFAULT_PORT, testapp=None, **kwargs ): """Hit the rest endpoint for allocating arms of a bandit given arms already sampled (historical info).""" endpo...
05d2b879c3b3acdd255710bbb07475cff9bffef9
3,621,722
def mark_branch(tree, target_leafs): """Mark in the tree the common ancestor of the species in target_leafs""" tree = deepcopy(tree) targets_in_tree = [ target for target in target_leafs if target in [leaf.name for leaf in tree.get_terminals()] ] if len(targets_in_tree) == 1:...
2e94fccb9faf46f74513736c05f2b92ce1537ec4
3,621,723
def GetEigenVectorCentr(*args): """ GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100) Parameters: Graph: PUNGraph const & NIdEigenH: TIntFltH & Eps: double const & MaxIter: int const & GetEigenVectorCentr(P...
7d39b1bf777868911da02fa54fad769b73ae686b
3,621,724
def run_random(connection, test_case, all_preds, nr_sums, timeout_s): """ Run simple random generation baseline. Args: connection: connection to database test_case: summarize for this test case all_preds: all available predicates nr_sums: generate so many summaries t...
d4f7c39f7e30f9fd46bed1fed61db308da550a6c
3,621,725
def load_cifar_10_data(data_dir, nparts=6, negatives=False): """ Return train_data, train_filenames, train_labels, test_data, test_filenames, test_labels """ # training data cifar_train_data = None cifar_train_filenames = [] cifar_train_labels = [] for i in range(1, nparts+1): ...
e15b2931d63afa1d726a99c2cf03776e51769c16
3,621,726
import csv def read_queue(project): """Read queue csv file Args: project (string): project, i.e. CMIP5/CMIP6 Returns: rows (dict): - prsenting each record stored in the file dids (set): dataset_ids stored in the file """ rows={} dids=set() # open csv file and read...
6e6fe3a08d22e5984c962eaba3cf446456e3cb59
3,621,727
def normalise_json_testdata(obj, ignore): """ Various normalisations of the JSON sourced test data: - make it immutable to avoid accidental manipulation of baseline values - remove any keys we want to ignore - lowercase any values with a key of "id" (since we always lowercase the external IDs in the...
079b12083a20214cf900afc8f933149b83fbb55c
3,621,728
import os import json def get_index(ipfs, domain, pin): """ Get the current index using ./cur_cgt_index_hash or create one if not existent """ if os.path.exists(__CUR_CGT_INDEX_FILE_NAME__): print("Loading existing index hash from ", __CUR_CGT_INDEX_FILE_NAME__) with open(__CUR_CGT_INDEX_FILE_...
94cd96fd6846c795dcb90648082d018494fa0740
3,621,729
import re def RecordFormatFromFilePattern(file_pattern): """Return the record format string for a Lingvo file pattern. Lingvo file patterns take the form of: tfrecord:/path/to/bar -> tfrecord is the record_format. This function takes a file pattern and returns a string indicating which format the filepa...
f307d8e732760122d0870494f96900d6092191a1
3,621,730
def compute_transpose(x): """ given a matrix, computes the transpose """ xt=[([0]*len(x)) for k in x[0]] for i, x_row in enumerate(x): for j, b in enumerate(x_row): xt[j][i]=x[i][j] return xt
22988bc9802deaf1bc07182a5e85c56d54c94436
3,621,731
def make_psf_map(psf, pointing, geom, exposure_map=None): """Make a psf map for a single observation Expected axes : rad and true energy in this specific order The name of the rad MapAxis is expected to be 'rad' Parameters ---------- psf : `~gammapy.irf.PSF3D` the PSF IRF pointing ...
ebfe470724d1977b59b6e4126d11660187cca643
3,621,732
def test_get_and_modify_user(cbcsdk_mock): """Tests retrieving and modifying a user.""" def check_put(url, body, **kwargs): assert body['login_id'] == 6942 assert body['login_name'] == 'jsheridan@babylon5.com' assert body['email'] == 'jsheridan@zhadum.net' return None cbcsdk...
e3644d9013c98fbc26d56dffbd45f7bb5b8c100d
3,621,733
def sort_articles(articles): """Sort articles based on score. :param articles: :return: """ if len(articles) < 1: raise ValueError('No news') sorted_articles = sorted(articles, key=lambda x: x.score, reverse=True) return sorted_articles
f8cbd9a1437a463e49269e65a440d51fdc7c0dd1
3,621,734
def get_interface_sequence(ip_addr_output): """ output interface sequence paired to eth0, None on not found ip_addr_output will be like: 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 ...
2203604fd11077c02896ca422de07d1ff1ee04a2
3,621,735
def body_id(b_name): """Return the body id""" return bodies['id'][where(bodies['name'] == b_name.encode())]
693a49a23ab1253f0cf389981220c7c6df634536
3,621,736
def build_dict_det_pair(det_df): """ Build the dictionary that converts from detector pair to index and angle Parameters ---------- det_df : pandas dataFrame dataFrame of detector pair indices and angles Returns ------- dict_pair_to_index : dict keys: detecto...
f9da588341f8940221d76cd82bfaa88b81348f82
3,621,737
import numpy as np def random_layout(H, center=None, dim=2, seed=None): """Position nodes uniformly at random in the unit square. Exactly as networkx does. For every node, a position is generated by choosing each of dim coordinates uniformly at random on the interval [0.0, 1.0). NumPy (http://scipy.or...
88b613f6a8cfd53eccf2a9397d926d254445761f
3,621,738
def test_close_handles_odbql_error(monkeypatch): """Test that the close method handles ODBQL_ERROR.""" def mock_odbql_close(connection): """mock odbql_close""" return py3odb.odbql.ODBQL_ERROR monkeypatch.setattr("py3odb.odbql.odbql_close", mock_odbql_close) conn = py3odb.connect("") ...
f68522b7f8d6fe19a31b543aafd16b5c75ee4da0
3,621,739
from typing import Optional from typing import Callable from typing import Any def _get_serializer(meta: Optional[AttributeMetadata]) -> Callable[[Any], str]: """Get a serializer function from the given attribute metadata.""" serializer = None if meta is None else SERIALIZER_MAP.get(meta.attribute_type) i...
f2f383e502b4dfdc1fc28d962c4e65c1923b1915
3,621,740
def client(): """ Create the configuration that we will have to use to be able to run our test cases, with this method we won't be able to run our test cases """ app = create_app() return app.test_client()
d964539af223b6def7c0d248523037a68b5e1477
3,621,741
def WR(df, n): """威廉指标""" hn = df["high"].rolling(n).max() ln = df["low"].rolling(n).min() df["wr"] = (hn - df["close"]) / (hn - ln) * (-100) return df
38ed4b05d970b4359d50103b7a54a91780dff3aa
3,621,742
import math def volume_correction(distance_values, temperature=298.15): """Calculates the volume correction of the free energy Parameters ------------- distance_values : numpy.array 1-D numpy.array containing the distance of the ligand from the protein (center of mass - center of mass...
d0d47781ec88a8820faf641ad0b09f6c34b8c19d
3,621,743
def key_released(key: int) -> bool: """Determines if the given key is released.""" # Handle the queued keys.""" for event in pygame_queued_events: if event.type == pygame.KEYUP: if event.key == key: pygame_queued_events.remove(event) return True # Time...
1e3fb0448d994c1eccb6b2f68af3617518e101ab
3,621,744
def extract_mocha_summary(lines): """ Example mocha summary lines (both lines can be missing if no tests passed/failed): ✔ 3 tests completed ✖ 1 test failed """ passes, fails = 0, 0 for line in lines: if line and line[0] == '✔': passes = int(line.split()[1]) elif ...
53d671c3d18f0421cbb512835a84f71a9588f947
3,621,745
def vote(request, ballot_url): """ For ballots with tokens. """ display_ballot = get_object_or_404(BallotPaper, ballot_url=ballot_url) queryset = Category.objects.filter(ballot_paper=display_ballot) caty = get_list_or_404(queryset) user = request.user for cat in caty: try: selected_choice = cat.choice_set...
c5750ab8007ba31c4a4db28166ba04ad3c323208
3,621,746
def index(): """Homepage""" dishes = Dishes.query.all() if not dishes: flash("No dishes are available in Mess!", category='warning') return render_template( 'index.html', year=year, dishes=dishes )
49bdfd39e03078824cc65ac7c26036216338c6b4
3,621,747
def get_gts(init_weight, aft_weight): """ """ gts = np.where(init_weight != aft_weight) return gts
b440502da72017ccdc80b47a864cf678cf637d75
3,621,748
import re def get_headword(tag): """ Extract the content of a BeautifulSoup element Tag object. Args: tag (Tag): a BeautifulSoup element tag, obtained by extracting from a soup Returns: short, long ([str]): short and long form of a word in dictionary definition Modules: b...
7f98d90973527901f9b87658dd5b29916d94cecf
3,621,749
def _boundary(sample, n_i, n_g, n_t, b): """ Find matrix for R and T for air/glass/slab interface. The resulting matrix is a diagonal matrix that is represented as an array. The reflection matrix is the same entering or exiting the slab. The transmission matrices should differ by a factor of ...
118088bc466aa9a474dc173c70d1d78d42e3b3d3
3,621,750
import os def gen_all_datasets(dir): """Looks through all .mat files in a directory, or just returns that file if it's only one.""" if dir.endswith(".mat"): (r, f) = os.path.split(dir) (f, e) = os.path.splitext(f) return [(r, f)] file_list = [] for r,d,f in os.walk(dir): ...
8f652cf1710d4aff814201575a3927f944a2fdb6
3,621,751
def get_obo() -> Obo: """Get ITIS as OBO.""" return Obo( ontology=PREFIX, name='Integrated Taxonomic Information System', iter_terms=iter_terms, auto_generated_by=f'bio2obo:{PREFIX}', data_version=_get_version(), )
5c312d32b08b8a4d3fe34f0bc914dbfa51f3b752
3,621,752
def _calculate_discount_for_last_element( lines_total_prices, total_price, total_discount_amount, currency ): """Calculate the discount for last element. If the given line is last on the list we should calculate the discount by difference between total discount amount and sum of discounts applied to re...
704b2b451f0062595846ae64daa2d704305f273e
3,621,753
import re def tfprint(tensor, prefix=None, summarize=256): """tf.Printのショートカットメソッド Return: tf.Print(tensor, [tensor],・・・・) の復帰値をそのまま返す。 """ if stop: # stopならprint無し return tensor if prefix is None: prefix = tensor.name if not re.match(out_n...
3dbb229bc3a796f8423b218bcac9eddbdcf39618
3,621,754
def replace_text(text): """ Android资源文件英文的双引号或单引号需要加斜杠,否则会报错,中文的双引号和单引号不需要 :param text: :return: """ temp_text = text.replace(r' \ "', r' \"').replace(r' / ', r'/').replace(r'% ', r' %') \ .replace(r' $ ', r'$').replace(r'$ ', r'$').replace(r'¥ ', r'¥ ').replace(r'¥ ', r'¥ ').replace(r...
cddb558dabb34442fe6e5118229e3ea092c144d2
3,621,755
import json def change_pwd(username, password): """ 修改密码 @param self 绑定为当前对象 @param username 要修改密码的账户名 @param password 新密码 """ try: sock = socksPool.get() cmd = [[{'op': '5'}, {'name': username}, {'pwd': password}]] json_data = _assembly_request(cmd) if js...
8c43f064a1926825cc0fbdadb56c07524d9d76ed
3,621,756
from typing import List from typing import Union def quantity_list_validator( item: List[Union[unyt.unyt_quantity, unyt.unyt_array, str]] ) -> List[unyt.unyt_quantity]: """ Converts a list of either strings (as ``FloatValue UnitX / UnitY``) or unyt quantities and arrays to a list of unyt quantities. ...
2b7e51b40dded76ba95f3e71806ad6bf5bc6339f
3,621,757
import copy def upwindFirstENO3a(grid, data, dim, generateAll=False): """ upwindFirstENO3a: third order upwind approx of first deriv by divided diffs. [ derivL, derivR ] = upwindFirstENO3a(grid, data, dim, generateAll) Computes a third order directional approximation to the first derivat...
373ce3b8a12829eaccdb988370d8c52e77255a2d
3,621,758
import importlib def _import_from_path(name, path): """A helper function that imports a module from the given path.""" spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod
eeaefe11f28077c390c5974e3d7e11ca3179c72c
3,621,759
def netstat(): """ Return information on open ports and states .. note:: On BSD minions, the output contains PID info (where available) for each netstat entry, fetched from sockstat/fstat output. .. versionchanged:: 2014.1.4 Added support for OpenBSD, FreeBSD, and NetBSD ....
f382061415948c936a18af1fbc220fb1e8f39264
3,621,760
from typing import Mapping def add_package_headings(toc: Toc, root_pkg: str, labels: Mapping[str, str]) -> Toc: """Breaks up a flat structure with headings for each 1st-level package.""" new_toc = [] current_section = None for entry in toc.get(...
bc9879c2b0a1f75a461ce341b4a12fdb5c47a23e
3,621,761
def wrap_deepmind(env, episode_life=True, clip_rewards=True, stack=4): """Configure environment for DeepMind-style Atari. Note: this does not include frame stacking!""" assert 'NoFrameskip' in env.spec.id # required for DeepMind-style skip if episode_life: env = EpisodicLifeEnv(env) # env ...
e8ab549e44f6faf45dbf45917847406f386853ac
3,621,762
from typing import Optional def build_dataset( x: np.ndarray, y: np.ndarray, num_classes: int, shuffle_buffer_size: int = 0, augment: bool = False, augment_color: bool = False, augment_horizontal_flip: bool = False, augment_offset: int = 0, seed: Optional[int] = None, normaliza...
5dcab33148b4fce8215f5ab8c4272c836de054f1
3,621,763
def factorial(n): """ Returns the factorial of n. e.g. factorial(7) = 7x6x5x4x3x2x1 = 5040 """ answer = 1 for i in range(n, 1, -1): answer = answer * i return answer
98c0530e4e0f1de8c1c0f622e7d62a5feb042bcb
3,621,764
def get_available_holidays_in_countries( countries, year_start, year_end): """Returns a dictionary mapping each country to its holidays between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first ...
ecdc6f8c20bed2ce8be16a1c50803c8033ef82b1
3,621,765
import json def load_json(filename: str) -> dict: """Load JSON from file.""" try: with open(filename, encoding="utf-8") as fdesc: return json.loads(fdesc.read()) # type: ignore except (FileNotFoundError, ValueError, OSError) as error: LOGGER.debug("Loading %s failed: %s", file...
75fa853263d975ef973ed7b0246d3f87b586384a
3,621,766
def vfun(self, parr="", func="", par1="", con1="", con2="", con3="", **kwargs): """Performs a function on a single array parameter. APDL Command: *VFUN Parameters ---------- parr The name of the resulting numeric array parameter vector. See *SET for name restrictions. ...
dba87cb721ba79a797c357160a2ebed425b3239f
3,621,767
def reverse_colors(frame): """ Reverse the order of colors in a frame from RGB to BGR and from BGR to RGB. """ return frame[:, :, ::-1]
210deca283c373d02c0d114daad2e23ba822b3ab
3,621,768
def extract_geohash_from_path(paths): """ :param paths: Sentinel2 paths;Shape = (batch_size, no_of_timestamps=3) :return: 1d list of geohashes for which imputation is made """ return [i[i.find('9q'):i.find('9q')+5] for i in paths]
4920e611bbb1e3f9c1ee2aef4efb93832a9b0c9b
3,621,769
def chl_decision(uncorrected_chl_value, regression_table, sample_date): """ Decision tree for correcting Chl values using a linear model regression results :param uncorrected_chl_value: the value to correct :param regression_table: the table to look up the rsquared, a coeff, b coeff for given date :param sample_da...
7b1e10241a303dcc973808148323d8444a78d17c
3,621,770
from typing import List def PCA_reduction( df: pd.DataFrame, cols: List[str], n_components: int, prefix: str = 'PCA_', random_seed: int = 42, keep: bool = False ) -> pd.DataFrame: """ Substitutes given feature columns with their principal components. Args: df: D...
d6b106eab4c2b2ccdce304d78b78959697dbd31d
3,621,771
from typing import Counter def getunknownwordmodel(tagged_sents, unknownword, unknownthreshold, openclassthreshold): """Collect statistics for an unknown word model. :param tagged_sents: the sentences from the training set with the gold POS tags from the treebank. :param unknownword: a function that returns ...
1f687ee95de99c34e7b731e32bf411e84378687c
3,621,772
import threading import time import math def __alive_bar(config, total=None, *, calibrate=None, _cond=threading.Condition): """Actual alive_bar handler, that exposes internal functions for configuration of both normal operation and overhead estimation.""" if total is not None: if not isinstance(t...
813af4025db0dd24838dcacfdde9572374b866bf
3,621,773
from .msg import info def read_lattice(filename='lattice.in'): """Reads the lattice.in file. Args: filename (str, optional): The filename to be read in. Default is 'lattice.in'. Returns: result (dict): A dictionary with the following fields: "sizes": the range of cell sizes, ...
0b5a1362db06053dd51a1ea97b43ae0d94b38a7e
3,621,774
from sys import version def is_compatible(testVersion: str, baseVersion: str = None) -> bool: """ Determine if testVersion is compatible with baseVersion Args: testVersion: the version identifier to test, as the string 'x.y.z' where x is the major version, y is the minor version, ...
3bf39c5314181d8541bec62d3d4b5a02446e65fd
3,621,775
def counter_unit(): """Unit symbol of a counter, motor or EPICS record""" return unit(counter_name)
a17a3fc9769b33246f76e3dfb5b9850b8463fe04
3,621,776
from typing import Optional from typing import Callable from typing import Sequence def resample_apply(rule: str, func: Optional[Callable[..., Sequence]], series, *args, agg='last', **kwargs): """ Apply `func` (such...
c8adfc14bae2d61a8ebe08fba8738b75501955f1
3,621,777
from typing import Optional def algo_parts(name: str) -> tuple[str, Optional[int]]: """Return a tuple of an algorithm's name and optional number suffix. Example:: >>> algo_parts('rot13') ('rot', 13) >>> algo_parts('whirlpool') ('whirlpool', None) """ base_algo = name.r...
c3231da2bc3f96091b6f07d38fdd2caa414e59a1
3,621,778
import os def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries): """Generate linker options for searching library directories and linking with specific libraries. 'libraries' and 'library_dirs' are, respectively, lists of library names (not filenames!) and search directories. ...
a615afce1d73b2d07652e53f4e15d06310a1e893
3,621,779
def get_page_ids_by_slug(slug, parents=None): """ Return all the page id according to a slug """ if not parents: sql = ''' SELECT c.page_id, c.language, MAX(c.creation_date) FROM pages_content c WHERE c.type = 'slug' AND c.body = %s GROUP BY c.page_id, c.language ...
e60b51247e7f06d4e4c23876451f439d97a1ccdf
3,621,780
def linear_q_learning(env, max_episodes, eta, gamma, epsilon, seed=None): """ Initialize coefficients, Q values and random state. Iterating through max episodes: start game. Until game over, choose action, play action to get rewards and new features. Use new features to select best new action. ...
75ba9bbe08632400b94beeae07d42fa714ec3cd9
3,621,781
from pathlib import Path from typing import Optional from typing import Mapping def voc_to_coco( xml_dir: Path, image_dir: Optional[Path] = None, category_mapping: Optional[Mapping[str, int]] = None, ): """Convert VOC to MS COCO images and annotations Parameters ---------- xml_dir : pathl...
4779188a2f9fbc6f9034df293cde155da4b50f9e
3,621,782
def get_non_zero_deplexed_samples(sample_sheet): """ Given a sample sheet return the names of the samples for which one or more reads were found. The sample sheet is assumed to have columns, ``SampleID``, ``TagRead`` and ``NumReads``. Rows whose ``SampleID`` values are ``Unassigned`` or ``Total...
fea0e622a60d69f425f24f2de76eb70184b7e5db
3,621,783
def getGateEstimates(): """ Returns a list of gate estimates for the current_user's company """ if request.method == 'GET': gates = dbSession.query(Gate) gates = gates.filter(Gate.company_name == current_user.company_name).all() if len(gates) == 0: return bad_request('No gate...
7751e1f5ef0216d919f421207d29f8f6f5d639ac
3,621,784
def calculate_rsi(analysis_df, column, window): """ Calculates relative stength index. Args: analysis_df: Pandas dataframe with a closing price column column: String representing the name of the closing price column window: Integer representing the number of periods used in the RSI ...
7c32751bc4aeb5583caa69397f1c19b88a208039
3,621,785
def has_slide_type(cell, slide_type): """ Select cells that have a given slide type :param cell: Cell object to select :param slide_type: Slide Type(s): '-', 'skip', 'slide', 'subslide', 'fragment', 'notes' :type slide_type: str / set / list :return: a bool object (True if cell should be select...
edb1323331317d53502179fe357c151a5b59af0b
3,621,786
from typing import Tuple def yolo_head(feats: tf.Tensor, input_shape: tf.Tensor, calc_loss: bool = False ) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor]: """Convert final layer features to bounding box parameters.""" # Reshape to batch, height, width, num_anchor...
5bf1a097d2c4aafba98a996664f109f05f7ba705
3,621,787
from re import T def shelter(): """ RESTful CRUD controller >>> resource="shelter" >>> from applications.sahana.modules.s3_test import WSGI_Test >>> test=WSGI_Test(db) >>> "200 OK" in test.getPage("/sahana/%s/%s" % (module,resource)) True >>> test.assertHeader("Content-Type", "text/html"...
951511dc701eddd68e8225e3b5e464eb3ddeabfb
3,621,788
def clip_matrix(left, right, bottom, top, near, far, perspective=False): """Returns a matrix to obtain normalized device coordinates from a frustum. The frustum bounds are axis-aligned along x (left, right), y (bottom, top) and z (near, far). Normalized device coordinates are in the range [-1, 1] ...
af1d259e0b0e2f1a1b44caa86d342a6e52875518
3,621,789
def metadata(request): """ Add some generally useful metadata to the template context """ return {'display_version': getattr(settings, 'DISPLAY_VERSION', False), 'version': getattr(settings, 'VERSION', 'N/A'), 'shop_name': settings.OSCAR_SHOP_NAME, 'shop_tagline': set...
f6094bd1b769bb9a8b75020abef760490ed1d1d3
3,621,790
def engine(request): """Create an SQLAlchemy engine with a disposable PostgreSQL database.""" if request.param == 'postgresql': postgresql = request.getfixturevalue('postgresql') return create_engine('postgresql://', poolclass=StaticPool, ...
7793b3d8d56e4e2c067d623310872d751c61bb54
3,621,791
def rigids_to_tensor_flat12( r: Rigids # shape (...) ) -> paddle.Tensor: # shape (..., 12) """Flat12 encoding: rotation matrix (9 floats) + translation (3 floats).""" return paddle.stack(list(r.rot) + list(r.trans), axis=-1)
88f13bd0e31de5befd4ce548bf9532218560454a
3,621,792
def auto_expand(list_or_value): """Given a list return it, given a scalar return a corresponding broadcasted 'infinite list'""" if isinstance(list_or_value, list): return list_or_value else: class Expanded: def __init__(self, value): self.value = value def __getitem__(self, i): ...
d56288adf0c0275e8539c9ba12026bb23a27fb64
3,621,793
import re import inspect def defined(var): """Returns true if the variable has already been defined. Otherwise, returns false.""" str(var) if not isinstance(var, str): raise Exception("defined() must be given a string") if not re.search(r'[A-Za-z][A-Za-z0-9\_]*', var): raise Exception...
222ce53db53cb2fedefb29ad1a3ccbb9ef6e938e
3,621,794
import os def shape_from_zip(zip_filename, shape_filename=None): """ Loads a shapefile from a zipfile. If shape_filename is None, we guess which shape file you want. """ dest = unzip(zip_filename) if shape_filename is None: shape_filenames = [ splitext(filename)[0] ...
825073cae2770532af1ece91c98119f78ea7146f
3,621,795
def auto_crop(data_and_label, mode=None, buffer_size=10, debug=False): """ return cropped [img, label] data_and_label : list of 3d-array numpy image. e.g. [data, labels] crop area = (x of estimated brain area + 2 * buffer_size) * (y of estimated brain area + 2 * buffer_size) """ imgs =...
4ab3ccedff244d902f812e00778f837c41567c25
3,621,796
def add_category( name: str, description: str = None, position: int = 0 ) -> flask.Response: """ This is the endpoint for forum category creation. The ``forums_forums_modify`` permission is required to access this endpoint. .. :quickref: ForumCategory; Create a forum category. **Example reques...
0a5b9e94557ab4abbffc0c6ebdebf75220c574b0
3,621,797
import sqlite3 def query(x,db,v=True): """ A function that takes in a query and returns/ prints the result""" conn = sqlite3.connect(db) curs = conn.cursor() my_result = list(curs.execute(x).fetchall()) curs.close() conn.commit() if v is True: print(my_result) return my_result
8b914224429bdfd8d167327bf6cc0e3afaf94b3c
3,621,798
def build_url(selector, child_key, parent_key): """Return url string that's conditional to `selector` ("site" or "area").""" if selector == "site": return "https://%s.craigslist.org/" % child_key return "https://%s.craigslist.org/%s/" % (parent_key, child_key)
f8f00d4f9d20c3312f2b36d014365dbcf08242bc
3,621,799