content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def showresults(options=''): """ Generate and plot results from a kima run. The argument `options` should be a string with the same options as for the kima-showresults script. """ # force correct CLI arguments args = _parse_args(options) plots = [] if args.rv: plots.appe...
0c5c944dc21e0abf808c258d8993f6133a254701
22,041
import re def convert_as_number(symbol: str) -> float: """ handle cases: ' ' or '' -> 0 '10.95%' -> 10.95 '$404,691,250' -> 404691250 '$8105.52' -> 8105.52 :param symbol: string :return: float """ result = symbol.strip() if...
cea1d6e894fa380ecf6968d5cb0ef1ce21b73fac
22,042
def smiles_dict(): """Store SMILES for compounds used in test cases here.""" smiles = { "ATP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C" + "@@H](O)[C@H]1O", "ADP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)O)[C@@H](O)[C" + "@H]1O", "meh": "CCC(=O)C(=O)O...
080373bdfb250f57e20e0e2b89702ac07c430f69
22,044
def prepare_parser() -> ArgumentParser: """Create all CLI parsers/subparsers.""" # Handle core parser args parser = ArgumentParser( description="Learning (Hopefully) Safe Agents in Gridworlds" ) handle_parser_args({"core": parser}, "core", core_parser_configs) # Handle environment subpa...
c0a42abf56f3c82ae09ef2459aae49fded71e9f0
22,045
def import_google(authsub_token, user): """ Uses the given AuthSub token to retrieve Google Contacts and import the entries with an email address into the contacts of the given user. Returns a tuple of (number imported, total number of entries). """ contacts_service = gdata.contact...
768b900ceac60cc69d1906ef915fdace8b6d0982
22,046
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(total)
30f0fa562cf88ca2986c3346b4111dcb18b1cb34
22,047
from datetime import datetime def validate_date(date, flash_errors=True): """ Validates date string. Format should be YYYY-MM-DD. Flashes errors if flash_errors is True. """ try: datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: if flash_errors: flask.flash('Invalid date provid...
ed3e45c3232da8d994f854001a3be852180681e0
22,049
def generate_error_map(image, losses, box_lenght): """ Function to overlap an error map to an image Args: image: input image losses: list of losses, one for each masked part of the flow. Returs: error_map: overlapped error_heatmap and image. """ box_lenght = int(box_lengh...
b4b8a8207a90226caba0c5f5be4c322dc6181a42
22,050
def get_order(oid): # noqa: E501 """Gets an existing order by order id # noqa: E501 :param oid: :type oid: str :rtype: Order """ oid = int(oid) msg = "error retrieving order" ret_code = 400 if oid in orders: msg = {"status": f"order retrieved", "order": orders[oid],...
d95051e027994b0bd7837859a3e7fd8106f4a07e
22,051
import operator def most_recent_assembly(assembly_list): """Based on assembly summaries find the one submitted the most recently""" if assembly_list: return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1]
1d7ecf3a1fa862e421295dda0ba3d89863f33b0f
22,052
import re def dict_from_xml_text(xml_text, fix_ampersands=False): """ Convert an xml string to a dictionary of values :param xml_text: valid xml string :param fix_ampersands: additionally replace & to & encoded value before parsing to etree :return: dictionary of data """ if fix_ampers...
fc008f9c9ef23640ed09adef3320eb549506988d
22,053
def find_encryption_key(loop_size, subject_number): """Find encryption key from the subject_number and loop_size.""" value = 1 for _ in range(loop_size): value = transform_value(value, subject_number) return value
cb9f58d065e4bc227ac034357981eac070834f73
22,054
import math def carla_rotation_to_RPY(carla_rotation): """ Convert a carla rotation to a roll, pitch, yaw tuple Considers the conversion from left-handed system (unreal) to right-handed system (ROS). Considers the conversion from degrees (carla) to radians (ROS). :param carla_rotation: the c...
30f4cd3facd3696d3f0daf25f2723d82541c89f2
22,055
from bempp.api.integration.triangle_gauss import rule from scipy.sparse import coo_matrix from scipy.sparse.linalg import aslinearoperator def compute_p1_curl_transformation(space, quadrature_order): """ Compute the transformation of P1 space coefficients to surface curl values. Returns two lists, curl_t...
6ad147c23fb9c153d534b742443c6238c1dc6f33
22,056
def _get_individual_id(individual) -> str: """ Returns a unique identifier as string for the given individual. :param individual: The individual to get the ID for. :return: A string representing the ID. """ if hasattr(individual, "identifier") and (isinstance(individual.identifier, list) and ...
e606d5eef7bfbcd0d76113c20f450be3c1e6b2ab
22,057
def get_self_url(d): """Returns the URL of a Stash resource""" return d.html_url if isinstance(d, PullRequest) else d["links"]["self"][0]["href"]
b7b88b49a1035ec7d15e4d0f7c864e489dccbf70
22,058
def shift(arr, *args): """ **WARNING** The ``Si`` arguments can be either a single array containing the shift parameters for each dimension, or a sequence of up to eight scalar shift values. For arrays of more than one dimension, the parameter ``Sn`` specifies the shift applied to the n-th dime...
b70a430039ba369d99a3c2edea920430eb27dfa1
22,059
def ConvertToMeaningfulConstant(pset): """ Gets the flux constant, and quotes it above some energy minimum Emin """ # Units: IF TOBS were in yr, it would be smaller, and raw const greater. # also converts per Mpcs into per Gpc3 units=1e9*365.25 const = (10**pset[7])*units # to cubic Gpc an...
e393f66e72c3a43e91e9975f270ac7dcf577ad3e
22,060
def hw_uint(value): """return HW of 16-bit unsigned integer in two's complement""" bitcount = bin(value).count("1") return bitcount
9a9c6017d3d6da34c4e9132a0c89b267aa263ace
22,061
import copy def clip(x,xmin,xmax) : """ clip input array so that x<xmin becomes xmin, x>xmax becomes xmax, return clipped array """ new=copy.copy(x) bd=np.where(x<xmin)[0] new[bd]=xmin bd=np.where(x>xmax)[0] new[bd]=xmax return new
502d8c5ce0427283bf02ead2d5f5c90c69e14638
22,062
def profile_from_creds(creds, keychain, cache): """Create a profile from an AWS credentials file.""" access_key, secret_key = get_keys_from_file(creds) arn = security_store(access_key, secret_key, keychain, cache) return profile_from_arn(arn)
62923959ce115bef776b32c3ed93a19aef93f9c3
22,063
import torch def test(model, test_loader, dynamics, fast_init): """ Evaluate prediction accuracy of an energy-based model on a given test set. Args: model: EnergyBasedModel test_loader: Dataloader containing the test dataset dynamics: Dictionary containing the keyword arguments ...
41c6e20fbcf11e76437a175f7b4662ec24b85773
22,065
def get_cluster_activite(cluster_path_csv, test, train=None): """Get cluster activite csv from patch cluster_path_csv. Merge cluster with station_id Parameters ---------- cluster_path_csv : String : Path to export df_labels DataFrame test : pandas.DataFrame train : pandas.DataFrame...
f8dbb1bb2149a58f8617f76cfdf1a4943f500314
22,066
from typing import Optional def get_ssl_policy(name: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSSLPolicyResult: """ Gets an SSL Policy within GCE from its name, for use with Target HTTPS and Target SSL...
1b4248a6a8dbbd735a006cc99de5d5e855c195ca
22,067
def getitem(self, item): """Select elements at the specific index. Parameters ---------- item : Union[slice, int, dragon.Tensor] The index. Returns ------- dragon.Tensor The output tensor. """ gather_args = [] if isinstance(item, Tensor): if item.dtype ...
0f7a4659a9fc3ac34fcee8f402fada7f622e11f0
22,068
import torch def zdot_batch(x1, x2): """Finds the complex-valued dot product of two complex-valued multidimensional Tensors, preserving the batch dimension. Args: x1 (Tensor): The first multidimensional Tensor. x2 (Tensor): The second multidimensional Tensor. Returns: The dot pro...
5e57dd7a693c420dd1b0c5c01523eb2f0fb85253
22,069
def serve_values(name, func, args, kwargs, serving_values, fallback_func, backend_name=None, implemented_funcs=None, supported_kwargs=None,): #249 (line num in coconut source) """Determines the parameter value to serve for the given parameter name and kwargs. First checks for unsupported funcs or kwargs, then ...
7ad5847df2d3904da7786ab0c77e5a0d9e6380cd
22,072
def find_peaks(sig): """ Find hard peaks and soft peaks in a signal, defined as follows: - Hard peak: a peak that is either /\ or \/. - Soft peak: a peak that is either /-*\ or \-*/. In this case we define the middle as the peak. Parameters ---------- sig : np array The 1d si...
486b30d506e3d79dc7df8d2503d3bc626b6791f5
22,073
def evenly_divides(x, y): """Returns if [x] evenly divides [y].""" return int(y / x) == y / x
dbf8236454e88805e71aabf58d9b7ebd2b2a6393
22,074
def proxmap_sort(arr: list, key: Function = lambda x: x, reverse: bool = False) -> list: """Proxmap sort is a sorting algorithm that works by partitioning an array of data items, or keys, into a number of "subarrays" (termed buckets, in similar sorts). The name is short for computing a "proximity map," which in...
9673abbad9320df5d83ebef9658c84ab21b5f021
22,075
import pathlib def load_footings_file(file: str): """Load footings generated file. :param str file: The path to the file. :return: A dict representing the respective file type. :rtype: dict .. seealso:: :obj:`footings.testing.load_footings_json_file` :obj:`footings.testing.load...
929cf95e631e8be4dcc8f18c36a0b545593fed69
22,076
def coupler(*, coupling: float = 0.5) -> SDict: """a simple coupler model""" kappa = coupling ** 0.5 tau = (1 - coupling) ** 0.5 sdict = reciprocal( { ("in0", "out0"): tau, ("in0", "out1"): 1j * kappa, ("in1", "out0"): 1j * kappa, ("in1", "out1"): ...
dfd40ce9a8c61ffe8382b461c41d4034c7342570
22,077
def new_client(request): """ Function that allows a new client to register itself. :param request: Who has made the request. :return: Response 200 with user_type, state, message and token, if everything goes smoothly. Response 400 if there is some kind of request error. Response 403 for forbidden. O...
d05eeb55527cfe355fb237751693749ed707a598
22,078
from datetime import datetime def parse_time_interval_seconds(time_str): """ Convert a given time interval (e.g. '5m') into the number of seconds in that interval :param time_str: the string to parse :returns: the number of seconds in the interval :raises ValueError: if the string could not be parsed...
6c07ee52b8dd727e96dae8a58f59c1bd043f3627
22,079
from typing import List from typing import Dict def _map_class_names_to_probabilities(probabilities: List[float]) -> Dict[str, float]: """Creates a dictionary mapping readable class names to their corresponding probabilites. Args: probabilities (List[float]): A List of the probabilities for the best ...
51096015e4c291b7d3357822ea13de3354b9b12f
22,080
import collections def order_items(records): """Orders records by ASC SHA256""" return collections.OrderedDict(sorted(records.items(), key=lambda t: t[0]))
a9117282974fcea8d0d99821ea6293df82889b30
22,081
def G2DListMutatorRealGaussianGradient(genome, **args): """ A gaussian gradient mutator for G2DList of Real Accepts the *rangemin* and *rangemax* genome parameters, both optional. The difference is that this multiplies the gene by gauss(1.0, 0.0333), allowing for a smooth gradient drift about the value. ...
52e739fe4c490064dbec5fe0b6a7443570cada0e
22,082
def convert_group_by(response, field): """ Convert to key, doc_count dictionary """ if not response.hits.hits: return [] r = response.hits.hits[0]._source.to_dict() stats = r.get(field) result = [{"key": key, "doc_count": count} for key, count in stats.items()] result_sorted = so...
888321f300d88bd6f150a4bfda9420e920bab510
22,083
def _parse_single(argv, args_array, opt_def_dict, opt_val): """Function: _parse_single Description: Processes a single-value argument in command line arguments. Modifys the args_array by adding a dictionary key and a value. NOTE: Used by the arg_parse2() to reduce the complexity ratin...
5b44a891400b545940c9be3913af9710c37df898
22,085
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}): """ task 0.5.9 comprehension whose value is the intersection of setA and setB without using the '&' operator """ return {x for x in (setA | setB) if x in setA and x in setB}
2b222d6c171e0170ace64995dd64c352f03aa99b
22,086
def d_beta(): """ Real Name: b'D BETA' Original Eqn: b'0.05' Units: b'' Limits: (None, None) Type: constant b'' """ return 0.05
32aa0e1fbf31761a36657b314a7c4bc4bf99889e
22,087
import csv def _get_data(filename): """ :param filename: name of a comma-separated data file with two columns: eccentricity and some other quantity x :return: eccentricities, x """ eccentricities = [] x = [] with open(filename) as file: r = csv.reader(file) for row...
f8c86f0f1c9bf2ee91108382cd6da6b98445bf1f
22,088
def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if len(strs) > 0: common = strs[0] for str in strs[1:]: while not str.startswith(common): common = common[:-1] return common else: return ''
a860d46df8dbaeaab90bb3bc69abb68484216b5b
22,089
def analytics_dashboard(request): """Main page for analytics related things""" template = 'analytics/analyzer/dashboard.html' return render(request, template)
068913de2f2b1a381f73395e53e2e06db7d02e8e
22,090
def insert(shape, axis=-1): """Shape -> shape with one axis inserted""" return shape[:axis] + (1,) + shape[axis:]
8c786df81b76cfa5dae78b51d16b2ee302263c53
22,091
import re def simplify_text(text): """ :param text: :return: """ no_html = re.sub('<[^<]+?>', '', str(text)) stripped = re.sub(r"[^a-zA-Z]+", "", str(no_html)) clean = stripped.lower() return clean
a867bd08a642843df9d8a2a517f1b0c13ea145b1
22,092
def is_numpy_convertable(v): """ Return whether a value is meaningfully convertable to a numpy array via 'numpy.array' """ return hasattr(v, "__array__") or hasattr(v, "__array_interface__")
163da2cf50e2172e1fc39ae8afd7c4417b02a852
22,093
def grower(array): """grows masked regions by one pixel """ grower = np.array([[0,1,0],[1,1,1],[0,1,0]]) ag = convolve2d(array , grower , mode = "same") ag = ag != 0 return ag
b6ae0c9eeb96ec13a5f9ef7a282ec428b5d536ad
22,094
def SMAPELossFlat(*args, axis=-1, floatify=True, **kwargs): """Same as `smape`, but flattens input and target. DOES not work yet """ return BaseLoss(smape, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
470e8f34cfd5fd6a867f9991e8babcad25fa03ff
22,095
from datetime import datetime def get_fake_datetime(now: datetime): """Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value.""" class FakeDatetime: """Fake datetime.datetime class.""" @classmethod def now(cls): """Return...
f268640c6459f4eb88fd9fbe72acf8c9d806d3bc
22,096
from typing import List def generate_order_by(fields: List[str], sort_orders: List[str], table_pre: str = '') -> str: """Функция генерит ORDER BY запрос для SQL Args: fields: список полей для сортировки sort_orders: список (asc\desc) значений table_pre: префикс таблицы в запросе Re...
863d348d2bd844718e056c6767e1f282405b3edf
22,097
def toUnicode(glyph, isZapfDingbats=False): """Convert glyph names to Unicode, such as 'longs_t.oldstyle' --> u'ſt' If isZapfDingbats is True, the implementation recognizes additional glyph names (as required by the AGL specification). """ # https://github.com/adobe-type-tools/agl-specification#2-the-mapping # ...
42bfee52db47f466308dfc4782a609776f6b90b9
22,098
def list_watchlist_items_command(client, args): """ Get specific watchlist item or list of watchlist items. :param client: (AzureSentinelClient) The Azure Sentinel client to work with. :param args: (dict) arguments for this command. """ # prepare the request alias = args.get('watchlist_al...
1567bd56c90e9560fcae583d8360e4299620c266
22,099
def blit_array(surface, array): """ Generates image pixels from a JNumeric array. Arguments include destination Surface and array of integer colors. JNumeric required as specified in numeric module. """ if not _initialized: _init() if len(array.shape) == 2: data = numeric.tra...
850b6451ecc780fd163f574176a8c5683174046e
22,100
def generate_IO_examples(program, N, L, V): """ Given a programs, randomly generates N IO examples. using the specified length L for the input arrays. """ input_types = program.ins input_nargs = len(input_types) # Generate N input-output pairs IO = [] for _ in range(N): input_va...
4449974cf5a1bd04a89e5575fb48362da8fa1621
22,102
def secrecy_capacity(dist, rvs=None, crvs=None, rv_mode=None, niter=None, bound_u=None): """ The rate at which X and Y can agree upon a key with Z eavesdropping, and no public communication. Parameters ---------- dist : Distribution The distribution of interest. rvs : iterable of it...
c55655847f9d9cf586bd4e274f72359d0241c349
22,104
def encrypt_message(partner, message): """ Encrypt a message :param parner: Name of partner :param message: Message as string :return: Message as numbers """ matrix = get_encryption_matrix(get_key(get_private_filename(partner))) rank = np.linalg.matrix_rank(matrix) num_blocks = ...
e8e96f99f511afb3b91a9c264f8452e45b14e165
22,105
def create_event(title, start, end, capacity, location, coach, private): """Create event and submit to database""" event = Class(title=title, start=start, end=end, capacity=capacity, location=location, coach=coach, free=capacity, private=private) db.session.add(event) db.session.commit() return even...
4a1b6314eee362f6ae7f35685cb09fe969175c0b
22,106
def regret_obs(m_list, inputs, true_ymin=0): """Immediate regret using past observations. Parameters ---------- m_list : list A list of GPy models generated by `OptimalDesign`. inputs : instance of `Inputs` The input space. true_ymin : float, optional The minimum val...
e9cc2567f9740deae7b681cc754d20a387fbc894
22,107
import numpy def pmat2cam_center(P): """ See Hartley & Zisserman (2003) p. 163 """ assert P.shape == (3, 4) determinant = numpy.linalg.det # camera center X = determinant([P[:, 1], P[:, 2], P[:, 3]]) Y = -determinant([P[:, 0], P[:, 2], P[:, 3]]) Z = determinant([P[:, 0], P[:, 1],...
f959eab9feeeafd90c3a2178b77d81e509ef1282
22,108
def _http_req(mocker): """Fixture providing HTTP Request mock.""" return mocker.Mock(spec=Request)
651866118fd25909e50469cb92f35a9aa3a6d873
22,109
def transform_data(df, steps_per_floor_): """Transform original dataset. :param df: Input DataFrame. :param steps_per_floor_: The number of steps per-floor at 43 Tanner Street. :return: Transformed DataFrame. """ df_transformed = ( df .select( col('id'), ...
163bedd83315828001f4cca2abdc130a2a77a55a
22,110
import logging def get_client(bucket): """Get the Storage Client appropriate for the bucket. Args: bucket (str): Bucket including Returns: ~Storage: Client for interacting with the cloud. """ try: protocol, bucket_name = str(bucket).lower().split('://', 1) except Valu...
46a27b4a028daa927507f3e8b0d5aeb453fd302b
22,111
def extract_text(xml_string): """Get text from the body of the given NLM XML string. Parameters ---------- xml_string : str String containing valid NLM XML. Returns ------- str Extracted plaintext. """ paragraphs = extract_paragraphs(xml_string) if paragraphs: ...
f3e80d960837d8663d9711bd9696644f00ba21e9
22,112
def search_organizations(search_term: str = None, limit: str = None): """ Looks up organizations by name & location. :param search_term: e.g. "College of Nursing" or "Chicago, IL". :param limit: The maximum number of matches you'd like returned - defaults to 10, maximum is 50. :returns: String cont...
5523f6278b4eff5618979ce942fb175b20042079
22,114
def call_math_operator(value1, value2, op, default): """Return the result of the math operation on the given values.""" if not value1: value1 = default if not value2: value2 = default if not pyd.is_number(value1): try: value1 = float(value1) except Exception...
da1a163e4079cfd885d8ca163939111c9291767b
22,115
def addGems(ID, nbGems): """ Permet d'ajouter un nombre de gems à quelqu'un. Il nous faut son ID et le nombre de gems. Si vous souhaitez en retirer mettez un nombre négatif. Si il n'y a pas assez d'argent sur le compte la fonction retourne un nombre strictement inférieur à 0. """ old_value =...
6f3778cec488138101a78a072591babb832d7f95
22,116
def BertzCT(mol, cutoff=100, dMat=None, forceDMat=1): """ A topological index meant to quantify "complexity" of molecules. Consists of a sum of two terms, one representing the complexity of the bonding, the other representing the complexity of the distribution of heteroatoms. From S. H. Bertz, J...
0ca8119db47121dc22e0554e114e51ad916af455
22,117
def BOPTools_AlgoTools_CorrectRange(*args): """ * Correct shrunk range <aSR> taking into account 3D-curve resolution and corresp. tolerances' values of <aE1>, <aE2> :param aE1: :type aE1: TopoDS_Edge & :param aE2: :type aE2: TopoDS_Edge & :param aSR: :type aSR: IntTools_Range & :param...
491b1930a017940137aa2a59c630f995f0fc8366
22,118
from typing import Tuple def approx_min_k(operand: Array, k: int, reduction_dimension: int = -1, recall_target: float = 0.95, reduction_input_size_override: int = -1, aggregate_to_topk: bool = True) -> Tuple[Array, Array]: """Retur...
e4716369b4371b27ccabaaa61d2157e513cf06ed
22,120
def sitemap_host_xml(): """Supplementary Sitemap XML for Host Pages""" database_connection.reconnect() hosts = ww_host.info.retrieve_all(database_connection) sitemap = render_template("sitemaps/hosts.xml", hosts=hosts) return Response(sitemap, mimetype="text/xml")
79b21d1465ef84c1cfaf192be0b2fa5bf07f1014
22,121
def WTC(df,N): """Within Topic Coherence Measure. [Note] It ignores a word which does not have trained word vector. Parameters ---------- df : Word-Topic distribution K by V where K is number of topics and V is number of words N : Number of top N words ...
b5b50eef85f6e12c54c9ec16a2f7264aa057d344
22,122
def extract_static_override_features( static_overrides): """Extract static feature override values. Args: static_overrides: A dataframe that contains the value for static overrides to be passed to the GAM Encoders. Returns: A mapping from feature name to location and then to the override value...
9425674eb2e0578ecbc926b249a6eb2f6afb37d0
22,123
def job_list_View(request): """ """ job_list = Job.objects.filter() paginator = Paginator(job_list, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, } return render(request, 'jobapp/job-list.html', cont...
a2928ea255ff3cb044462fc4ebf7c530bd54b2fb
22,124
import json def edit_schedule(request): """Edit automatic updates schedule""" if request.method == "POST": schedule = models.UpdateSchedule.objects.get() def fun(query): return [int(x.strip()) for x in query.split(" ") if x.strip() != ""] schedule.text = json.dumps({ ...
c87ef4ff0088bf4d67a1078ffe11b4c723272a8a
22,125
import math def infection_formula(name_model, infectious_number, classroom_volume, classroom_ach): """ Calculate infection rate of with/without a mask by selected model. """ if name_model == "wells_riley": # Use wells riley model. effect_mask = 1.0 / ((1.0 - config.EXHALATION_FILTRATION_EFFIC...
99b14a88c4ed02716626d8bc037b3f54211caa2a
22,126
def RetryWithBackoff(opts, fn, args=None, kwargs=None): """`fn` function must follow the interface suggested: * it should return tuple <status, err> where status - backoff status err - error that happend in function to propogate it to caller.""" args = args or () kwargs = kwa...
bf040a93015f3a283ac858c8738dc6bd8c48b2af
22,127
def noaa_api_formatter(raw, metrics=None, country_aggr=False): """Format the output of the NOAA API to the task-geo Data Model. Arguments: raw(pandas.DataFrame):Data to be formatted. metrics(list[str]): Optional.List of metrics requested,valid metric values are: TMIN: Minimum temper...
155b9a0cee72f85d6f5329a5a68aca4aa1dfe1eb
22,128
def crop_wav(wav, center, radius): """ Crop wav on [center - radius, center + radius + 1], and pad 0 for out of range indices. :param wav: wav :param center: crop center :param radius: crop radius :return: a slice whose length is radius*2 +1. """ left_border = center - radius right_b...
69a5a078f06b083694d5d5eb5328b63c70a6f17c
22,129
def markdown(text: str) -> str: """Helper function to escape markdown symbols""" return MD_RE.sub(r'\\\1', text)
2cb5fb3f5cac2d5cc5b6d256c4a8357832f3e53e
22,130
def import_sample(sample_name, db): """Import sample""" cur = db.cursor() cur.execute('select sample_id from sample where sample_name=?', (sample_name, )) res = cur.fetchone() if res is None: cur.execute('insert into sample (sample_name) values (?)', (sam...
c477a4f036951cac88789b59f361cf9397a0e9ee
22,131
import torch def change_background_color_balck_digit(images, old_background, new_background, new_background2=None, p=1): """ :param images: BCHW :return: """ if new_background2 is None: assert old_background == [0] if not torch.is_tensor(new_background): new_backgr...
f17f627616c75f3673d6ed043f0f36751ccde2a1
22,132
def render_sprites(sprites, scales, offsets, backgrounds, name="render_sprites"): """ Render a scene composed of sprites on top of a background. An scene is composed by scaling the sprites by `scales` and offseting them by offsets (using spatial transformers), and merging the sprites and background togethe...
c4210a3b1f123368c77d89fcf15634ead3d97c85
22,133
import ctypes def load_shared_library(dll_path, lib_dir): """ Return the loaded shared library object from the dll_path and adding `lib_dir` to the path. """ # add lib path to the front of the PATH env var update_path_environment(lib_dir) if not exists(dll_path): raise ImportError('Sh...
983b6b42b25e5f7936117579b02babff30899d21
22,134
def preprocess_img(image): """Preprocess the image to adapt it to network requirements Args: Image we want to input the network (W,H,3) numpy array Returns: Image ready to input the network (1,W,H,3) """ # BGR to RGB in_ = image[:, :, ::-1] # image centralization # They are the ...
c4a0136c03aa57a54db432e9abe8e35cbe43f0b6
22,135
def _parse_ec_record(e_rec): """ This parses an ENSDF electron capture + b+ record Parameters ---------- e_rec : re.MatchObject regular expression MatchObject Returns ------- en : float b+ endpoint energy in keV en_err : float error in b+ endpoint energy ...
00480d031a3e6b118d880ed5e2abb890e7e8b410
22,136
import datetime def skpTime(time): """ Retorna un datetime con la hora en que la unidad genero la trama. >>> time = '212753.00' >>> datetime.time(int(time[0:2]), int(time[2:4]), int(time[4:6]), int(time[-2])) datetime.time(21, 27, 53) >>> """ return datetime.time(...
8bfa7e4d7faa52152c0a63944502cd6b1975ebdf
22,137
def calc_max_moisture_set_point(bpr, tsd, t): """ (76) in ISO 52016-1:2017 Gabriel Happle, Feb. 2018 :param bpr: Building Properties :type bpr: BuildingPropertiesRow :param tsd: Time series data of building :type tsd: dict :param t: time step / hour of the year :type t: int :re...
3fe2ab28b8f0ba3e6ba2139ed168f08e1b0e969d
22,138
def compress_pub_key(pub_key: bytes) -> bytes: """Convert uncompressed to compressed public key.""" if pub_key[-1] & 1: return b"\x03" + pub_key[1:33] return b"\x02" + pub_key[1:33]
05824112c6e28c36171c956910810fc1d133c865
22,139
def is_tensor(blob): """Whether the given blob is a tensor object.""" return isinstance(blob, TensorBase)
514e9fea7b6fc60078ea46c61d25462096fa47cc
22,140
def transform_dlinput( tlist=None, make_tensor=True, flip_prob=0.5, augment_stain_sigma1=0.5, augment_stain_sigma2=0.5): """Transform input image data for a DL model. Parameters ---------- tlist: None or list. If testing mode, pass as None. flip_prob augment_stain_sigma1 aug...
9f7bacb5a27667667432d3775ae624f4fd57e2c6
22,141
def _(text): """Normalize white space.""" return ' '.join(text.strip().split())
f99f02a2fe84d3b214164e881d7891d4bfa0571d
22,142
import ipdb def mean_IOU_primitive_segment(matching, predicted_labels, labels, pred_prim, gt_prim): """ Primitive type IOU, this is calculated over the segment level. First the predicted segments are matched with ground truth segments, then IOU is calculated over these segments. :param matching ...
cf405144206e824a868f4eb777635237e8cc59b8
22,143
def _infer_title(ntbk, strip_title_header=True): """Infer a title from notebook metadata. First looks in metadata['title'] and if nothing is found, looks for whether the first line of the first cell is an H1 header. Optionally it strips this header from the notebook content. """ # First try the...
e8152f0c160d2cb7af66b1a20f4d95d4ea16c703
22,145
import hashlib def stable_hash(value): """Return a stable hash.""" return int(hashlib.md5(str(value).encode('utf-8')).hexdigest(), 16)
a5be51a971eb6c9a91489155216ef194f9d0d7ba
22,146
def minimal_community(community_owner): """Minimal community data as dict coming from the external world.""" return { "id": "comm_id", "access": { "visibility": "public", }, "metadata": { "title": "Title", "type": "topic" } }
18b99c30d4dff01b988e8ac311a6da92142e71ee
22,147
from typing import Counter def retrieve_descriptions(gene, descriptions, empties): """Given single gene name, grab possible descriptions from NCBI and prompt user to select one""" # Perform ESearch and grab list of IDs query = gene + '[Gene Name]' handle = Entrez.esearch(db='gene', term=query, ...
524d4955a51eb0e3143c06d91eb7ae611579d9dd
22,148
import time def readCmd(): """ Parses out a single character contained in '<>' i.e. '<1>' returns int(1) returns the single character as an int, or returns -1 if it fails""" recvInProgress = False timeout = time.time() + 10 while time.time() < timeout: try: rc = ser.re...
3e7b1eef27ab41b7079c966bf696e95923ebe6eb
22,149
def map_ground_truth(bounding_boxes, anchor_boxes, threshold=0.5): """ Assign a ground truth object to every anchor box as described in SSD paper :param bounding_boxes: :param anchor_boxes: :param threshold: :return: """ # overlaps shape: (bounding_boxes, anchor_boxes) overlaps = ja...
1609bac66f4132249e893996b07b1a8752b8ab48
22,150
def MakeFrame(ea, lvsize, frregs, argsize): """ Make function frame @param ea: any address belonging to the function @param lvsize: size of function local variables @param frregs: size of saved registers @param argsize: size of function arguments @return: ID of function frame or -1 ...
f0affe28d506a65d2a43fa64f2b9a99dbaf62b25
22,152