content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_tomography_circuits(circuit, qreg, creg, tomoset): """ Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography...
ab42a0b57ccd94f6ffbb64425473c3a90dd10888
3,653,100
def filter_background(bbox, bg_data): """ Takes bounding box and background geojson file assumed to be the US states, and outputs a geojson-like dictionary containing only those features with at least one point within the bounding box, or any state that completely contains the bounding box. This te...
f06fe5efe1e3920d8b1092601a121e313da4eec4
3,653,101
def rename_columns(table, mapper): """ Renames the table headings to conform with the ketos naming convention. Args: table: pandas DataFrame Annotation table. mapper: dict Dictionary mapping the headings of the input table to the stan...
c9c9228f4f477b8d5ade234964c2540fd20ddd09
3,653,102
def get_round(year, match): """Get event number by year and (partial) event name A fuzzy match is performed to find the most likely event for the provided name. Args: year (int): Year of the event match (string): Name of the race or gp (e.g. 'Bahrain') Returns: The round numbe...
e5f4d724eb2d453251c107287450b1f0166152dc
3,653,103
from typing import Union import json def parse_tuple(s: Union[str, tuple]) -> tuple: """Helper for load_detections_csv, to parse string column into column of Tuples.""" if isinstance(s, str): result = s.replace("(", "[").replace(")", "]") result = result.replace("'", '"').strip() resul...
ad568bfc8ccdf8440378e852daccaf2f24a7e2d0
3,653,104
import re def clean(tweet): """ clean tweet text by removing links, special characters using simple regex statements Parameters ---------- tweet : String Single Twitter message Returns ------- tokenized_tweet : List List of cleaned tokens derived from the input Twitter messa...
fbfacb49f88638610fb071cb6b14d02dadf665e1
3,653,105
def predict(x, u): """ :param x: Particle state (x,y,theta) [size 3 array] :param u: Robot inputs (u1,u2) [size 2 array] :return: Particle's updated state sampled from the motion model """ x = x + motionModel(x, u) + np.random.multivariate_normal(np.zeros(3), Q) return x
7fe3e9fa42e1e74ac448a0139ca6dae8ff5388ad
3,653,106
def plot_multiple(datasets, method='scatter', pen=True, labels=None, **kwargs): """ Plot a series of 1D datasets as a scatter plot with optional lines between markers. Parameters ---------- datasets : a list of ndatasets method : str among [scatter, pen] pen : bool, optional, default: T...
85b41b719cb8d33884dd7364b3e0937100167c6a
3,653,107
def _scale_enum(anchor, scales): """ 列举关于一个anchor的三种尺度 128*128,256*256,512*512 Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) #返回宽高和中心坐标,w:16,h:16,x_ctr:7.5,y_ctr:7.5 ws = w * scales #[128 256 512] hs = h * scales #[128 256 512] anchor...
b0b8e9418b935daf2961fbd690a4ccf2b6bd6d7b
3,653,108
import codecs def metamodel_from_file(file_name, **kwargs): """ Creates new metamodel from the given file. Args: file_name(str): The name of the file with textX language description. other params: See metamodel_from_str. """ with codecs.open(file_name, 'r', 'utf-8') as f: ...
526a1876ed11aff2341133d061573ae9f3bfb1fe
3,653,109
import sirepo.template import copy def _python(data): """Generate python in current directory Args: data (dict): simulation Returns: py.path.Local: file to append """ template = sirepo.template.import_module(data) res = pkio.py_path('run.py') res.write(template.python_so...
df0d2eae8155f1093dde02db73fd5185983d6847
3,653,110
def load_hosts_conf(path='/etc/hosts'): """parse hosts file""" hosts = {} try: with open(path, 'r') as f: for line in f.readlines(): parts = line.strip().split() if len(parts) < 2: continue addr = ip_address(parts[0]) ...
c6e2d1f34f5aa140a3bccfbd4d9791641cc75fff
3,653,111
import os def get_first_env(*args): """ Return the first env var encountered from list PLEASE NOTE: Always prefer using get_env, this helper is for app transitioning to a new config structure. Example: get_first_env('DB_NAME', 'DATABASE_NAME') """ for name in args: if nam...
70438ee5b991e2f6c90905e89fb16fb0fd6f5de2
3,653,112
import pandas def pick(df, isnotnull=None, **kwargs): """Function to pick row indices from DataFrame. Copied from kkpandas This method provides a nicer interface to choose rows from a DataFrame that satisfy specified constraints on the columns. isnotnull : column name, or list of co...
e8cdf1fb88ef92748c73095c62ca80c29bd40fec
3,653,113
import random def _waveform_distortion(waveform, distortion_methods_conf): """ Apply distortion on waveform This distortion will not change the length of the waveform. Args: waveform: numpy float tensor, (length,) distortion_methods_conf: a list of config for ditortion method. ...
cca32854f3d72f381d40a5ca8802c29996413149
3,653,114
def _pad_returns(returns): """ Pads a returns Series or DataFrame with business days, in case the existing Date index is sparse (as with PNL csvs). Sparse indexes if not padded will affect the Sharpe ratio because the 0 return days will not be included in the mean and std. """ bdays = pd.dat...
fde27dd928d3f0510f98fa4eba8f89f7d6b81922
3,653,115
def add_header(r): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public...
3a758340d1c13cc29f0013f3d2fec77c47099c02
3,653,116
def pair_sorter(aln): """Get the alignment name and attributes for sorting.""" return ( aln.name, not aln.first_in_pair, aln.unmapped, aln.supplementary_alignment, aln.secondary_alignment)
217eac7c89a12f68f4c9fe324c4feb6c2a955d58
3,653,117
import requests import yaml import json def _read_input_from(input_from): """ Reads the labels from the input from. """ inputs = [] for input_from_line in input_from.splitlines(): # Skip if line is empty. if input_from_line.strip() == '': continue # Load file content ...
2477771fecf99e1f6ef59a0ebeceb3a650b9f414
3,653,118
def project_to2d( pts: np.ndarray, K: np.ndarray, R: np.ndarray, t: np.ndarray ) -> np.ndarray: """Project 3d points to 2d. Projects a set of 3-D points, pts, into 2-D using the camera intrinsic matrix (K), and the extrinsic rotation matric (R), and extrinsic translation vector (t). Note that this ...
5f9bc03ae0086649746651da4e5e8e1d870db6bd
3,653,119
import copy def uncontract_general(basis, use_copy=True): """ Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not ...
de6638ae34b4d6f0b3a467048683ac363f71f9c1
3,653,120
def read_sd15ch1_images(root_dir, image_relative_path_seq, resize=None, color=False): """ WARNING ------- - All images must have the same shape (this is the case for the frames, and all models but the ones of the "01-origina...
0d6efd2eac2762440ae532564e4f680a1f056d30
3,653,121
def is_private_bool(script_dict): """ Returns is_private boolean value from user dictionary object """ return script_dict['entry_data']['ProfilePage'][0]['graphql']['user']['is_private']
1e8b30a38dc527dc5e2ea73e75c253d8f1a59550
3,653,122
def manage_greylist(request): """ View for managing greylist. """ message = None if request.method == 'POST': form = GreylistForm(request.POST) if form.is_valid(): # Set details to empty string if blank new_greylisted_guest = form.save(commit=False) ...
eafbbf10b6150189d25c7d863cb00f6565648925
3,653,123
def get_regions(): """Summary Returns: TYPE: Description """ client = boto3.client('ec2') region_response = client.describe_regions() regions = [region['RegionName'] for region in region_response['Regions']] return regions
700119f1c852ad9475823170388c062f62291637
3,653,124
def _is_ignored_read_event(request): """Return True if this read event was generated by an automated process, as indicated by the user configurable LOG_IGNORE* settings. See settings_site.py for description and rationale for the settings. """ if ( django.conf.settings.LOG_IGNORE_TRUSTED_SU...
f6f7417fe923ef6bd56a6d649ef302ed811185e8
3,653,125
def aten_embedding(mapper, graph, node): """ 构造embedding的PaddleLayer。 TorchScript示例: %inputs_embeds.1 : Tensor = aten::embedding(%57, %input_ids.1, %45, %46, %46) 参数含义: %inputs_embeds.1 (Tensor): 输出,embedding后的结果。 %57 (Tensor): weights。 %input_ids.1 (Tensor): 需要进行embeddi...
d174c7e551bb3db7e7dc5d9014de9edd48ee4032
3,653,126
import os def build_drivers(compilation_commands, linker_commands, kernel_src_dir, target_arch, clang_path, llvm_link_path, llvm_bit_code_out, is_clang_build): """ The main method that performs the building and linking of the driver files. :param compilation_commands: Parsed compilat...
ca6dcd258d118c8114204303e5993ee376780d70
3,653,127
def _validate_opts(opts): """ Check that all of the types of values passed into the config are of the right types """ def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of...
cafd1048a7496728715a192a4f70c7d50ade3622
3,653,128
async def from_string(input, output_path=None, options=None): """ Convert given string or strings to PDF document :param input: string with a desired text. Could be a raw text or a html file :param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string ...
2b3b6d9523d516fd3d258a3f722655720f49d91b
3,653,129
def parse_tuple(tuple_string): """ strip any whitespace then outter characters. """ return tuple_string.strip().strip("\"[]")
d0052dce0582ca04d70455f1833d98545792c8ac
3,653,130
def create_size(): """Create a new size.""" in_out_schema = SizeSchema() try: new_size = in_out_schema.load(request.json) except ValidationError as err: abort(400, {'message': err.messages}) try: db.session.add(new_size) db.session.commit() except IntegrityError...
f85b339c5ec5c38b8778de25456caa6fb0680d76
3,653,131
import click from typing import Optional def inject_snakefmt_config( ctx: click.Context, param: click.Parameter, config_file: Optional[str] = None ) -> Optional[str]: """ If no config file argument provided, parses "pyproject.toml" if one exists. Injects any parsed configuration into the relevant para...
4d1fc2996db4c63070f67ef6b19387b2b30ac5cd
3,653,132
def sort_by_ctime(paths): """Sorts list of file paths by ctime in ascending order. Arg: paths: iterable of filepaths. Returns: list: filepaths sorted by ctime or empty list if ctime is unavailable. """ ctimes = list(map(safe_ctime, paths)) if not all(ctimes) or len(set(ctimes)...
551b7bc1d2cdc416588cbd783c9b1ac3e5914077
3,653,133
def get_ospf_metric(device, destination_address): """Get OSPF metric Args: device (obj): Device object destination_address (str): Destination address """ out = device.parse('show route') # Example dictionary # "route-table": [ # { # ...
f5cd44794389a28db647e815baac4e954d59757b
3,653,134
def get_episode_url(): """エピソードの配信URLを追加 Returns: [type]: [description] """ # フォームの値を取得 episode_num = "#"+request.form['episode_num'][0] print(episode_num) # 配信先一覧を取得 podcasts = Podcast.query.all() broadcasts = Broadcast.query.all() # 配信先 url broadcast_urls = {...
e27f0324fd8332aa0648d35630cbb88b2b36c721
3,653,135
def autofs(): """Fixture data from /proc/mounts.""" data = "flux-support -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 flux-support.locker.arc-ts.umich.edu:/gpfs/locker0/ces/g/nfs/f/flux-support\numms-remills -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 umms-remills....
ea53c34d863de69c15f1e1247b98599c5f365ab7
3,653,136
def flag_dims(flags): """Return flag names, dims, and initials for flags. Only flag value that correspond to searchable dimensions are returned. Scalars and non-function string values are not included in the result. """ dims = {} initials = {} for name, val in flags.items(): try...
4cafd991e21facacf36423028288e4c5bb10c8d9
3,653,137
import shutil import os def where(cmd, path=None): """ A function to wrap shutil.which for universal usage """ raw_result = shutil.which(cmd, os.X_OK, path) if raw_result: return os.path.abspath(raw_result) else: raise ValueError("Could not find '{}' in the path".format(cmd))
bbac46386ef955190898e52ee3efa57aac3fa264
3,653,138
def to_stack(df, col, by, transform=None, get_cats=False): """ Convert columns of a dataframe to a list of lists by 'by' Args: df: col: by: transform: Returns: """ g = df.groupby(by) transform = _notransform if transform is None else transform x_data = [] ...
7bbf0ff609aaf2a6f5b49f80128ad06c04f93b5c
3,653,139
from typing import List def entries_repr(entries: List[Metadata]) -> str: """ Generates a nicely formatted string repr from a list of Dropbox metadata. :param entries: List of Dropbox metadata. :returns: String representation of the list. """ str_reps = [ f"<{e.__class__.__name__}(pat...
cc768a662ac6440ef7d5ca0eaddff5205a7c0a8c
3,653,140
def frequency_encode(dftrain, dftest, columnlist, output_type="include"): """ Frequency encode columns in columnlist. Parameters: dftrain: [DataFrame] train set dftest: [DataFrame] test set columnlist: [list] columns to encode. output_type: [str], default="include" will ...
3380853f0b5f88a6b2392a657424c4fc326876e2
3,653,141
def get_ranked_results(completed_rounds): """ For the rounds given in completed_rounds, calculate the total score for each team. Then all teams are sorted on total score and are given a ranking to allow for ex aequo scores. """ results = [] for team in QTeam.objects.all(): teamtotal = 0 ...
cea2afa2bb8de1db82450f323274af94ad3b633f
3,653,142
def get_subgraphs(): """ Returns a list of lists. Each list is a subgraph (represented as a list of dictionaries). :return: A list of lists of dictionaries. """ subgraph_list = [c.get("color") for c in classes if c.get("color") is not None] subgraphs = [] # Add to subgraphs all the lists of...
5e9b766b2c7f58d71eac62d88be64096272d2511
3,653,143
def score(self, features): """ return score from ML models""" assert len(self._models) > 0, 'No valid prediction model' scores = list() for feature in features: # when feature list extraction fails if not feature: scores.append(-float('inf')) continue item...
413eb4a0ecdcf0ac4b8f9cf9643b08a839c78b9a
3,653,144
def fromRGB(rgb): """Convert tuple or list to red, green and blue values that can be accessed as follows: a = fromRGB((255, 255, 255)) a["red"] a["green"] a["blue"] """ return {"red":rgb[0], "green":rgb[1], "blue":rgb[2]}
205a8f189d177e7af5cdc686e7c52fd2053a3c87
3,653,145
import math def computeTelescopeTransmission(pars, offAxis): """ Compute tel. transmission (0 < T < 1) for a given set of parameters as defined by the MC model and for a given off-axis angle. Parameters ---------- pars: list of float Parameters of the telescope transmission. Len(pars)...
50b2e2908726b8a77bc83a2821cf760b7475300b
3,653,146
def mean_iou( results, gt_seg_maps, num_classes, ignore_index, nan_to_num=None, label_map=dict(), reduce_zero_label=False, ): """Calculate Mean Intersection and Union (mIoU) Args: results (list[ndarray]): List of prediction segmentation maps. gt_seg_maps (list[ndarra...
a6d90cb4028c831db82b4dddb6a4c52a8fa4e1f0
3,653,147
def as_date_or_none(date_str): """ Casts a date string as a datetime.date, or None if it is blank. >>> as_date_or_none('2020-11-04') datetime.date(2020, 11, 4) >>> as_date_or_none('') None >>> as_date_or_none(None) None """ if not date_str: return None return dateut...
bf01bd280526e7962e1b08aa0400d6ebadf8053f
3,653,148
def guarantee_trailing_slash(directory_name: str) -> str: """Adds a trailling slash when missing Params: :directory_name: str, required A directory name to add trailling slash if missing Returns: A post processed directory name with trailling slash """ if not directory_...
38cfdf971262fceb4888277522b22ba7276fa9b7
3,653,149
def bc32encode(data: bytes) -> str: """ bc32 encoding see https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2020-004-bc32.md """ dd = convertbits(data, 8, 5) polymod = bech32_polymod([0] + dd + [0, 0, 0, 0, 0, 0]) ^ 0x3FFFFFFF chk = [(polymod >> 5 * (5 - i)) & 31 for i in ...
46feb2b744089f5f4bf84cae6ff9d29623b3bba5
3,653,150
def read_all_reviews(current_user): """Reads all Reviews""" reviews = Review.query.all() if reviews: return jsonify({'Reviews': [ { 'id': review.id, 'title': review.title, 'desc': review.desc, 'reviewer': review.reviewer.use...
78642f38dab8328c11445e67848b7f6d9583d892
3,653,151
def matches_filters(row, field_to_index, transformed_filters): """ Validate field name in transformed filter_expressions, return TRUE for rows matching all filters Parameters ------------ row : str row in `list` registry table (manager.show()) field_to_index : dict key = column ...
119b5e7d7f7dfb72e1a66525d5bf84665cbbced0
3,653,152
def div(f, other): """Element-wise division applied to the `Functional` objects. # Arguments f: Functional object. other: A python number or a tensor or a functional object. # Returns A Functional. """ validate_functional(f) inputs = f.inputs.copy() if is_functiona...
abfc7df85946cfcd5196dff58bec22ee237b590b
3,653,153
import itertools def select_latest_versions(files): """Select only the latest version of files.""" result = [] def same_file(file): """Return a versionless identifier for a file.""" # Dataset without the version number dataset = file.dataset.rsplit('.', 1)[0] return (datas...
81862d64ea44d0b0d9621bb198e5590c7f7ef0c7
3,653,154
def _gen_input(storyline, nsims, mode, site, chunks, current_c, nperc, simlen, swg_dir, fix_leap): """ :param storyline: loaded storyline :param SWG_path: path to the directory with contining the files from the SWG :param nsims: number of sims to run :param mode: one of ['irrigated', 'dryland'] ...
d0594a3b986c1415202db5f894101537464355a8
3,653,155
def guess_mime_mimedb (filename): """Guess MIME type from given filename. @return: tuple (mime, encoding) """ mime, encoding = None, None if mimedb is not None: mime, encoding = mimedb.guess_type(filename, strict=False) if mime not in ArchiveMimetypes and encoding in ArchiveCompressions:...
8202551c81b25e9bb104ec82114a750a16556b23
3,653,156
def get_paths(uast_file, max_length, max_width, token_extractor, split_leaves=True): """ Creates a list of all the paths given the max_length and max_width restrictions. :param uast_file: file containing a bblfsh UAST as string and binary-coded :param max_length: :param max_width: :param token_e...
cd2ec58f6d960317ac56a6992373f6aa311f9672
3,653,157
def get_members(): """ Get a list of all members in FreeIPA """ members = [] ldap_conn = ldap.get_con() res = ldap_conn.search_s( "cn=users,cn=accounts,dc=csh,dc=rit,dc=edu", pyldap.SCOPE_SUBTREE, "(uid=*)", ["uid", "displayName"], ) for member in res: ...
2714bddf7554884fa638066f91aa489b497f6c15
3,653,158
def _unicode_decode_extracted_tb(extracted_tb): """Return a traceback with the string elements translated into Unicode.""" return [(_decode(file), line_number, _decode(function), _decode(text)) for file, line_number, function, text in extracted_tb]
bbe020daecf6dc7021ff38dfac6869646120be5d
3,653,159
def load_table(source, version): """Load synth table from file """ filepath = get_table_filepath(source, version=version) return pd.read_table(filepath, delim_whitespace=True)
b95d35a6f297e0f73fee3652a0c9c6942b792451
3,653,160
def single_spaces(string: str) -> str: """Replaces all instances of whitespace-like chars with single spaces Args: string (str): The string to modify Returns: str: The cleaned string """ return UGLY_SPACES_RE.sub(" ", string)
eb37ae691f7fb54b6a23a5fd6d2cdd3edf8ebf57
3,653,161
import socket def snmp_count( address, oid, port=161, community="public", version=SNMP_v2c, timeout=10, bulk=False, filter=None, max_repetitions=BULK_MAX_REPETITIONS, tos=None, ioloop=None, udp_socket=None, ): """ Perform SNMP get request and returns Future to b...
0ddf236abeb1bca4d9a8584b7714225b1bc93166
3,653,162
def create_group(api_key: str, board_id: str, group_name: str, *args, **kwargs): """Creates a new group in a specific board. __________ Parameters api_key : `str` The monday.com v2 API user key. board_id : `str` The board's unique identifier. group_name ...
b591fe000718615f44954e488d4e3c46b9cf0123
3,653,163
import cvxopt def _solve_qp_ik_vel(vel, jac, joint_pos, joint_lims=None, duration=None, margin=0.2): """ Solves the IK for a given pusher velocity using a QP solver, imposing joint limits. If the solution is optimal, it is guaranteed that the resulting joint velocities will not cause the joints to rea...
25bd82403421f936d81d1a5c3090c1fbb1a964c1
3,653,164
def channel_will_be_next(crontab: str): """Checks if the given notification channel will be activated on the next channel, in an hour.""" return pycron.is_now(crontab, now + timedelta(hours=1))
b5505d7e27d70377cfb58acab8a38d9bd12d9351
3,653,165
def hospital_resident(residents, hospitals, optimal="resident"): """Solve an instance of HR using an adapted Gale-Shapley algorithm :cite:`Rot84`. A unique, stable and optimal matching is found for the given set of residents and hospitals. The optimality of the matching is found with respect to one part...
e666b502a2e74f5c4628108397a82977b7da5b7f
3,653,166
def log_request(response): """Log request. :param response: :return: """ ip = request.headers.get('X-Forwarded-For', request.remote_addr) host = request.host.split(':', 1)[0] app.logger.info(f"method={request.method}, path={request.path}, " f"status={response.status_cod...
838df023329b8b49c2349e58d02b44ef51ef7213
3,653,167
def reduce(path, n_procs, column, function): """ Calculate an aggregate value from IMB output. Args: path: str, path to file n_procs: int, number of processes column: str, column name function: callable to apply to specified `column` of table for `n_procs` in...
e2892b862f02ca11acaa180e24d390804441f0db
3,653,168
from pathlib import Path def output_file_path(status_id, phase): """ """ BASE_DIR = Path(__file__).resolve().parent.parent return f"%s/logs/stage/{status_id}-{phase}.txt" %str(BASE_DIR)
3bcbd80ad95389b9cf37fa66923bacb819ede710
3,653,169
def clean(some_string, uppercase=False): """ helper to clean up an input string """ if uppercase: return some_string.strip().upper() else: return some_string.strip().lower()
cdc4587b762625e00c91189950bd45840861c93f
3,653,170
import re def to_title(value): """Converts a string into titlecase.""" t = re.sub("\s+", ".", value) t = filter(LETTER_SET.__contains__, t) t = re.sub("([a-z])'\W([A-Z])", lambda m: m.group(0).lower(), t.title()) return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
a88c9559abeab7426fa874e66c9e81a75138c0cd
3,653,171
import yaml def parse_config_or_kwargs(config_file, **kwargs): """parse_config_or_kwargs :param config_file: Config file that has parameters, yaml format :param **kwargs: Other alternative parameters or overwrites for config """ with open(config_file) as con_read: yaml_config = yaml.load(...
f36946ed3a05f32057786ddf8e4194b935b4c129
3,653,172
def sig_generacion(m): """Devuelve la matriz resultante de aplicar las reglas del juego a cada celda""" FILAS = len(m) COLUMNAS = len(m[0]) if len(m) else 0 new_m = [] # matriz resultado for i in range(FILAS): l = [] # Una lista para ir generando una fila for j in range(COLUMNAS): ...
09da2baede2eef22179218f267bc2325d72822ee
3,653,173
import hmac import hashlib import base64 def calc_file_signature(data: str, password: str = None) -> str: """ Função que calcula o has da assinatura de um arquivo @param data: string assinada @param password: senha da assinatura @return: hash da assinatura """ if (password): digest...
1422b8058a6eb7995558b3e0a7fa5f33f6cfd134
3,653,174
def get_angle_from_coordinate(lat1, long1, lat2, long2): """https://stackoverflow.com/questions/3932502/calculate-angle-between-two-latitude-longitude-points""" dLon = (long2 - long1) y = np.sin(dLon) * np.cos(lat2) x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dLon) brng ...
a1ad7ffe1e63197cc5f70b2ce2f343078fd9b5e7
3,653,175
import json def get_predictions(): """Return the list of predications as a json object""" results = [] conn = None columns = ("pid", "name", "location", "latitude", "longitude", "type", "modtime") try: conn = psycopg2.connect(db_conn) # create a cursor cur = conn.cursor()...
6afb9d703f4dbeff81d4369f9096d577dcafc993
3,653,176
def parse_packageset(packageset): """ Get "input" or "output" packages and their repositories from each PES event. :return: set of Package tuples """ return {parse_package(p) for p in packageset.get('package', packageset.get('packages', []))}
ff8af3423c0fda993cfa88be16142520e29b999e
3,653,177
import urllib import zipfile def download_nyiso_csv(month, data_type, zone = None): """Downloads a NYISO csv dataset for a specific data type, month, and zone. Args: month: string denoting the first day of the month to be downloaded in yyyymmdd format data_type: string den...
cbe99ea482a26d5e59bf553ff143fe9895390f4e
3,653,178
def pretty_print_large_number(number): """Given a large number, it returns a string of the sort: '10.5 Thousand' or '12.3 Billion'. """ s = str(number).ljust(12) if number > 0 and number < 1e3: pass elif number >= 1e3 and number < 1e6: s = s + " (%3.1f Thousand)" % (number * 1.0 / 1e3)...
6762f34744da360b36d4a4fc0659fcf7d3fb0465
3,653,179
def find_aligning_transformation(skeleton, euler_frames_a, euler_frames_b): """ performs alignment of the point clouds based on the poses at the end of euler_frames_a and the start of euler_frames_b Returns the rotation around y axis in radians, x offset and z offset """ point_cloud_a = convert_...
1d323fcb0af73aacbc57e5cf57f0b9875375b98d
3,653,180
def find_all_visit(tx): """ Method that queries the database to find all VISIT relationships :param tx: session :return: nodes of Person , Location """ query = ( """ MATCH (p:Person)-[r:VISIT]->(l:Location) RETURN p , ID(p) , r , r.start_hour , r.end_hour , r.date ,...
851d790b16f9db285a6d09b5cabc4e12ad364484
3,653,181
def read_vectors(filename): """Reads measurement vectors from a space or comma delimited file. :param filename: path of the file :type filename: str :return: array of vectors :rtype: numpy.ndarray :raises: ValueError """ vectors = [] data = read_csv(filename) expected_size = le...
a772c4185d55543e0c641271a5af699f91e81b95
3,653,182
def get_scoring_algorithm(): """ Base scoring algorithm for index and search """ return scoring.BM25F()
78fe59d02071ce000262208f4c228566e0747857
3,653,183
def _make_augmentation_pipeline(augmentation_list): """Buids an sklearn pipeline of augmentations from a tuple of strings. Parameters ---------- augmentation_list: list of strings, A list of strings that determine the augmentations to apply, and in which order to apply them (the first s...
e53f4d198e6781c5eaf6ce6c0a453801f4ceb0d7
3,653,184
def ctg_path(event_name,sc_reform,path_cache,var_map,model,prev_events): """ Recursively computes the controllable and contigent events that influence the schedule of a given event. """ if event_name in path_cache:#If solution has been already computed, use it return path_cache[event_name] ...
5de8eb6fe3be991da3f4af37b6e81990aa8cb34f
3,653,185
def _setup_mock_socket_file(mock_socket_create_conn, resp): """Sets up a mock socket file from the mock connection. Args: mock_socket_create_conn: The mock method for creating a socket connection. resp: iterable, the side effect of the `readline` function of the mock socket file. Returns: The ...
5b70c73bb948211919065298a01a48d927e64482
3,653,186
def get_defense_type(action: int, game_config) -> int: """ Utility method for getting the defense type of action-id :param action: action-id :param game_config: game configuration :return: action type """ defense_type = action % (game_config.num_attack_types+1) # +1 for detection return...
68a05cf15bd833fb24aa448b8be2d08c1a949d12
3,653,187
def color_box( colors, border="#000000ff", border2=None, height=32, width=32, border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF ): """Color box.""" return colorbox.color_box( colors, border, border2, height, width, border_size, check_size, max_colors, alpha, border_...
6f8a98743c11985529afd5ad0c04a64c1301f85a
3,653,188
def get_performance_of_lstm_classifier(X, y, n_epochs, verbose=1, final_score=False): """ Reshapes feature matrix X, applies LSTM and returns the performance of the neural network :param X: List of non-reshaped/original feature matrices (one per logfile) :param y: labels :param n_epochs: Number of ...
13a494f9aca643ff23ce6954471ef007df96f9e8
3,653,189
def worker(data): """Thread function.""" width, column = data queen = Queen(width) queen.run(column) return queen.solutions
ef0f3c6410885ac2e20b28f009085d92b6fca22b
3,653,190
def eitem(self, key, value): """Translate included eitems.""" _eitem = self.get("_eitem", {}) urls = [] for v in force_list(value): urls.append( { "description": "E-book by EbookCentral", "value": clean_val("u", v, str), } ) _e...
d9a5d3f9dc29baa15d9df6b4fe32c7f20151316c
3,653,191
def annotate_group(groups, ax=None, label=None, labeloffset=30): """Annotates the categories with their parent group and add x-axis label""" def annotate(ax, name, left, right, y, pad): """Draw the group annotation""" arrow = ax.annotate(name, xy=(left, y), xycoords="data", ...
33f57ccf96b4b0907ea8c2ea161e19b0e6e536d2
3,653,192
def background_schwarzfischer(fluor_chan, bin_chan, div_horiz=7, div_vert=5, mem_lim=None, memmap_dir=None): """Perform background correction according to Schwarzfischer et al. Arguments: fluor_chan -- (frames x height x width) numpy array; the fluorescence channel to be corrected bin_chan -- b...
512d1721dc14a4f7a09843603b8700360f97fd37
3,653,193
from typing import Optional import os def _get_eula_date(extract_path: str) -> Optional[str]: """Get any EULA accept date in the install script, if any. :param extract_path: The path to the extracted archive. :return: The EULA date, if any. """ install_script = os.path.join(extract_path, "houdin...
044ff76dadf7c4bdcd74b1435e02d2ec29c0a877
3,653,194
def get_output_data_path(extension, suffix=None): """Return full path for data file with extension, generated by a test script""" name = get_default_test_name(suffix) return osp.join(TST_PATH[0], f"{name}.{extension}")
ce5437c23061df490a31ac11f26f72e5935f0fd7
3,653,195
def _plot(self, **kwargs) -> tp.BaseFigure: # pragma: no cover """Plot `close` and overlay it with the heatmap of `labels`.""" if self.wrapper.ndim > 1: raise TypeError("Select a column first. Use indexing.") return self.close.rename('close').vbt.overlay_with_heatmap(self.labels.rename('labels'), ...
eaa6df4f29db8d1ab6dc0ffd1b9ecf8804f6aac9
3,653,196
def _set_global_vars(metadata): """Identify files used multiple times in metadata and replace with global variables """ fnames = collections.defaultdict(list) for sample in metadata.keys(): for k, v in metadata[sample].items(): print k, v if os.path.isfile(v): ...
23caefdf0f999a9b60649c85278edb8498b771b3
3,653,197
def user_get(context, id): """Get user by id.""" return IMPL.user_get(context, id)
b3108b4627751d5dfef1b42b8ccad0295b33cc99
3,653,198
def unpack_singleton(x): """ >>> unpack_singleton([[[[1]]]]) 1 >>> unpack_singleton(np.array(np.datetime64('2000-01-01'))) array('2000-01-01', dtype='datetime64[D]') """ while isinstance(x, (list, tuple)): try: x = x[0] except (IndexError, TypeError, KeyError): ...
f6f55ff17ba29aab5946c682b825c72eb70324dd
3,653,199