content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence def domain_concatenated_no_4gc(seq: str, seqs: Sequence[str]) -> bool: """prevent {G,C}^4 under concatenation""" for altseq in seqs: catseq = altseq + seq + altseq strength = catseq.translate(_binaryGCTable) if '1111' in strength: return False ...
9a11a67fbdddefc7b1b5b44eed8ec701f7d92a76
72,046
def delete_item(id:int, db: Session = Depends(get_db)): """This functions takes the id delete the required item """ existing_item = db.query(models.Item).filter(models.Item.id == id).delete() if not existing_item : return("Item Does Not Exist ") db.commit() return("Item del...
b63c0078794f28fef9b07c9024fed21287dfeb34
72,047
def convert_file(source_file, to, format=None, extra_args=(), encoding='utf-8', outputfile=None, filters=None, verify_format=True): """Converts given `source` from `format` to `to`. :param str source_file: file path (see encoding) :param str to: format into which the input should be conve...
2ed89f9c7cdedcffc45b7e028c9377e192eaaf12
72,048
def make_polynomial_mmd_evaluation(degree=3, theta=None): """Make a Polynomial MMD evaluation function See coresets.kernels.PolynomialKernel for a description the polynomial kernel parameters. Parameters ---------- degree : int, optional theta : float, optional Returns ------- ...
20452374dc9dbe681a9d5b256683ae4010bdf2d1
72,049
def geocode(query, limit=None): """Convenience function to query Address objects for a text string and return a subset of the queryset object values. """ qs = Address.objects.filter(address_text__search=query) resp = [] if limit: qs = qs[0:limit] for address in qs: resp.appen...
8e8fd4f771867a35808b741a2ec6378237ddbc3d
72,050
def polar(fmla,pos,pol): """ Return the polarity of the `pos` argument of `fmla` assuming the polarity of `fmla` is `pol`. The polarity indicates the number of negations under which the formula occurs. It is 0 for an even number, one for an odd number and None if the formula occurs under both an eve...
944db348e22739b598fff686803b23cfe935086f
72,052
import numpy def Mat3Vec3Mult(mat3, vec3): """Performs elementwise Mat3-Vec3 multiplication.""" return numpy.einsum('lij,lj->li', mat3['d'], Vec3ToArray(vec3))
e10d3f2eca1e1623b29f34a9269186dd0942d08c
72,053
def minutes_to_seconds(minutes:str)->int: """ Converts minutes to seconds """ return int(minutes)*60
a4aa5851749cf8081a8f49b1a1b7eb136e2bb372
72,055
def open_default_resource_manager(library): """This function returns a session to the Default Resource Manager resource. Corresponds to viOpenDefaultRM function of the VISA library. Returns ------- VISARMSession Unique logical identifier to a Default Resource Manager session constants....
ab6cb802e09d9e60fcf32ee3ab4ccb53960e2c6e
72,056
import torch def warp_from_NormMap2D(x, NormMap2D): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow """ B, C, H, W = x.size() # mesh grid vgrid = NormMap2D.permute(0, 2, 3, 1).contiguous() output = nn.functi...
d4d429b72fe1949f8d5de9bde85b841845479057
72,057
def jd_corr(jd, ra, dec, obslon=None, obslat=None, obsalt=None, jd_type='bjd'): """Return BJD_TDB or HJD_TDB for input JD_UTC BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay where: JD_to_TDB_corr is the difference between UTC...
cc4912e8f221caa595e8e08588b3ab7ee0ee8050
72,058
import time def timeit(method=None, *, wargs=False): """takes method and wraps it in a timer""" if method is None: return partial(timeit, wargs=wargs) log = LogMixin() @wraps(method) def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.t...
6a9de69bf51d5aba452ff577585760793322f0a0
72,059
def api_machine_num(val: int) -> None: """Set available number of machine/node for running job . Args: val (int): available number of machines """ return enable_if.unique([machine_num, do_nothing])(val)
b0749b41b5afd7d418d91739927fd1cf1df1b528
72,060
def common_modulus_attack(c1: int, c2: int, e1: int, e2: int, n: int) -> int: """ This functionw will carry out the common modulus attack. :param c1: Ciphertext integer 1. :param c2: Ciphertext integer 2. :param e1: encryption exponent 1. :param e2: encryption exponent 2. :param n: The modulus n. :return: The ...
cc3f94a99638c8519ea2a39446451269c82b15ac
72,061
def fragmentation_heuristic(board): """Estimates how fragmented the board is. This works because we'd get the same total cost if we would remove each zone individually. """ zones = get_zones(board) num_zones = len(zones) if num_zones == 0: return 0 color_counts = defaultdict(i...
02ac9e770423d9f6179201479c71a3de40500812
72,062
import math def normal_approximation_to_binomial(n, p): """finds mu and sigma corresponding to a Binomial(n, p)""" mu = p * n sigma = math.sqrt(p * (1 - p) * n) return mu, sigma
6c25d1009df6f15fa413ab561af2e58ba831cfab
72,063
def read_data(filename, sep=",", aFilter=int): """ Data format(ith line): label_i,x_i1,x_i2,...x_id """ def split_line(line): return line.split(sep) def process_line(line): return map(aFilter, split_line(line)) with open(filename) as f: lines = map(process_l...
40a4c1fda3bce6e70acef0b72971b99dd4507b9a
72,064
def get_vision_sensor_image(): """ Purpose: --- This function should first get the handle of the Vision Sensor object from the scene. After that it should get the Vision Sensor's image array from the CoppeliaSim scene. Input Arguments: --- None Returns: --- `vision_sensor_image` : [ list ] the imag...
ac6470c0f7d4f4f8226060f99e110fbf8b16a0bf
72,065
def get_presets(global_presets, groups): """Returns a dictionary of presets merged with the referenced preset Presets define a direct acyclic graph by including the `preset` property, so this function validates that there are no cycles and that all referenced presets are defined. In the output, pres...
068c639f16c8711da7ef7ccd1bd7e34fdb018153
72,066
import io async def import_books_csv(file: UploadFile = File(...)): """import `Book`s from csv file""" session = Session() df: pd.DataFrame = pd.read_csv( io.StringIO(UnicodeDammit(file.file.read()).unicode_markup) ).replace({np.nan: None}) logger.info(f"shape: {df.shape}") df = df[ ...
b4de9cda2b14e77477e2d94d26dde511aa781e81
72,067
def string_array(array): """ Make a numpy array a space separated string """ return " ".join(map(str, array))
beaa9b8e8911454409be2c4e255b919f9e379635
72,068
def get_docs(log, yaml_editor, yaml_file): """Get all documents from a YAML/JSON/Compatible file.""" docs_loaded = True docs = [] if yaml_file != "-" and not isfile(yaml_file): log.error("File not found: {}".format(yaml_file)) return ([], False) for (yaml_data, doc_loaded) in Parse...
3b82236e850660803da4e66742ff726a07e14ca1
72,069
from typing import List from typing import OrderedDict def _analyze_class(ctx: 'mypy.plugin.ClassDefContext', auto_attribs: bool, kw_only: bool) -> List[Attribute]: """Analyze the class body of an attr maker, its parents, and return the Attributes found. auto_attribs=Tru...
ae5085cf883e3ecbbb6a9e32e596b23602364724
72,071
def get_player_colour(player): """ Decide the colour of a plot element based on the freeze-frame player's team and position. """ if player['teammate']: return 'pink' if not player['teammate'] and not is_gk(player): return 'skyblue' if is_gk(player): return 'green'
b7ba5d9fce7c8acd8a5cb352381fd68b5889134f
72,072
def _dict2df(to_plot_dict:dict, meta_key:str) -> pd.DataFrame: """Transform a dictionary into a DataFrame for catplotting""" to_plot_df = [] for range, values in to_plot_dict.items(): range_grouped = [] for ds in values: values_ds = values[ds].to_frame(name="values") ...
562f9bbe1c8c021b484b6b553dacbdb2d7218611
72,073
def orthonormalize_axes(xaxis, yaxis): """Corrects xaxis and yaxis to be unit vectors and orthonormal. Parameters ---------- xaxis: [float, float, float] | :class:`~compas.geometry.Vector` The first axis. yaxis: [float, float, float] | :class:`~compas.geometry.Vector` The second axi...
717c4feb940d59874c9880f735c09d929407a074
72,074
def _binary_expression( value, to_camel_case, serial_field_relations, level_limits, bidirectional ): """ _binary_expression it is probably a relationship NOTE: Not used here, but prop.entity.all_orm_descriptors is access to related column """ if hasattr(value, "prop"): ...
04718f295e4796914c0550e17abf8f8926978bb8
72,075
def electron_binding_energy(charge_number): """Return the electron binding energy for a given number of protons (unit is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C., 2003, Rev. Mod. Phys.,75, 1021].""" return 1.44381e-5 * charge_number ** 2.39\ + 1.55468e-12 * char...
6d5a845b1b11720b44b62500f979f0a621faca0a
72,076
def policy_gradient(*, policies, actions, action_values): """ https://github.com/deepmind/trfl/blob/master/docs/trfl.md#policy_gradientpolicies-actions-action_values-policy_varsnone-namepolicy_gradient """ actions = jax.lax.stop_gradient(actions) action_values = jax.lax.stop_gradient(action_values) ...
6903e8be60f89e722ead6fdb4e6fe139b2054eb3
72,078
from .base import Kit def Celery(module_name, path=None): """Returns the Celery application registered for the module. :param module_name: the module name for which to get the application. Typically, this should always be set to ``__name__``. :type module_name: str :param path: the path to the overall ki...
c47dd9c86f59b48ce3f5c2e68c926149c4cfbca2
72,079
def grid1d(dist: float, L: int, parms: list[float] = None) -> np.ndarray: """ generate 1D grid Parameters ---------- dist: float one-way distance from origin (meters) L: int number of cells Returns ------- x: np.ndarray 1D vector grid """ xmin = -...
75c3f9cf12f8cab30a7a06363f7273f0bd6746d1
72,081
import math import numpy def rquaternionu(u, theta): """Returns a quaternion representing the right handed rotation of theta radians about vector u. Quaternions are typed as Numeric Python numpy.arrays of length 4. """ u = normalize(u) half_sin_theta = math.sin(theta / 2.0) x = u[0] * ha...
b8e852378d98b51e156d4a4889bec68bb858c410
72,084
def ctsim_drsa_cal(Model_RDMs, RDMs, method='spearman'): """ Calculate the Cross-Temporal Similarities between temporal model RDMs and temporal neural RDMs (dynamic-RSA) Parameters ---------- Model_RDMs : array The Coding Model RDMs. The shape should be [n_ts, n_cons, n_cons]. n_ts...
136a72910d9ed7a737e6fe9f92496319977f50d9
72,085
def madmom_1(filename, reference_beats_filename): """ Estimates beats using reference beats and the `DBNBarTrackingProcessor` provided with madmom: S. Bock, F. Korzeniowski, J. Schlüter, F. Krebs, and G. Widmer, “Madmom: A new Python Audio and Music Signal Processing Library,” in P...
41fc14d19fed3f7416a30219e4c26d6f1437471a
72,086
import requests import html def login(username: str, password: str) -> TransperthSession: """ :returns: a session object with login cookies attached """ logger.info('Authenticating...') s = requests.Session() r = _login(s, username, password) doc = html.document_fromstring(r.text) m...
0e7a419eec4dca86465bbc3618cd731ea0b4a4e6
72,087
import re def urlencode_paths(path): """Urlencode some paths before forwarding requests.""" for rule_regex in SPECIAL_ROUTE_REGEXES: m = re.search(rule_regex, path) if m: return '{leading}{before}{match}{after}{trailing}'.format( leading=m.group(1), ...
c6aa0dbffe4ea69fd017fcadfe61f3b07e1be2fa
72,088
def executedf(): """ Executes df command Returns: lOutput = [ { sName :'partition1', iBlocksTotal :1234, iBlocksUsed :1000 iBlocksAvailable:234 iPercent :90 sMountpoint...
13fef095a7104c1d3ab94c2a1cb6c005e1b9f897
72,090
def recall(y_true,y_pred): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred,0,1))) possible_positives = K.sum(K.round(K.clip(y_true,0,1)...
84fe5f3a68cc1df0bdc956813442068245e6879c
72,091
def pad_image(img, size, smooth=None): """ Pads image to new_length x new_length and pads with black. Only works with grayscale right now. Arguments: - smooth (float/None) : sigma value for Gaussian smoothing """ if np.max(img.shape) > size: resize_factor = float(size) / np.max(im...
7cf850e7ed76e17637ffa92c7e32b18297596d12
72,092
def L(x, gamma): """Return Lorentzian line shape at x with HWHM gamma""" return gamma / np.pi / (x**2 + gamma**2)
cbae0d5f37ae24e3ab22900f6433806e3faa7110
72,093
import warnings import torch def load_from_openmmlab(filename, map_location=None): """load checkpoint through the file path prefixed with open-mmlab or openmmlab. Args: filename (str): checkpoint file path with open-mmlab or openmmlab prefix map_location (str, optional): Same as :...
02b079ebf2c4cb0f18f700ae098d3c9e80cc7d3a
72,095
def __dict_to_pod_spec(spec): """ Converts a dictionary into kubernetes V1PodSpec instance. """ spec_obj = kubernetes.client.V1PodSpec() for key, value in iteritems(spec): if hasattr(spec_obj, key): setattr(spec_obj, key, value) return spec_obj
0e84fb28217c35f9897fc33ccdbdadee1800e100
72,096
def pca(X,Y,k): """Count accuracy of PCA method Parameters ---------- X : array A 2-d array with the entropy and godel numbering Y : array The value of the class k: int K-mer value Returns ------- The accuracy of the pca method in RandomForestClassifier. """ # te...
547fe123e579badad8e63d798b7f0c4bfdf1b191
72,097
def gumbel_softmax_sample(logits, tau=1, eps=1e-10): """ NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3 Draw a sample from the Gumbel-Softmax distribution based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca7...
2d17c4e14153d98074266cb1007ec5889fff5a29
72,098
def cross3(left, right): """Numpy is inefficient for this Args: left (3x0 array): left term of the cross product right (3x0 array): right term of the cross product """ return np.array([[left[1] * right[2] - left[2] * right[1]], [left[2] * right[0] - left[0] * right[...
a77e1d719c07722537f10a5232c9bf8282ac0c6b
72,099
def parse_generic(data, key): """ Returns a list of (potentially disabled) choices from a dictionary. """ choices = [] for k, v in sorted(data[key].iteritems(), key=lambda item: item[1]): choices.append([v, k]) return choices
90d2f2188d5cca7adb53eebca80a80f2c46b04a7
72,100
def get_ct_solution_array(mechanism, library): """Obtain a Cantera SolutionArray object representative of an arbitrary library Parameters ---------- mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance the mechanism library: a spitfire.chemistry.library...
950b2c88c031ad26534dda21ba7c965601892d0e
72,101
def read_layer(path, layer=0, index=None): """Create a vector layer from the specified path. Will try to read using ogr.OpenShared. Parameters ---------- path_or_str: string path or json string layer: integer The layer number to use. Use ogrinfo to see the available la...
f42903a780a4d37a9aaa9e0d3e1fe4a57a3e7272
72,103
import copy def abut (source,*args): """ Like the |Stat abut command. It concatenates two lists side-by-side and returns the result. '2D' lists are also accomodated for either argument (source or addon). CAUTION: If one list is shorter, it will be repeated until it is as long as the longest list. If this beh...
f8a2329b1f70e1483a2975244bb237ff3a02d437
72,104
def template(*args, **kwargs): """template function that injects context into each call""" rendered = jinja2_template( *args, **kwargs | dict( queries=appState.queries, errors=appState.errors, path=request.path, logged_in=appState.logged_in...
96cb7da93b51d71c3ef6c82893f2baf818ac0937
72,105
def log_format_info(event_str, data = {}): """ log_format_info is a helper function. It will format an info message with support for event data. event_str A string describing the event data A dictionary with info returns string to pass to logger.info() Example: try: ... except Exception as e: log...
cc1c7dee4d566e95bb7f966943b4bfdb180c9ff2
72,106
def tag_pos(sentences: list) -> list: """Tag parts of speech of tokens in each sentence. Args: sentences (list): List of word tokenized sentences. Returns: list: List of part-of-speech tagged sentences. """ return [nltk.pos_tag(sentence) for sentence in sentences]
20ffddf8c840460e2b184c613e096209e3aa39a7
72,107
def attrs_to_dict(attrs): """ Convert a list of tuples of (name, value) attributes to a single dict of attributes [name] -> value :param attrs: List of attribute tuples :return: Dict of attributes """ out = {} for attr in attrs: if out.get(attr[0]) is None: out[attr[0...
ccf9440d29de2f8556e694f4ab87e95f0bfd9e8a
72,109
import re def sub(table, field, pattern, repl, count=0, flags=0): """ Convenience function to convert values under the given field using a regular expression substitution. See also :func:`re.sub`. .. versionadded:: 0.5 .. versionchanged:: 0.10 Renamed 'resub' to 'sub'. """...
3246d45c2eac67bb9af8c3fc5281b135030f202d
72,110
from typing import Dict from typing import Any from typing import Type from re import T def get_instance(config: Dict[str, Any], target_class: Type[T]) -> T: """Constructs an instance of type target_class from config.yml dict structure. E.g. {class: path.to.module.MyClass, constructor: {arg1: <arg1>}} ...
9e7de1a80ed230a72229b31d2435e084df6cdc52
72,113
def count(i): """List or text. Returns the length as an integer.""" return len(i)
d8daf7cd325ce1acfb382723759ff190becd785f
72,114
import yaml def GenerateConfig(context): """Entry function to generate the DM config.""" content = { 'resources': [ _RuntimeConfig(context), _Waiter(context), ], 'outputs': [ { 'name': 'config-url', 'value': _ConfigUrl(context) ...
2aad00d49d9d657d79b1d9806e61f8559c1b530e
72,115
def estimate_psd(t, k, n_zero=2_000, db=False): """Estimate the PSD from samples of the kernel. Args: t (vector): Time points of the kernel, which should be a linear space starting from the origin. k (vector): Kernel. n_zero (int, optional): Zero padding. Defaults to `2_000`...
77360454125c729cf894d4927a38cd7aeb764622
72,116
def approve(owner, spender, tokenId, amount): """ approve amount of the tokenId token to toAcct address, it can overwrite older approved amount :param owner: :param spender: :param tokenId: :param amount: :return: """ res = int(owner) RequireWitness(owner) RequireScriptHash(o...
9a6bd562b3d6ceb3648ebe3a78a86ef916abcbf8
72,117
def determine_fit_quality_mvm_interface(imglist, filtered_table, catalogs_remaining, ref_catalog_length, align_pars, print_fit_parameters=True, loglevel=logutil.logging.NOTSET): """Simple interface to allow MVM code to use determine_fit_quality(). Parameters --------...
d6b17fae04853731f341c4feb208e33e4fc812f5
72,118
from datetime import datetime def started_streaming(before: discord.Member, after: discord.Member): """ Return True if the member just started streaming, and did not do so recently. """ # The member is not streaming at the moment if after.game is None or not after.game.type == 1: return False ...
905d40512bbe48ea29c41dbc7b99749af5617ad7
72,120
def score(hand): """ Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. hand: full yahtzee hand Returns an integer score """ possible_scores = [] #Add each possible score to the list of possible scores for num in list(hand): ...
da6ff8c5a0c640034ae063bc08a54351f4dd259e
72,122
from functools import reduce def lLog( A ): """Calculate the log of A: log(A)""" if type(A) is list: Ainv = lInvert( A ) Ap = [ lScalMult(Fraction(1, n), reduce( lSum, ( lScalMult( k, lConvolute( A[k], Ainv[n-k] ) ) for k in range(1,n+1) ) ) ) for n in range(1,len(A)) ] return [lLog(A...
cf4792da0df7bab331d56a603cc00553fe665d59
72,123
import math def fibonacci_sphere(samples=1): """Implementation from as https://stackoverflow.com/questions/9600801/evenly-distributing-n-points-on-a-sphere""" points = [] phi = math.pi * (3. - math.sqrt(5.)) # golden angle in radians for i in range(samples): y = 1 - (i / float(samples - 1)) ...
31a438be2b0c737cde8542369c777c600690a118
72,124
def ml(request): """A pytest fixture to provide access to the underlying coverage object.""" # Check with hasplugin to avoid getplugin exception in older pytest. if request.config.pluginmanager.hasplugin('_test_ml'): plugin = request.config.pluginmanager.getplugin('_test_ml') if plugin.cov_...
f4625b642347e5c331a5850b7877bee1429565f7
72,125
def load_doc_topics(input_file, doc_topic_file, threshold=0.01): """Load topics in each document""" articles = [] with open(doc_topic_file) as tfin: for data in utils.read_json_list(input_file): topic_line = tfin.readline() if not topic_line: break ...
90668191c8aaa0791a17a33687db53362c7970cf
72,126
from typing import Union import pathlib from typing import IO from typing import Any from typing import Dict from typing import Callable from typing import Optional import io def from_yaml( yaml_str: Union[str, pathlib.Path, IO[Any]], routing_strategy: Dict[str, Callable] = routing_strategy_factories, lab...
937cedae6c57dafc2629b6aaab7ffe1cf5b62995
72,128
def wehrli(smooth=True, unit=u.Unit('W/(m2 um)')): """Wehrli (1985) solar spectrum (at 1 AU). Parameters ---------- smooth : bool, optional Set to `True` to smooth the solar spectrum (see Notes). unit : astropy Unit Return flux in these units (must be spectral flux density). Return...
6c6f446a0e0e567cdb1e61914b4551bff8be62b1
72,129
def load_frm_bag(filename): """Loads specific topics from rosbag and stores data as np.arrays Parameters ---------- filename : string, required Name of .bag file Outputs ---------- """ bag = rosbag.Bag(filename) outbag = rosbag.Bag(filename+'_new','w') # topic_name =...
ae8e7b4af6cd2e8dd1125560e5de8549059ebc96
72,130
import math def PlateStiffener (b, t, hw, tw, bf, tf, L, fyp, fyw = 0, fyf = 0, E = 210000): """ """ # plate (flange) section _b = b _t = t # web section _hw = hw _tw = tw # flange section _bf = bf _tf = tf # Fy plate _Fyp = fyp # Fy web if fyw == 0: _Fyw = _Fyp...
13321a27dd3580f99b0128daa859acfeb5dad5d7
72,131
def find_body(view): """ Find first package body declaration. """ return view.find(r'(?im)create\s+(or\s+replace\s+)?package\s+body\s+', 0)
b592199e4ef09d079645fc82ade8efbe3c92a895
72,132
def _get_files_project(sample, upload_config): """Retrieve output files associated with an entire analysis project. """ out = [{"path": sample["provenance"]["programs"]}] if sample["summary"].get("project"): out.append({"path": sample["summary"]["project"]}) for x in sample.get("variants", [...
04d973a90372343fd43da4cc180ba861fde62125
72,133
from bs4 import BeautifulSoup def add_currency_card(soup: BeautifulSoup, conversion_details: dict) -> BeautifulSoup: """Adds the currency conversion boxes to response of the search query Args: soup: Parsed search result conversion_details: Dictionary of currency ...
7fa7962288cbe7113f3d786c5a8ff6f5211e2ad0
72,134
def _should_send_own_updates(self): """Get whether a user wants to receive emails about their activity. This is patched into the user object to make it easier to deal with missing Profile objects. """ try: return self.get_profile().should_send_own_updates except Profile.DoesNotExist: ...
9825fdffc6f20165b687b7f4fe4dc2be8d24a0dc
72,135
def get_glibc_version(): # type: () -> Optional[Tuple[int, int]] """Based on PEP 513/600""" import ctypes # pylint: disable=bad-option-value,import-outside-toplevel try: process_namespace = ctypes.CDLL(None) gnu_get_libc_version = process_namespace.gnu_get_libc_version except (Attr...
02a950909a308bc811529588e1ca2cd72e0ff6f3
72,136
def generate_family_filenames(name, styles): """Name is the family name portion of a Noto filename. Styles is the encoding of the styles, see _get_stylenames.""" stylenames = _get_stylenames(styles) return [name + "-" + s + ".ttf" for s in stylenames]
cce985c0a1696d534c1276d1bdd25ffd1e232c41
72,137
def type_accept(*type_args, **type_kwargs): """Decorator to check function/method input types. Based on Python Cookbook 3rd ed. #9.7.""" def decorate(func): # Map function argument names to supplied types sig = signature(func) bound_types = sig.bind_partial(*type_args, **type_kwargs).ar...
d37134e3f150ebf7d2c99c3980e17f2c30c09a33
72,138
def geonet_diffusion(demArray, diffusionMethod, nFilterIterations, edgeThreshold, diffusionTimeIncrement, diffusionSigmaSquared, pixelSize): """ References: Based on diffusion() by Guy Gilboa Code imported from GeoNet2.1 by Harish Sangireddy June 2014 ...
5f35cc6252e9187d3b9ae794ab4a5d941e34d003
72,139
def hid_logout(): """ Flask controller: kill the user's login session with Humanitarian.ID GET parameters: from - the URL of the page from which we were redirected """ path = flask.request.args.get('from', '/') # original path where user choose to log out flask.session.clear() # clear the logi...
097dfae9077feafdc013d60a3418d68c3ed152d0
72,141
def grabCut(image, labels, use_tresholds=True, thresholds=(0.2, 0.6, 0.8), iterations=2, clean=False): """Use the predicted mask and OpenCV's GrabCut algorithm to mask an image. Parameters ---------- image : numpy.ndarray input image to mask labels : numpy.ndarray labels for backgro...
f9c56aa906617d28435c0c4157926fd9f025c1d9
72,142
from typing import List def get_resolutions() -> List[str]: """ Get available resolutions for DWD CDC Climate Data. If `resolution_name` is None, all resolutions are returned. :param str resolution_name: A string describing the resolution, either "hourly" or "10_minutes" :returns: A list of res...
99d1de6c2205d247b86b25c155b153c37b034a82
72,143
def renormalize(a: tp.MaybeArray[float], from_range: tp.Tuple[float, float], to_range: tp.Tuple[float, float]) -> tp.MaybeArray[float]: """Renormalize `a` from one range to another.""" delta1 = from_range[1] - from_range[0] delta2 = to_range[1] - to_range[0] return (delta2 * (a - from_ra...
1003f031fed6a9adbe48327760ee64fdc31b2a37
72,144
def jdn_to_rjd(jdn: int) -> int: """Return Reduced Julian Day (RJD) number from Julian day number (JDN). Args: jdn: Julian day number (JDN). """ return jdn - 2400000
73ffa9a6b56dfa6e543ebe581256428859311d8e
72,145
import time def bruteforceGeocoding(dict_address: dict, apiKey: str, waitTime: int): """ Geocoder trying the Bing API given the address Args: dict_address (dict): dictionary with the address to locate. apiKey (str): Bing API key. waitTime (int): Time to wait between a call and the...
ca53820e12138d3d575cd296ebede1b6227056a5
72,146
import math def roll(entropy, n): """From 0 to n - 1.""" # Minimum bit depth to cover the full range. # Note that more bits would be more fair. bit_depth = math.ceil(math.log2(n)) x = entropy(bit_depth) # Scale from total range to desired range. # Numbers with higher odds will be evenly...
a714b1636cd6a97fb4d4ccc19e966795cadec76c
72,147
def get_parsed_trigger_file( trigger_file, s3_key, expected_keys=[], legacy_keys=[] ): """Check that trigger file has the correct keys, add default values, and potentially fall back to a legacy format if the first set of keys are not present""" if all(key in trigger_file for key in expected_keys): ...
a637679d697984a0cf2ab3816dd88acd49c74d44
72,148
def minibatch_iterator(minibatch_size = 1, epochs = 1, final_treatment = 'stop', single_channel = False): """ :param minibatch_size: :param epochs: :param final_treatment: :param single_channel: :return: A function that, when called with a Data Collection, returns an iterator. """ def i...
f834743617bf44b9e07dbe4e3638f85db610505d
72,150
def create_ipv6_network(config_id, pool_cidr, pool_name): """create ipv6 network under configuration""" parent = get_parent(config_id, pool_cidr) parent_id = config_id if parent is not None: parent_id = parent['id'] return g.user.get_api()._api_client.service.addIP6NetworkByPrefix(parent_id,...
4f42a8ac5bb6384908c9457288cf579bcd27f0a8
72,151
import random def gen_sample_data(n_sample=300): """ Generate sample data """ survey_data = [] for _ in tqdm_notebook(range(n_sample)): district = random.choice(possible_district) age = random.choice(possible_age) sex = random.choice(possible_sex) increase_list = ra...
40fc92b1f64bbe8f9a84c98b80b9a6318c0d254f
72,152
def yaml_ssm_constructor(loader, node): """ Implements the yaml tag !SSM The tag takes the same arguments as SSM's GetParameter call: http://boto3.readthedocs.io/en/latest/reference/services/ssm.html#SSM.Client.get_parameter http://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParamete...
af977c6f68e2a99ad1d49424ad059bc09b21fa29
72,153
def check_pair_numpy_param(inputs_name, inputs, labels_name, labels): """ Dimension-equivalence check for `inputs` and `labels`. Args: inputs_name (str): Name of inputs. inputs (Union[list, tuple, numpy.ndarray]): Inputs. labels_name (str): Name of labels. labels (Union[list...
91e4f1b2388b6b54464ddf4994067e574836a6be
72,154
import json def page_json(): """Return a Page JSON.""" page_str = json.dumps( { "name": "RVXXX1-AutoForward", "capture_credentials": True, "capture_passwords": False, "redirect_url": "redirect.domain", "html": AUTO_FORWARD, } ) ...
aa220982c1c31e89f200817c6827435f4ee972c1
72,155
def index(request): """the homepage for learning log""" return render(request, 'learning_logs/index.html')
5d52e42a7d108f2085d64018e2114c4208ad13eb
72,156
import re def validate_search_service_engine_version(engine_version): """ Validate Engine Version for OpenSearchServiceDomain. The value must be in the format OpenSearch_X.Y or Elasticsearch_X.Y Property: Domain.EngineVersion """ engine_version_check = re.compile(r"^(OpenSearch_|Elasticsearch...
4fd725b20578047afb1751da646381003289e9c4
72,157
import random def generateDrops(imagePath, cfg, inputLabel = None): """ This function generate the drop with random position """ maxDrop = cfg["maxDrops"] minDrop = cfg["minDrops"] drop_num = randint(minDrop, maxDrop) maxR = cfg["maxR"] minR = cfg["minR"] ifReturnLabel = cfg["return_label"] edge_ratio = c...
239aa2905ad1f6067b95065d2ac7b17cfb87998c
72,161
import torch def make_algebra_matrix(tau, mode): """ Generates the matrix on the Lie algebra of the transformation group for vector tau Input: :Tensor tau: parameter vector :String mode: transformation set Output: :array B: 3x3 matrix on the Lie algebra of mode """ tau.squeeze_()...
92080c5955a4127ff25d7afd5f7623df46f21831
72,162
def get_num_objects(tree): """ Get number of objects in an image. Args: tree: Tree element of xml file. Returns: Number of objects. """ num_obj = 0 for e in tree.iter(): if e.tag == 'object': num_obj = num_obj + 1 return num_obj
92f937cbbf2eabdc909ef6bc1f06ccb87e0148b7
72,163
import math def generate_gate_piover8_daggered_hamiltonian_vec() -> np.ndarray: """Return the vector representation for the Hamiltonian of a pi/8 daggered (T^dagger) gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element. The result is a real vector...
00f5a1c5431c6fa51da048cc6cc9c0850dc58ff0
72,164
def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs): """ A wrapper for twisted.internet.threads.deferToThreadpool, which handles logcontexts correctly. Calls the function `f` using a thread from the given threadpool and returns the result as a Deferred. Creates a new logcontext fo...
4f0c834cfcf79aff76de99aa8f96270e6c27eb5c
72,165
def global_admin_css(): """Add /static/css/custom.css to the admin.""" return format_html( '<link rel="stylesheet" href="{}">', static("css/wagtail-overrides.css") )
020ca665768aa6eb6d87e02070ed44e4021cb40e
72,166