content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def acad_to_academy(text): """ A function to change `Acad` to `Academy`. Smartly. Tries to ignore instances of `Acad` followed by `emy` or `emies`. Usage: from core.utils import acad_to_academy replace_str = 'Harmony Science Acad (Waco)' print acad_to_academy(replace_str) ...
50f515d2b0c67a5a50799c92ea0a51d6828107b9
3,612,100
from pathlib import Path def load_database(path): """Return database metadata object for the database stored in ``path``. This is the default way of loading a database for read-only purposes in estimagic. Args: path (str or pathlib.Path): location of the database file. If the file does ...
ba73be7d3ea39a2324bf6340e84607df5c774f43
3,612,101
def broad_sel_egress_queue( data # type: "XDR Data" ): """Broadcom Selected Egress Queue - Type: Flow, Enterprise: 4413, Format: 1""" datagram = {} datagram["Queue"] = packet_direction(data.unpack_uint()) data.done() # Verify all data unpacked return datagram
fc263fcd88d22010f57191790e110766219d4591
3,612,102
def _earlygetopt(aliases, args): """Return list of values for an option (or aliases). The values are listed in the order they appear in args. The options and values are removed from args. >>> args = ['x', '--cwd', 'foo', 'y'] >>> _earlygetopt(['--cwd'], args), args (['foo'], ['x', 'y']) >...
034bf7e4cde24cc45ed888b742361ce0a4ed1a8b
3,612,103
def cluster_leftovers(times, waveforms): """Reassign all datapoints labeled -1""" time_joined_waveforms = np.hstack([ waveforms, (times - np.mean(times))[:, None] / 3600.0 ]) time_based_umap = umap.UMAP(n_components=3, n_neighbors=10, min_dist=0.01).fit_transform( time_joined_wa...
df7e782a508e8a6ef7bf7090afc89c2311915a02
3,612,104
import statistics def cue_iti_responding(timecode, eventcode, code_on, code_off, counted_behavior): """ :param timecode: list of time codes from operant conditioning file :param eventcode: list of event codes from operant conditioning file :param code_on: event code for the beginning of a cue :par...
ed94f8a7fbe6e3c2c210eae81dcb34525eccd38d
3,612,105
def rmse(a, b): """Root Mean Square Error""" return np.sqrt(np.mean(np.sum((a - b)**2, axis=1)))
ff73fd1b5f9c4a8b9d3b0335ba59cf992fd50501
3,612,106
def ais6tobitvecSLOW(str6): """Convert an ITU AIS 6 bit string into a bit vector. Each character represents 6 bits. This is for text sent within ais messages If the original BitVector had ((len(bitvector) % 6 > 0), then there will be pad bits in the str6. This function has no way to know how man...
662325dae3eb0bd66cba37f8b7b6eecf06680781
3,612,107
from openghg.store import recombine_datasets from openghg.retrieve import search from openghg.dataobjects import FootprintData def get_footprint( site: str, domain: str, height: str, model: str = None, start_date: Timestamp = None, end_date: Timestamp = None, species: str = None, ) -> Foot...
a6c7842e26b97786871f44adcea2b6cc5710410d
3,612,108
def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """ thread = Thread(*a, **kw) thread.daemon = True return thread
66486777e5a0e5d7476e2de1f3197491d1b3745d
3,612,109
import string def autolink(text, trim_url_limit=None, nofollow=False): """ Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the righ...
74d1874f7338247e149caf4ae966f2531d3c494b
3,612,110
def chunks(l, n): """ https://stackoverflow.com/a/1751478 """ n = max(1, n) return (l[i : i + n] for i in range(0, len(l), n))
01bcae9d06bf430874717b70039c79de532b9fd4
3,612,111
def make_0235(pc): """EXP/JOBEXP""" result = pack_int(0) #EXP(x0.1%) result += pack_int(0) #JobEXP(x0.1%) result += pack_byte(0) #WarRecodePoint result += pack_int(0) #ecoin return result
3e48d7d8d67f3b47246ee572de58d2c1511d2d00
3,612,112
def np_hsv_value_histogram(v): """ Create Matplotlib histogram of value values for an HSV image and return the histogram as a NumPy array image. Args: v: Value values as a 1-dimensional float NumPy array Returns: Matplotlib histogram of saturation values converted to a NumPy array image. """ title...
0b461029d90b71a4618529d035c57242ac05c342
3,612,113
from datetime import datetime def get_stock(stock: str, beg: datetime, fin: datetime): """gets stock data and writes .csv file""" new_beg = datetime(beg.year, beg.month, beg.day - 1) df = yf.download(stock, start=new_beg, end=fin) return df
092c84d87e37fea7a4584e4145558005ef0aabf0
3,612,114
def is_case_special_activated(b, location, k): """Teste si le toit n'est pas affiché en raison de la position de Knil""" x, y = location x0, y0 = getOrigin(b) kx, ky = Knil.getPos(k) knil_case = getCase(b, kx+x0, ky+y0) special_attrib = bool("special_case" in knil_case.keys()) case = getCase(b, x, y) if "spec...
93962c3393b83852fd5f07e072198566eb68a9e9
3,612,115
def plugin_zip(p): """Maps columns to values for each row in a plugins sql_response and returns a list of dicts Parameters ---------- p : :class:`taniumpy.object_types.plugin.Plugin` * plugin object Returns ------- dict * the columns and result_rows of the sql_response in P...
b91e5403fd710875c4588afc0eba3da1b1a82c4a
3,612,116
def species_list(): """ """ spc_081 = ( SpeciesFactory( spc="081", spc_nmco="lake trout", spc_nmsc="Salvelinus namaycush" ), ) spc_091 = ( SpeciesFactory( spc="091", spc_nmco="lake whitefish", spc_nmsc="Coregonus clupeaformis" ), ) spc_093...
682398d1c1e6679a4aa22990d210cc45a1f0bd61
3,612,117
from typing import Tuple from typing import List def get_annotated_sentences(sentences: pd.DataFrame) -> Tuple[ List[int], List[Tuple[LexicalTreeNode, List[IGTag]]], List[str] ]: """ :param sentences: DataFrame of sentences with sentence type (r/c) - output of get_sentence_type :return: Tuple...
c66548f2447e2a4c9be7fa9e64656d3bcd5dcff3
3,612,118
import platform import subprocess def ping(host): """ Returns True if host responds to a ping request """ # Ping parameters as function of OS ping_num_param = "-n" if platform.system().lower() == "windows" else "-c" # Ping return subprocess.run(['ping', ping_num_param, '1', host], stdout...
7665ab5c43380e9b847037c84e03296f00f348a1
3,612,119
from typing import Callable from typing import Any def get_content_message_handler( callback: Callable[[Update, CallbackContext], Any] ) -> MessageHandler: """ Creates a universal message handler, that catches all messages, that should be considered as diary content. :param callback: Function to be r...
d8092133bb95785111e946b20907ecd80abd3990
3,612,120
def get_string_from_ascii(input): """ This function is reversed engineered and translated to python based on the CoderUtils class in the ELRO Android app :param input: A hex string :return: A string """ try: if len(input) != 32: return '' byt = bytearray.fromhex...
fdf878ac689c614720e9ad5ebeecbd32c9f893b1
3,612,121
def admin_new_prompt(): """ get: resets prompt """ if session.get('admin') is True: random_generator() flash('New random prompt generated') return redirect(url_for('.admin')) abort(404)
9ac717b7e68f78d5f53657c91e1c88631454fdb6
3,612,122
def split_multiline(value): """Special behaviour when we have a multi line options""" value = [element for element in (line.strip() for line in value.split('\n')) if element] return value
a5eecefb94a79639afe3582e4c3cfb8e7a0adf6f
3,612,123
def get_price_change_rate(order_book_ids, start_date=None, end_date=None, expect_df=False, market="cn"): """获取价格变化信息 :param order_book_ids: 股票列表 :param start_date: 开始日期: 如'2013-01-04' :param end_date: 结束日期: 如'2014-01-04';在 start_date 和 end_date 都不指定的情况下,默认为最近3个月 :param expect_df: 返回 DataFrame (Defa...
7e6f6e178a05c43abe2d13330209b80e2ebd7acd
3,612,124
def positive_x_gradient(x, constants, variables): """ Returns gradients of the positive x constraints. :param np.ndarray x: Parameters of updated Voce-Chaboche model. :param dict constants: Defines the constants for the constraint. :param dict variables: Defines constraint values that depend on x. ...
d2b1a23e3b27ccbeec88842ea6da8a69a3eb88b7
3,612,125
def create_borrow_time_list(config): """create a list of borrow time limits""" limit_list = [] current = 0 for i in range(MAX_LEVEL + 1): current = max(current, config['core']['borrow time limit'].get(str(i), 0)) limit_list.append(current) config['core']['borrow time limit'] = limit_...
746a1bab4621227bc150506ab8500e07e583c998
3,612,126
from typing import OrderedDict def _to_pdb_ccd_cif_dict(component): """Export component to the PDB CCD CIF file. Args: component (pdbeccdutils.core.Component): Component to be exported. Returns: (dict of str: str)): dictionary representation of the component to be...
b021aa205221391363c5927d7ca714cf69fe7810
3,612,127
import os def git_src_dir(projects_yaml, project): """ Return the directory where the specified project's source is located. """ parent_dir = '/mnt/openstack-git' projects = _git_yaml_load(projects_yaml) if 'directory' in projects.keys(): parent_dir = projects['directory'] for p...
53ca7463ecd65bc5ec7fbb133c6fe3e67f8a9d5a
3,612,128
from typing import Tuple from typing import List def yield_stdev( model: pyhf.pdf.Model, parameters: np.ndarray, uncertainty: np.ndarray, corr_mat: np.ndarray, ) -> Tuple[List[List[float]], List[float]]: """Calculates symmetrized yield standard deviation of a model, per bin and channel. Retur...
39376b46e0661cac1986df439141c37b3bdb5c9f
3,612,129
import re def limit_carbon(comp, C_limit=25): """True if the compound exceeds the carbon atom limit, otherwise False.""" regex = re.compile('[A-Z]{1}[a-z]*[0-9]*') try: formula = comp['Formula'] except KeyError: try: comp_id = comp['_id'] except KeyError: ...
1b5065cee5b047896e5efc1cf3d7a48448c8d7bc
3,612,130
async def add_premis_event( base_path, workspace_path, event_type, event_datetime, event_detail, event_outcome, event_target=None, event_outcome_detail=None, **kwargs): """ Add a PREMIS event using dpres-siptools tool 'premis-event' """ args = [ "premis-event", "--base_pa...
325ccd05f447a14875419bd14fee887c580f931c
3,612,131
def create_vocab_dictionaries(args): """Takes as input the path for an annotated freebase data file, and returns dictionaries word2ix, ix2word w.r.t the questions found in the file""" sbj_mid, predicate, obj_mid, question = DataCreator.get_spo_question(args.path_load_sq, ...
8ceb976bfc6a7422014ad79d9fa6409254fb4f71
3,612,132
def send_get_request(url, params=None): """ Return HTTP GET decoded JSON response as dict. """ response = request_get(url, params=params) if response.status_code != HTTP_200_OK: exception(response) return '' return response.json()
ba23d1d55d5c85addf297164afbbfe60c7dbb9fc
3,612,133
def MakeListComprehensionFunction (name, nsets): """Returns a function applicable to exactly <nsets> sets. The returned function has the signature F(set0, set1, ..., set<nsets>) and returns a list of all element combinations as tuples. A set may be any iterable object. """ if nsets <...
b37c9ca933790d2bd51dade77dedc3e902d6cf4c
3,612,134
def transform_trace_log_to_event_log(log, include_case_attributes=True, case_attribute_prefix='case:'): """ Converts the trace log to an event log Parameters ---------- log: :class:`pm4py.log.log.TraceLog` A trace Log includes_case_attributes: Default is True case_attribute_...
ef29bfc5832edd72a8dd4d0829393351df3723da
3,612,135
import torch def avg_pool(x, inds): """ Pools features with the maximum values. :param x: [n1, d] features matrix :param inds: [X, X, ..., X, max_num] pooling indices :return: [X, X, ..., X, d] pooled features matrix """ # Add a last row with minimum features for shadow pools x = torc...
999f71004afd3542d161187355e44a0a8e667d7c
3,612,136
def validate_ip_address(ip_address): """Return True if the provided IP address is a valid IPv4 or IPv6 address""" return validate_ipv4_address(ip_address) or \ validate_ipv6_address(ip_address)
33d14508d0a9fa2b5626305911f3dc4dece91c93
3,612,137
def lambda_remove_resource_policy(**kwargs): """Remove lambda resource policy.""" response = aws_lambda.remove_permission(**kwargs) log.info("lambda_remove_resource_policy: {}".format(response)) return response
6ff73f62d2fcb62c6026bb4020d54704f2846ea5
3,612,138
from typing import Iterator def getDiskImages(db: ArtifactDB, limit: int = 0) -> Iterator[Artifact]: """Returns a generator of disk images (type = disk image). Limit specifies the maximum number of results to return. """ return _getByType(db, 'disk image', limit)
7da58f00ce7bcf6f3ab78ffd044e85e5378ffe20
3,612,139
async def add_unconfirmed_transaction(transaction: Transaction): """ broadcasts transactions to all nodes """ sender_signature = transaction.sender_signature pub_sender_key = transaction.sender_public_send_key receiver = transaction.receiver amount = transaction.amount new_transaction = bl...
f0bede4b94015b73f1674c434eecfd11198a2a46
3,612,140
from ostap.utils.progress_bar import progress_bar def _add_response_chain ( chain , *args ) : """Specific axction to ROOT.TChain """ files = chain.files() cname = chain.GetName() status = None verbose = True and 1 < len ( files ) for f in progress_bar ( files , len ...
d5b2b8bbae48ee8c831fec9e2fe23d90a86b5c62
3,612,141
def center_align_x(shapes): """ Returns a constraint setting the shapes' centers' x-coordinates equal. """ s = FreshSymbol(REAL) return And(Equals(shape.center.x, s) for shape in shapes)
51ebe2c67c2e0a1a89b59b7fd80cfd3af18845af
3,612,142
def locate_qr_code_using_slider(image, scanner): """Try sliding a window over the image to search for the QR code.""" for slider in window_slider(image): cropped = image.crop(slider) results = scanner.scan(cropped) if results: box = bbox(results) # Box is relative...
72f9fe70a0dd72f180589ccbd1d6c6a77768345e
3,612,143
def ParseRegionalFlags(args, resources, message=None): """Make Frontend suitable for RegionalLister argument namespace. Generated client-side filter is stored to args.filter. Args: args: The argument namespace of RegionalLister. resources: resources.Registry, The resource registry message: The respo...
69a34b3200a7158661afa9bbcff47888e52b9628
3,612,144
import argparse def GetArgs(): """ Supports the command-line arguments listed below. """ parser = argparse.ArgumentParser(description='A utility to perform various conversions for the ZeroOne project') parser.add_argument('-i', '--input', required=True, action='store', help='Specify the name of t...
8ffe26bbc7e0339ceb3cda6117adc0d9ef890ccd
3,612,145
def __virtual__(): """ Only load if boto libraries exist. """ has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__["boto3.assign_funcs"](__name__, "sns") return has_boto_reqs
57cefe1152f135ea0cf30b0b69e7a9946edb756e
3,612,146
def GetRegionFromZone(zone_or_region): """Returns the region a zone is in (or "zone_or_region" if it's a region).""" if IsRegion(zone_or_region): return zone_or_region return zone_or_region[:-1]
060835fb21f6bcd3bd0a2151ff96493f784b88ae
3,612,147
import re def unhtmlify(html): """ Remove html-tags and unescape encoded html-entities. :param html: Evil-string containing html :return: """ return unescape(re.sub(r'<.*?>', '', html))
0a3f56c5cba9b878113cd2dde70097bbcb8e12b8
3,612,148
def CalculatePath3(mol): """ ################################################################# Calculation of the counts of path length 3 for a molecule ################################################################# """ return _CalculatePathN(mol, 3)
4011c27db51f91980d0f1e09024a5fff414e1fb6
3,612,149
def _preferred_string(value1, value2): # pylint:disable=too-many-return-statements """ Retrieves preferred title from both values. :param value1: :type value1: str :param value2: :type value2: str :return: The preferred title :rtype: str """ if value1 == value2: return v...
9a5e22d1f8b8db70d8c5ae998bda1689cd2987c6
3,612,150
from typing import List import torch def load_nets(name: str, in_shape: List[int], bias=False, **kwargs) -> torch.nn.Module: """ Creates an instance of a network architecture. :param name: name of the model of which an instance is to be created. :param in_shape: shape of the inputs the model expects (...
2d12118dc9df2f9107dc1dbaf0018e7ffeb277bc
3,612,151
def timestamp_to_epoch(timestamp: str) -> int: """Takes a `timestamp` str and attempts to convert it to an epoch value using the list of known time stamp formats. :param timestamp: str :return: int """ for ts_fmt in KNOWN_TIMESTAMP_FORMATS: try: return pendulum.from_format(...
7920357dce852f079fde2e7b5243e16ac3cf79ee
3,612,152
def get_labels_from_responsibility_string(responsibility_string, include_none=False, warn_on_legacy_responsibilities=True): """ :param responsibility_string: :param include_none: If 'none' should be included in the returned list when no other responsibilities are present :return: """ if respons...
60329ed9126206bfb3b63a2e233736907e5d380c
3,612,153
def get_saved_session(**kwargs): """Gets a SessionState object for the current session. Creates a new object if necessary. Parameters ---------- **kwargs : any Default values you want to add to the session state, if we're creating a new one. Example ------- >>> session...
4d194d1f757278afa3e24da1ddbd63d8ef4244be
3,612,154
def frame_center_satspots(array, xy, subim_size=19, sigfactor=6, shift=False, debug=False): """ Finds the center of a frame with waffle/satellite spots (e.g. for VLT/SPHERE). The method used to determine the center is by centroiding the 4 spots via a 2d Gaussian fit and finding t...
8fb3a3efa0ec7bdbea77d6e72a0cdf8be587ef4c
3,612,155
def prev_surname(prev_surname_val: str, **kwargs) -> ValidatedRecord: """Coerce and validate previous surname. Validation rules: Must contain only uppercase alphabetic characters and space, apostrophe or hyphen. Max length 35. Args: prev_surname_val (str): Previous surname to validate. Re...
8c209dd18871c96c3632fcdd937075d0aceec754
3,612,156
import re def class_in_endpoint(class_, entrypoint): """Check if a given class is in the EntryPoint object as a class.""" regex = r'(vocab:)?(.*)EntryPoint/(.*/)?' + re.escape(class_["title"]) + r'$' # Check supportedProperty for the EntryPoint try: supportedProperty = entrypoint["supportedPro...
d28e18ee40992aabc38a2fa4423e3717217fcc89
3,612,157
def compute_mean_median(all_methods_df): """ Computes the mean values and the median values for each column of the Pandas.DataFrame grouped by the methods. Parameters ---------- all_methods_df : Pandas.DataFrame Returns ------- list - means: Pandas.DataFrame containing the ...
b4397bfcef8e0215e3478f1f50708aa4608a14e2
3,612,158
def get_circumsphere(S): """ Computes the circumsphere of a set of points Parameters ---------- S : (M, N) ndarray, where 1 <= M <= N + 1 The input points Returns ------- C, r2 : ((2) ndarray, float) The center and the squared radius of the circumsphere """ U = ...
fcc7fc1c787cf35778c70f3b4bcac1bd3e920227
3,612,159
import textwrap def random_mac(separator='', uppercase=False, oui=''): """return random mac address. OUI should not contain separators""" if len(oui) == 6 and is_hex(oui): digits = textwrap.wrap(oui, 2) digits += [format(randrange(256), '02x') for _ in range(3)] else: digits = [for...
98440a8c8dd16b604b1c39ee8051da485a688124
3,612,160
import torch def unmold_boxes_x(boxes, class_ids, masks, image_shape, window, scores=None): """Reformats the detections of one image from the format of the neural network output to a format suitable for use in the rest of the application. detections: [N, (y1, x1, y2, x2, class_id, score)] masks: ...
aea658af0c9e87b2427972a6be7a5d967dc8330f
3,612,161
def get_volumes_in_pool_recycle_bin(session, pool_id, start=None, limit=None, return_type=None, **kwargs): """ Retrieves a list of volumes in the pool's recycle bin. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Req...
5cf9282087686c0956547fbc9fe9163c178052f6
3,612,162
import torch def get_cosinebased_yaw_pitch(input_: torch.Tensor) -> torch.Tensor: """ Returns a tensor with two columns being yaw and pitch respectively. For yaw, it uses cos(yaw)'s value along with sin(yaw)'s sign. Args: input_: 1st column is sin(yaw), 2nd Column is cos(yaw), 3rd Column is si...
ca5c10908de8dfa8b86446a1874b1ef780ae5313
3,612,163
from typing import Iterable def generate_episode_statistics(trackers: Iterable['Tracker'] ) -> AgentStatisticsMap: """Generate episode statistics from set of trackers """ statistics = combine_statistics([t.get_episode() for t in trackers]) return statistics
2d97f441385b7f192daad35d3e0a38ea7d044979
3,612,164
def GaussElimination(MATRIX,B): """ Applies Gauss Elimination Algorithm to MATRIX in order to solve a linear system MATRIX.X = B. MATRIX is transformed to row echelon form: |1 * * * * * | |0 1 * * * * | |0 0 1 * * * | |0 0 0 1 * * | |0 0 0 0 1 * | |0 0 ...
180c7889f41a5e6e0c3b9fb02e27a8eee3ea6c13
3,612,165
from typing import Sequence from typing import Optional from typing import Union from typing import Tuple import warnings def histogram_log( *, x_data: Sequence, bins: Optional[Union[Sequence, int]] = None, bin_width_initial: Optional[float] = None, bin_width_factor: Optional[float] = None, x_...
b73e25aa45f8497d7314e860623efea27b08b82a
3,612,166
def get_variants_from_log_trace_idx(log, parameters=None): """ Gets a dictionary whose key is the variant and as value there is the list of traces indexes that share the variant Parameters ---------- log Log parameters Parameters of the algorithm, including: Para...
bbdeb104c3d57f175759b87cbb6fe0b2ad7de958
3,612,167
import torch import asyncio import time async def test_partitioning_asynchronous(): """ensure that tensor partitioning does not interfere with asynchronous code""" tensors = [torch.randn(2048, 2048), torch.randn(1024, 4096), torch.randn(4096, 1024), torch.randn(30_000, 1024)] peer_fractions = [0.4, 0.3, 0...
7230f745ea452a2260118c15e32323faf734b305
3,612,168
def mark_entry_as_read_groups(request_ctx, group_id, topic_id, entry_id, forced_read_state=None, **request_kwargs): """ Mark a discussion entry as read. No request fields are necessary. On success, the response will be 204 No Content with an empty body. :param request_ctx: The request...
c031e40f134ecdbf2c7db8d248e20890cec54278
3,612,169
def has_capability(capability, jobboard_job=None): """ Check if the local machine has the specified capability :param str capability: The capability to evaluate :param obj jobboard_job: TaskFlow jobboard job :return bool capable: True if it has the capability, False if not """ # If the job i...
8b2dd091b3939c75b6a2fe2dfd65b4e9b95dd9d9
3,612,170
from re import T import numpy def tceil(tensor: T.Tensor) -> T.Tensor: """ Return a tensor with ceilinged elements. Args: tensor: A tensor. Returns: tensor: A tensor rounded up to the next integer (still floating point). """ return numpy.ceil(tensor)
6136ca238130b54efcff133ba50a49887fd0d09b
3,612,171
import re def CommitPositionFromBuildProperty(value): """Extracts the chromium commit position from a builders got_revision_cp property.""" # Match a commit position from a build properties commit string like # "refs/heads/master@{#819458}" test_arg_commit_position_re = r'\{#(?P<position>\d+)\}' match =...
c0fdb07ce3be907db3ec8628eaefc3ad1453ef34
3,612,172
from typing import List def dqn_mlp_network(hidden_sizes: List[int], num_actions: int) -> NetworkFn: """DQN MLP """ def net_fn(inputs): network = hk.Sequential([ dqn_mlp_torso(hidden_sizes), dqn_mlp_value_head(num_actions) ]) # return QNetwo...
b99ed49c66ca6c4fed0fe332bbd72b13a8cdd790
3,612,173
from typing import Optional import os def create_item( granule_href: str, read_href_modifier: Optional[ReadHrefModifier] = None, archive_format: Format = Format.SAFE, ) -> pystac.Item: """Create a STC Item from a Sentinel-1 GRD scene. Args: granule_href (str): The HREF to the granule. ...
01880ad3a58c3c3696accdc5d7c038a0c0d91fed
3,612,174
def batch_gather(values, indices): """Returns batched `tf.gather` for every row in the input.""" unpacked = zip(tf.unstack(values), tf.unstack(indices)) result = [tf.gather(value, index) for value, index in unpacked] return tf.stack(result)
e4a25b67189ed67f7d0954be08bb7eb3d36d94e5
3,612,175
def datatype_from_column_expression(c): """Determine a datatype from a column or column expression""" datatype = "unknown" try: if hasattr(c, "type") and c.type: # Check supported column types if isinstance(c.type, String): datatype = "str" elif is...
bf04e27c48a1dc5f863aea682a244f8bb602ca32
3,612,176
def context_top_elems(cur_elem, dict_result): """ Given a list of elements, return the object that is in the dict at that point dict_result = {'root': {'list1': ['dict1': {key: ""} ] } cur_elem = ['root', 'list1', 'dict1'] Should return a reference to a dict that is dict_result['dict1'] """ ...
8e3dc06dcc0d224ecfbeba2d7364e5466f73f22a
3,612,177
def example_data(): """Example data.""" return { 'id': 'eng', 'title': {'en': 'English', 'da': 'Engelsk'}, 'description': {'en': 'Text', 'da': 'Tekst'}, 'icon': 'file-o', 'props': { 'datacite_type': 'Text', }, }
de5ec1bb45080b5d24e9c8e123cc25b5cacc95ac
3,612,178
def rand_q() -> ElementModQ: """ Generate random number between 0 and Q. :return: Random value between 0 and Q """ return ElementModQ(randbelow(get_small_prime()))
bedc0d5c73bef5da1bcd77d9d05dacc2122fd8f2
3,612,179
def update_gloss(request, glossid): """View to update a gloss model from the jeditable jquery form We are sent one field and value at a time, return the new value once we've updated it.""" if not request.user.has_perm('dictionary.change_gloss'): return HttpResponseForbidden("Gloss Update Not Al...
5424264de7588561879190dc5949cb5d1e68601e
3,612,180
def PEditFD (inUV, outUV, err): """ Frequency-domain editing of UV data - produces FG table Editing is done independently for each visibility channel. First clipping is done on correlator and Vpol amplitudes. Following this, an average and RMS is determined for each channel in each timeAvg per...
f688105c8aa8c6ebc4e884e52ab2c7239438383c
3,612,181
def setup_scanner(hass, config, see, discovery_info=None): """Setup an endpoint for the GPSLogger application.""" hass.http.register_view(GPSLoggerView(see)) return True
90f94869a03ad7e2dd29271331cf2c604f490863
3,612,182
def calculate_antenna_visibility_limits(target,station,referenceephemtime,plusminusdays=1., elevation_limit_deg=15., interpsteps=100, alwaysup_fmt='nan', timeformat='ephem', LST_PT=False, verbose=False): """ Calculate the previous and next time within e.g. 24hrs when a target reaches a specified elevation ...
bf229763e51503d6d3d06c16a09ae3d2aac8cff7
3,612,183
def traverse_tree(t, parent_name=""): """ Returns the list of all names in tree. """ if parent_name: full_node_name = parent_name + "/" + t.name else: full_node_name = t.name if (t.children is None): result = [full_node_name] else: result = [full_node_name + "/"] ...
16b1773895569c108fde5f9a1a43a12a24314dcc
3,612,184
def s3_retrieve(key_path: str, study_object_id: str, raw_path:bool=False, number_retries=3) -> bytes: """ Takes an S3 file path (key_path), and a study ID. Takes an optional argument, raw_path, which defaults to false. When set to false the path is prepended to place the file in the appropriate study_id f...
05822dfccb777c609aeb9fa8b763e9fa61c0bd67
3,612,185
def _get_latlon(grid, dbz_fname): """ Generates latitude and longitude arrays. Parameters ---------- grid : Grid Py-ART grid object. dbz_fname : str Reflectivity field name. Returns ------- longitude : ndarray Array of coordinates for all points. latitud...
a14f1058bc9e451b20dcc28f11bed2321a6dfd49
3,612,186
def pad_stride(x: np.ndarray, w_r_shape, stride_i) -> np.ndarray: """ :param x: (bs, ch_o, h_o, w_o) :param w_r_shape: (bs, ch_i, h_k, w_k) :param stride_i: (int, int) :return: """ bs, ch_o, h_o, w_o = x.shape _, _, h_k, w_k = w_r_shape h_st, w_st = stride_i if h_st == 1 and w_...
879cbec573ee6b23e5b6ac807f2f2fa2342778fd
3,612,187
def attribute_fetcher(context, user_id): """ Read a user from the Dashboard private userdb and return an update dict to let the Attribute Manager update the use in the central eduid user database. :param context: Plugin context, see plugin_init above. :param user_id: Unique identifier :typ...
8686723bb7c936ede3a4af9d069ddf1c4e48d11b
3,612,188
import yaml from datetime import datetime def generate_cookie(username, address, environment_ids=None, methods=None, eternal=False, settings_path=None): """ Generate and return a cookie with the given information. username should be the username of the cookie user. environment_ids ...
b6099ea00159df2e3a81a00d8b9c0e5d21e3fd62
3,612,189
def extract_pdeep_mod(mod_pep, mod_ident='bracket', mod_trans=True): """ input: '_C[Carbamidomethyl (C)]DM[Oxidation (M)]EDER_' output: 'CDMEDER', '1,Carbamidomethyl[C];3,Oxidation[M];' """ stripped_pep, mod = rapid_kit.split_mod(modpep=mod_pep, mod_ident=mod_ident) if mod_trans: mod = t...
bf63bdaa89c91ab0eab33eabcf4dbc6eaa17833d
3,612,190
def create_conversion_dict(): """ -> parse the variable_description.xml file and return a dictionnary for the discretization procedure: variable_name : Possible_Values : Binary_Values -> use for convert posible values of a variable into binary values -> return a dictionnary """ description_file_name = "PARAMET...
12ba0ae810a551e44ba0022032008a76164b5942
3,612,191
def water_toluene_material_stream(): """ Create a homogeneous material_stream model """ pp_ = pp_water() pp_.addPropertyPackage(pp_toluene()) class material_stream(MaterialStream): def __init__(self, name, description, pp=None): super().__init__(name, description, prope...
1255be6b7d74910c9705f50d59ec73b1214dd98a
3,612,192
def GetPolyCoords(geometry,coord_type): """ ===================================================== getPolyCoords(geometry,coord_type) ===================================================== Returns Coordinates of Polygon using the Exterior of the Polygon. inputs: 1- geometry: ...
4a1a62617956baaac55f957cb7683826002b80d6
3,612,193
import pymongo import os import json def db2local(save_file="/opt/lavector/components/json.mongo", collect='label_corpus', use_cache=True): """ 从MongoDB 获取数据,保存到save_file中, mongo结果, 模型准确率为:0.6782511210762332 :param save_file: :param collect: label_corpus 获取成分的词的标注 :return: """ # 配置client, ...
5ef02b8dec08bcc822d8b464c00c25b0362f752d
3,612,194
def delete_playlist(playlist_id): """ Deletes a Todo with id = id """ dao = MusicDao() error, is_deleted = dao.delete_playlist(playlist_id) return error, is_deleted
70f987e50c4424cb9188003132fb82d596556275
3,612,195
import os def _gatk_base_recalibrator(broad_runner, dup_align_bam, ref_file, platform, dbsnp_file, intervals, data): """Step 1 of GATK recalibration process, producing table of covariates. For GATK 4 we use local multicore spark runs: https://github.com/broadinstitute/gatk/iss...
76dfbd5b6784d5c68cdb5aac17fdb20d852152d6
3,612,196
def poa_horizontal_ratio(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): """ Calculates the ratio of the beam components of the plane of array irradiance and the horizontal irradiance. Input all angles in degrees. Parameters ---------- surface_tilt : n...
77c6c86e7650aa5ffedbaf0417ff358a4dd69ac7
3,612,197
def _breakend_orientation(strand1, strand2): """Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [...
b730d21364e391fca46a5257b6786d24ceddb2fa
3,612,198
def test_unpickable_error_find_document(): """Check error messages for pickledb""" class UnpickableClass: i_am_not_pickable = None unpickable_doc = { "_id": 2, "a_pickable": 1, "b_unpickable": UnpickableClass(), "c_pickable": 3, } def make_pickable(uid): ...
0ec0298e122667ab8446f237c3b080213676bf8a
3,612,199