content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def diff_kerning(font_before, font_after, thresh=2, scale_upms=True): """Find kerning differences between two fonts. Class kerns are flattened and then tested for differences. Rows are matched by the left and right glyph keys. Some fonts use a kern table instead of gpos kerns, test these if no gp...
156b60e132da47e5f25dda68bdd8cb969adaba34
49,700
def str_tspec(tspec, arg_names): """ Turn a single tspec into human readable form""" # an all "False" will convert to an empty string unless we do the following # where we create an all False tuple of the appropriate length if tspec==tuple([False]*len(arg_names)): return "(nothing)" return "...
eaba40d79561d8f8cdb2c0a3a29dffd62f256217
49,701
def get_option(prompt: str, options: list[str] = MENU_OPTIONS) -> int: """Gets an option from the user and ensures it's valid.""" while True: option: int = int(input(prompt)) if option > 0 and option <= len(options): return option else: raise ValueError('Not a val...
211041c437330eab3f50b3bfcb4cfd4881fcd81a
49,702
from datetime import datetime def form_DateDifferentEmpty(request): """ A simple date field but with the ``empty`` attribute value set to todays date """ schema = schemaish.Structure() schema.add('myDateField', schemaish.Date()) form = formish.Form(schema, 'form') form['myDateField'].widge...
145e6f48b3a490edc21e39f0ce9fd473957f1f03
49,703
def render_toolbar(context, config): """Render the toolbar for the given config.""" quill_config = getattr(quill_app, config) t = template.loader.get_template(quill_config['toolbar_template']) return t.render(context)
50bce69f078b7a787b009383d055cb638af3c5c9
49,704
def get_commit_timestamps(commits): """Get all commit timestamps for the given ebuild. Args: commits (list[Commit]): The commits in question. Returns: list[int]: The uprev commit unix timestamps, in order. """ return [int(commit.timestamp) for commit in commits]
72694219664d0d6cf83d793e9ccce2b0642ec89f
49,705
def mask_tokens_after_eos(input_ids, input_masks, eos_token_id=VatexDataset.EOS, pad_token_id=VatexDataset.PAD): """replace values after `[EOS]` with `[PAD]`, used to compute memory for next sentence generation""" for row_idx in range(len(input_ids)): # possibly more than o...
589b13c266836ca2641f2d796ace1dd8ba001212
49,706
def xywh_to_xyxy(xywh): """Convert [x1 y1 w h] box format to [x1 y1 x2 y2] format.""" if isinstance(xywh, (list, tuple)): # Single box given as a list of coordinates assert len(xywh) == 4 x1, y1 = xywh[0], xywh[1] x2 = x1 + np.maximum(0.0, xywh[2] - 1.0) y2 = y1 + np.maxi...
2d6469d309c92354f33cd196be2d24967bf9d966
49,707
from pathlib import Path from typing import List import ast import re def get_entry_point(filename: Path, prefix: str, import_path: str) -> List[str]: """Returns the entry point string for a given path. This looks for LIBTBX_SET_DISPATCHER_NAME, and a root function named 'run'. It can return multiple res...
02031fe25f58f8aed009c407349cfbfb7002c63f
49,708
def DataUsed_TypeInfo(): """DataUsed_TypeInfo() -> RTTI""" return _DataModel.DataUsed_TypeInfo()
b8468185277d98d5190b1d0b697f3471d69764af
49,709
def get_min(filename): """ Isolate the minimum search size from a file name. Example input: github_notebooks_200..203_p3.json output: 200 """ return int(filename.split("_")[2].split("..")[0])
defc634a9b41ec2c6a4c821014e3c34119c3ea24
49,710
def scatter_complex(series: pd.Series) -> str: """Scatter plot (or hexbin plot) from a series of complex values Examples: >>> complex_series = pd.Series([complex(1, 3), complex(3, 1)]) >>> scatter_complex(complex_series) Args: series: the Series Returns: A string conta...
75026a609fe1656a80a95115a5caa491ded1fcca
49,711
from typing import Mapping def get_operations(managed_portfolio: portfolio.Portfolio ) -> Mapping[Text, operation.Operation]: """Gets all the position of all assets in the portfolio. Args: managed_portfolio: Portfolio from which to obtain operations. Returns: Map of portfolio operat...
28c5fa37482b70aa51ba571f4cbf27286181a7fe
49,712
def commonprefix(m): """Given a list of pathnames, returns the longest common leading component without trailing /""" if not m: return "" m = [p.rstrip("/").split("/") for p in m] s1 = min(m) s2 = max(m) s = s1 for i, (c1, c2) in enumerate(zip(s1, s2)): if c1 != c2: ...
4d0bb25fd1eb1dbcd4ee28f67b61574751b6e091
49,713
def edgecolor_by_source(G, node_colors): """ Returns a list of colors to set as edge colors based on the source node for each edge. Parameters ---------- G : graph. A networkx graph. node_colors : list List of node colors. Example -------- >>> colormap = {'male':...
961205e100cf208f5471c08afdd8b3c7328713c0
49,714
def get_random_colors(n, name="hsv", hex_format=True): """Returns a function that maps each index in 0, 1, ..., n-1 to a distinct RGB color; the keyword argument name must be a standard mpl colormap name.""" cmap = plt.cm.get_cmap(name, n) result = [] for i in range(n): color = cmap(i) ...
c077e0e143c539766907c961b3246a9fc9ae6ab0
49,715
def fdwDdz(k,t,a): """Function for calculating :math:`\\frac{dt}{dz}` in order to calculate the electric field in x and y direction. """ return fdwDdt(k,t)*fdtDdz(a)
eac9405be9e9cf2a44076479b4e1be129b9e39c0
49,716
import json import base64 def _load_credentials_file(credentials_file): """Load credentials from the given file handle. The file is expected to be in this format: { "file_version": 2, "credentials": { "key": "base64 encoded json representation of credentials."...
e01c47db0d1849a70d9623a9a5c4c33c40584d42
49,717
def __CallStoredProcedure(self, sProcedureName, pArguments): """Calls the given SQL stored procedure""" pRows = None error_string = "" locked_state = False try: # Acquire the database lock self.database_lock.Acquire(10) locked_state = True # Acquire the cursor and in...
da2cdf71254b38c687b1c3cb0a1771e85ec44341
49,718
from telegram import Message from telegram import Update def effective_message_type(entity): """ Extracts the type of message as a string identifier from a :class:`telegram.Message` or a :class:`telegram.Update`. Args: entity (:obj:`Update` | :obj:`Message`) The ``update`` or ``message`` to e...
5ed152cc88900d1d6167b9cf28637f29099189fc
49,719
from datetime import datetime def create_post(i): """ Helper to create one remote post. :param i: :return: """ i = i.get('posts')[0] post = Post() post.id = i.get('id') post.author = create_author(i.get('author')) post.contentType = i.get('contentType') post.description = ...
c0ff9d105ad7a4ebc78c2c10a29eca7cfd2fcedb
49,720
import os def parse_internal_field(fn): """ parse internal field, extract data to numpy.array :param fn: file name :return: numpy array of internal field """ if not os.path.exists(fn): print("Can not open file " + fn) return None with open(fn, "rb") as f: content = ...
1c7b99a252e631517327e9d84debf5ae0e3df2da
49,721
import pathlib def get_valid_executable_path_or_empty_path(arg_string: str) -> pathlib.Path: """ >>> if lib_detect_testenv.is_doctest_active(): assert get_valid_executable_path_or_empty_path(__main__.__file__) == empty_path >>> assert get_valid_executable_path_or_empty_path(__file__) == pathlib.Path(__fil...
9134817cf8e191855f416208bfe329e2a0b66201
49,722
def _ignore_filter(referrers, ignore, extraids, getid=id): """ Ignore objects on the referrers list if ignore(x) is true or if x is in extra """ r = [] for ref in referrers: if ignore is not None: extraids.update(set([getid(o) for o in ignore(ref)])) if getid(ref) in extraids: c...
e13a28ba1610de9d6bc835a03cf02a0f6752f7b2
49,723
def request_fake(): """Create request with fake i18n subscribers on.""" config = testing.setUp() config.scan("pyramid_localize.subscribers.fake") request = Request({}) request.registry = config.registry return request
6f6cd5e6388b6ab5d495fabd2d7da0e13f91a4be
49,724
def read_settings(key=None): """ Read application settings. Parameters ---------- key : str, optional Setting key to read, by default `None`. Returns ------- str | dict If `key` is given, the corresponding value. If key is `None`, return all settings in a dictio...
c99b13864889f8af9a3f71ab4213f45693236858
49,725
def navigable_thresh(img, rgb_thresh=(160, 160, 160)): """Identify the image pixels that are above the provided threshold. Each threshold value can range between 0 and 255, with 160 doing a nice job of identifying ground pixels only. :param img: Numpy 3d array (x, y, RGB layers) :param rgb_threh: 3 ...
ba5d927149c26bd96611840250c92a4e844c514f
49,726
def Hbeta(D=np.array([]), sigma=1.0): """ Compute the P_ji matrix and the entropy for some data given a sigma value. Params: D - Squared difference of two vectors. Must be a numpy array. sigma - a float Output: H, P - Entropy and P_ji matrix """ # Compute P-row and corresponding pe...
3035d88e1db6d0cc46076dc5cdf23fc04e9cf765
49,727
def gaia_morph(gaia): """Retrieve morphological type for Gaia sources. Parameters ---------- gaia: :class:`~numpy.ndarray` Numpy structured array containing at least the columns, `GAIA_PHOT_G_MEAN_MAG` and `GAIA_ASTROMETRIC_EXCESS_NOISE`. Returns ------- :class:`~numpy.arra...
7433d0b148d37c2310d0200bfc3e5af6d2deadbe
49,728
def motherfucking_rainbows(string, inputmode=False, end="\n"): """ I cANtT FeELLE MyYE FACECsEE ANYrrMOROeeee """ for character in string: print(choice(colors) + character, end="") print('\033[0m', end="") if inputmode: return input("") return print(end, end="")
9359889925841df59b25c964d37349fb3318caf9
49,729
def comp_joule_losses(self, out_dict, machine): """Compute the electrical Joule losses Parameters ---------- self : Electrical an Electrical object out_dict : dict Dict containing all magnetic quantities that have been calculated in comp_parameters of EEC machine : Machine ...
cc106b6602424cbd4f55f98da156a557e17e79e2
49,730
from typing import Tuple def negative_distances( negative_mining_strategy: str, distances: FloatTensor, negative_mask: BoolTensor, positive_mask: BoolTensor, ) -> Tuple[FloatTensor, FloatTensor]: """Negative distance computation. Args: negative_mining_strategy: What mining strategy to...
64ea23280fd1fce937f9561d5873d3fab0dfc810
49,731
def get_courses(input_urls: list[str]): """ Return course_dict of list of courses """ courses = [] for input_url in input_urls: course_data = get_course_data(input_url) course_dict = {} if course_data: course_dict = get_course_dict(course_data) courses.app...
d13534fad5e35cd24d179917fc8e8010050fc090
49,732
import requests import json def get_course_info(orgUnitId): """Returns basic info for a course offering""" url = DOMAIN + "/lp/{}/courses/{}".format(LP_VERSION, orgUnitId) response = requests.get(url, headers=HEADERS) code_log(response, "GET course offering info org unit".format(orgUnitId)) return...
c7e0d465634a1457623a01c94c77f9b88de5ebb2
49,733
def process_remove_outliers_ph(df: pd.DataFrame) -> pd.DataFrame: """Remove waters with ph <= 1 or ph>13 and potability=1.""" df = df[ ~((df["Potability"] == 1) & (df["ph"].apply(lambda x: x <= 1 or x >= 13))) ].copy() return df
1ba7615045f4bf2624c355fbf1ddce63f1f80f35
49,734
import numpy as np def deserialize_numpy(serialized_np, shape): """ Deserializes a numpy array from a JSON-compatible string. from https://stackoverflow.com/questions/30698004/how-can-i-serialize-a-numpy-array-while-preserving-matrix-dimensions#30699208 Parameters ---------- serialized_np : ...
b8981fc98909eb570e59c36c9c0f003e445e2358
49,735
import json def get_field_data_from_room(): """ 1. Get required arguments 2. Call the worker method 3. Render the response """ # 1. Get required arguments args = Eg003Controller.get_args() try: # 2. Call the worker method results = Eg003Controller.worker(args) exce...
5c9c95308a3774e547fae1089118517a6d269424
49,736
def build_tuple_for_feet_structure(quantity): """ Builds the tuple required to create a FeetAndInches object :param quantity: string containing the feet, inches, and fractional inches :return: tuple containing feet, inches, and calculated fractional inches """ feet = float(quantity[0]) inche...
2a66e7bf859e120d224c097a628445342a987067
49,737
def _all(itr): """Similar to Python's all, but returns the first value that doesn't match.""" any_iterations = False val = None for val in itr: any_iterations = True if not val: return val return val if any_iterations else True
bb1145abaaaa1c6910371178ca5ebe68600bb287
49,738
def list_plot3d_array_of_arrays(v, interpolation_type, texture, **kwds): """ A 3-dimensional plot of a surface defined by a list of lists ``v`` defining points in 3-dimensional space. This is done by making the list of lists into a matrix and passing back to :func:`list_plot3d`. See :func:`list_plo...
d3099b55a37f57a9df111b3f8b55033732b1ebcc
49,739
import six def volume(input, copyFrom=None, rescale=True, voltype=None): """ Read an existing geoprobe volue or make a new one based on input data Input: input: Either the path to a geoprobe volume file or data to create a geoprobe object from (either a numpy array or ...
c04a5d5060a0afd25d9b3f12b5d6a207582739ea
49,740
def view_related_developers(request, tag, slug): """ Tutorial > View Related Developers """ namespace = CacheHelper.ns('tutorial:views:view_related_developers', tag=tag, slug=slug) response_data = CacheHelper.io.get(namespace) if response_data is None: response_data, tutorial = RelatedH...
f36355eb0635dd29edd1fe548ff88f22ec51ffdb
49,741
def compute_neuron_head_importance(task_name, model, data_loader, num_layers, num_heads, loss_fct=nn.loss.CrossEntropyLoss(), ...
be0d52c34539db4650aba53c0bb41a958af17ab9
49,742
def no_init(_data, weights): """ Return the entered weights. Parameters ---------- _data: ndarray Data to pick to initialize weights. weights: ndarray Previous weight values. Returns ------- weights: ndarray New weight values Notes ----- Useful ...
f120b49ab26fa1051360b4e4ae85dd07025ae5cc
49,743
def primeFactors(someInt): """ return a list of the prime factors of someInt. e.g. primeFactors(24)=[2,2,2,3] primeFactors(23)=[23] primeFactors(25)=[5,5] """ return "stub"
4afe8491585721852571ecda89c7cd33fb05d1f7
49,744
def create_local_gateway_route(client, local_cidr, **route_kwargs): """[summary] Arguments: client {[type]} -- [description] local_cidr {[type]} -- [description] Keyword Arguments: gateway {[type]} -- [description] (default: {None}) Returns: OperationResult """ ...
e7f07f133be40d7eb71a6c40ec610f3ceba3e6c8
49,745
def validate_ui(self, value): """Validate EngineUI objects.""" if not isinstance(value, EngineUI): reason = 'not an EngineUI object' raise ValueError(self.msg.format(reason)) return value
dbe3eb7377164a2c98dd875f1e5715a84d613176
49,746
import uuid def is_valid_uuid(val): """ Check if a string is a valid uuid :param val: uuid String :return: Returns true if is a string is a valid uuid else False """ try: uuid.UUID(str(val)) return True except ValueError: return False
d04f658d3ae2fa85377e110b0a6716bc34ee9df0
49,747
def generate_stat_string(stat_distribution, name): """generates the gear rating string based on the count of the stat""" count = stat_distribution.count(name) extra_line = "\n" if name == "versatility" else "" return "gear_{0}_rating={1}{2}".format(name, count * config["stats"]["steps"], extra_line)
bab062276be57fbc134bc49c70eda1d96513de86
49,748
from typing import Tuple from typing import List def pad_dialog( dialog: Dialog, max_dialog_size: int, max_utterance_size: int ) -> Tuple[List[List[int]], List[List[int]], List[List[int]], List[List[int]]]: """Pads utterances in a dialog up to max dialog sizes.""" dialog_usr_input, dialog_usr_mask, dialog_sy...
2456716cd0ffc9b0d8613adb04ff206c250cc0c8
49,749
from pathlib import Path import warnings import shlex def _make_sbatch_string( command: str, folder: tp.Union[str, Path], job_name: str = "submitit", partition: tp.Optional[str] = None, time: int = 5, nodes: int = 1, ntasks_per_node: tp.Optional[int] = None, cpus_per_task: tp.Optional[...
bde05036f280d2cf9b88e2b768bb2b93806682dd
49,750
import warnings import urllib def parse_redis_url(url): """ Given a url like redis://localhost:6379/0, return a dict with host, port, and db members. """ warnings.warn( "Use redis.StrictRedis.from_url instead", DeprecationWarning, stacklevel=2) parsed = urllib.parse.urlsplit(ur...
6d24b885feadf58a6f9a17486ba71e4473bce100
49,751
import numpy def Torque(cc1,cc2,ccp,g,mass=1.0): """ cc1: origin of axis, cc2 head of axis ccp: point g: Gradients in Cartasian coordinate, [dx,dy,dz] """ torque=0.0 x21=cc2[0]-cc1[0]; y21=cc2[1]-cc1[1]; z21=cc2[2]-cc1[2] xp1=ccp[0]-cc1[0]; yp1=ccp[1]-cc1[1]; zp1=ccp[2]-cc1[2] dnom...
d4974f3e5997e44530ad7a1988fe36800d3dad4b
49,752
import io import tarfile def write_tar_from_contents(contents, filter=None): """Writes a tar file from a dict of archive names to bytes that represent the contents of each file. """ digest = io.BytesIO() with tarfile.TarFile(mode="w", fileobj=digest) as tar: for filename, content in conten...
c7918a131ca0038647f0de24198609b1f1e28363
49,753
def eliminate(values, s, d): """Eliminate d from values[s]; propagate when values or places <= 2. Return values, except return False if a contradiction is detected.""" global counttotalsearches # DGTEMP counttotalsearches += 1 # DGTEMP if d not in values[s]: return values ## Already elim...
7df68c13c1088933a8601eecbcb3b8bd9aba5d03
49,754
def non_zero_uniform(shape): """Samples in open range (0, 1). This avoids the value 0, which can be returned by tf.random.uniform, by replacing all 0 values with 0.5. Args: shape: a list or tuple of integers. Returns: A Tensor of the given shape, a dtype of float32, and all values in the open i...
c3c50d26d6c1e87e2c1049c5d2931e73f4c7dd86
49,755
import os import torch def load_detector(device='cpu'): """ utility function to load a trained detector """ this_dir = os.path.dirname(__file__) cfg.merge_from_file(this_dir + '/w32_256x256.yaml') # pretrain state_dict by us state_dict = torch.load(this_dir + '/model_best.pth', map_location=d...
9c5bbed088763248bdb01aec71858044d6363830
49,756
def _format_moving_cutoff_predictions(y_preds, cutoffs): """Format moving-cutoff predictions""" if not isinstance(y_preds, list): raise ValueError(f"`y_preds` must be a list, but found: {type(y_preds)}") if len(y_preds[0]) == 1: # return series for single step ahead predictions retu...
f52d70c72a00a84bcbb35eacf952eaee1e7dbb44
49,757
import os def wipe_cluster(cluster, force=False): """ Deletes data on all datanode and namenode disks. Options: force: If set to True, the user is not prompted. Default: no. username: name of the user who is given permissions to the storage directories. Default: hdfs """...
177430592fd7ca2c0e1a064ddcedf103eebc6a26
49,758
import subprocess def get_bom_contents(bom_file): """ Run lsbom on the provided file and return a nested dict representing the file structure """ lsbom = subprocess.Popen( ["/usr/bin/lsbom", bom_file], stdout=subprocess.PIPE ).communicate()[0] file_list = filter(None, [ l...
c31c78a936879d7c97830b8c0f5b76b3bb0a07d1
49,759
import re def get_possible_modes(): """Get the set of possible modes.""" modes = set() with open("web/src/helpers/constants.js", encoding="utf-8") as file_: # The call to `eval` is a hack to parse the `modeOrder` array from the # JavaScript source file. for mode in eval(re.search(r...
062159e1dffd24296264792fd8cf6e53441fb141
49,760
def convert_to_hexadecimal(bits, padding): """ Converts bits to a hexadecimal character with padding. E.g. Converts [False, False, False, True], 0 to "1". Converts [True, False, False, False], 2 to "08" Args: bits: List of boolean values. padding: Integer of number of ...
b8cd1647a24072278aca65f7734934acd93d8f12
49,761
import fastapi from typing import List async def read_patron_list( session: aio_session.AsyncSession = fastapi.Depends( dependencies.get_session), offset: int = 0, limit: int = fastapi.Query(default=100, le=100), current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-...
522407fd8b448564d80957b66df58feef3252f99
49,762
def beta_table(stocks_weights, start, end): """ Returns an attribution table for portfolio beta :param stocks_weights: table of the name of equities in one column, weights in another :param start: start date :param end: end date :return: table """ # Due to the nature of the percentchange...
9cfb5f6658dc1a3d4960bc7451be06c9e48ac9fb
49,763
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
a7f94ec286df89e252262d6ada7031a92d133342
49,764
import wheel def convert(context, base_path, rule): """ Convert the python representation of a targets file into a python representation of a buck file. """ converters = [ discard.DiscardingConverter(context, 'cpp_binary_external'), discard.DiscardingConverter(context, 'haskell_ge...
dcaa320255dc4286b73ab3750d465898060a4008
49,765
import json def set_review_filters(request): """Sets review filters given by passed request. """ review_filters = request.session.get("review-filters", {}) if request.POST.get("name", "") != "": review_filters["name"] = request.POST.get("name") else: if review_filters.get("name"):...
9d9f7e1544e3eea9767f0f85677bcb2b23cdd81c
49,766
import string def _sanitize_title(title): """ Remove all non alphanumeric characters from title and lowercase """ alphanumeric = string.ascii_lowercase + string.digits + ' ' title = title.lower() title = "".join(filter(lambda x: x in alphanumeric, title)) return title
6f0d1818140bc2a50b160f73b8b4590be8f31891
49,767
def IsBefore(version, major, minor, revision): """Decide if a given version is strictly before a given version. @param version: (major, minor, revision) or None, with None being before all versions @type version: (int, int, int) or None @param major: major version @type major: int @param minor: minor...
3fe9f995b90d7406d0b0366b0bbe5a940f975893
49,768
import os import shutil from clinica.utils.longitudinal import save_long_id from clinica.utils.stream import cprint from clinica.utils.ux import print_end_image def save_to_caps( source_dir, image_id, list_session_ids, caps_dir, overwrite_caps=False ): """Save `source_dir`/`image_id`/ to CAPS folder. Thi...
2ca8425faa6affc6587614dc741e5c37839a62c6
49,769
def get_pdf_keys(template_pdf): """ Helper function for generating pdf form field keys, debugging, etc. """ template_pdf = pdfrw.PdfReader(template_pdf) annotations = template_pdf.pages[0][ANNOT_KEY] keys = {} for page in template_pdf.pages: annotations = page[ANNOT_KEY] if ...
1cfb92654cf87d200563f5b08291eed4076721b4
49,770
def generateRules(L, supportData, minConf=0.7): """ 生成关联规则 Args: L 频繁项集列表 supportData 频繁项集支持度的字典 minConf 最小置信度 Returns: bigRuleList 可信度规则列表(关于 (A->B+置信度) 3个字段的组合) """ bigRuleList = [] for i in range(1, len(L)): # 获取频繁项集中每个组合的所有元素 for freqSet in...
2ab2c23450cfff8c80f6b2bd9783e73186f1d064
49,771
def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc impor...
057665c5de32747a92b09f83831db36665f127c3
49,772
import math def makePyramid(elem, graph, levels=4, scale=0.5): """ Create a pyramid of num images based upon elem, which becomes the first child of the new pyramid """ p = elem.getparent() minDim = round(levels / scale) width = max(int(elem.get(swidth, str(minDim))), minDim) height = m...
822f54fcb78673101390d8aaa7bb8aefb022d90c
49,773
import os import errno import logging def get_file_handler(log_dir=None): """ This function is responsible for creating a file log handler with a global format and returning it. Returns: - (obj): A log handler that is responsible for logging to a file. """ log_file_dir = log_dir if log_d...
10ea32b41f296c2ae458dddbac3ea8dc3a9deba5
49,774
def parse_negline(neg_line): """ Parse the THIRD line of the .mmo file, where the negations are stored. Why does it not do this per-phrase? Mystery. We connect the negated-CUI to its appearance in the text using the ConceptPositionalInfo which _appears_ to correspond to the PosInfo field which ...
a412add79370a58f6bd00c0139a9fe334e808432
49,775
import json def validate_cohort_project_allowed(): """ Returns true if a valid project is provided. Remote call is set up in static/js/cohortUpload.js. """ project = request.args.get('project') valid = project in db.get_mw_projects() return json.dumps(valid)
79e568d2a8ec8f5541aa5c6ea97aac5d42d80bb5
49,776
def depthwise_2d_fast(feat, weights): """ """ feat = tf.convert_to_tensor(feat) weights = tf.convert_to_tensor(weights) kernel_size = weights.shape.as_list()[0] return graphics_tf_module.depthwise_conv_fast(feat, weights, kernel_size)
f3aa9989a7c7f4559a1184f19d303187d2d2e594
49,777
def handle_trace_length(state_trace_length): """ transform format of trace length :return: """ trace_length_record = [] for length in state_trace_length: for sub_length in range(0, int(length)): trace_length_record.append(sub_length + 1) return trace_length_record
39631247d10dbaa024a0e8d553024718150ccc51
49,778
from time import time from scipy.signal import fftconvolve def compute_ts_map(counts, background, exposure, kernel, mask=None, flux=None, method='root brentq', optimizer='Brent', parallel=True, threshold=None): """ Compute TS map using different optimization methods. ...
ebfc3dada9e0e39ba8bea0c3e36948f5d6ffe134
49,779
import os import sys import json def init_db_storage(): """Creates and returns path to empty compilation database. Terminates script if database already exists.""" working_directory = os.getcwd() compilation_db_path = os.path.join(working_directory, DB_FILENAME) if os.path.lexists(compilation_db_...
2c3c10b49d73a4969f9d72e0db9282a62e89173f
49,780
import sound def audio_duration(filename): """ duration of a audio file (usually mp3) Parameters ---------- filename : str must be a valid audio file (usually mp3) Returns ------- duration in seconds : float Note ---- Only supported on Windows and Pythonista. On ...
6d51619957c6a6dc96eb1b3647bfe2176ae080fd
49,781
def is_moderator(request, view): """ Helper function to check if a user is a moderator Args: request (HTTPRequest): django request object view (APIView): a DRF view object Returns: bool: True if user is moderator on the channel """ user_api = request.channel_api cha...
31c8b53c28b3972a731b87b13177b3c01c45ade4
49,782
def monkeypatch(monkeypatch): """Adapt pytest's monkeypatch to support stdlib's pathlib.""" class Monkeypatcher: """Middle man for chdir.""" def _chdir(self, value): """Change dir, but converting to str first. This is because Py35 monkeypatch doesn't support stdlib's p...
d7da33204cd0a2f07f51b47b95f106e053c28c1f
49,783
def binom(n, k): """ Obtain the binomial coefficient, using a definition that is mathematically equivalent but numerically stable to avoid arithmetic overflow. The result of this method is "n choose k", the number of ways choose an (unordered) subset of k elements from a fixed set of n elements. ...
b322712d1757df543ccdc92ffc7f883504804346
49,784
def no_auth(request): """ Use this if no auth is desired """ return request
5871518399aee8204d2ece4c8bad575527270627
49,785
def bilstm_layer_cudnn(input_data, num_layers, rnn_size, keep_prob=1.): """Multi-layer BiLSTM cudnn version, faster Args: input_data: float32 Tensor of shape [seq_length, batch_size, dim]. num_layers: int64 scalar, number of layers. rnn_size: int64 scalar, hidden size for undirectional L...
6f55275787e7e5f68004cb5b5173008ab34ae6f1
49,786
from typing import Tuple def calculate_smoothed_trends( case_counts: np.ndarray, death_counts: np.ndarray, hosp_counts: np.ndarray, smoothing_window: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Calculates the smoothed trends with the given smoothing window :param case_counts: Cases per day :par...
c8fc0ef3a071bb04c86bbed1e27d04a505b094ea
49,787
def generate_swagger_params(crown: ViewCrown, swagger_params: dict) -> dict: """ assemble params for swagger_auto_schema by crown """ default_params = {} if crown.body_in: default_params = {"request_body": crown.get_in_serializer_instance()} elif crown.query_in: default_params = ...
dc91db1a6e9317a4b45346e6829df1d4d195a18c
49,788
def total_size(metainfo): """ Compute sum of all files' size """ if metainfo.has_key('files'): total = 0 for infile in metainfo['files']: if infile.has_key('length'): total += infile['length'] return total else: return None
84deea16534e35f2c3c86c9674a8e83f880bd5a5
49,789
def diffmap(adata, **kwargs): """\ Scatter plot in diffmap basis. Parameters ---------- {scatter} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return scatter(adata, basis="diffmap", **kwargs)
f304e66f76fa143ff7102eec5388749c6e6014fe
49,790
import random import string def makeHTMLword(body, fontsize): """take words and fontsize, and create an HTML word in that fontsize.""" #num = str(random.randint(0,255)) # return random color for every tags color = 'rgb(%s, %s, %s)' % (str(random.randint(0, 255)), str(random.randint(0, 255)), str(rando...
00bb65217f4b75344a38100cee88c1e928aa0698
49,791
def sigma_x_rk_new( thickness, radius, length, f_y_k, fab_quality=None, flex_kapa=None ): """ Meridional characteristic buckling stress. Calculates the characteristic meridional buckling stress for a cylindrical shell according to EN1993-1-6 [1]. Paramet...
fc79d852b8878757d7e5e2eb794a1507986bb0cb
49,792
import os import subprocess import sys def exec_command(command, cwd=None, stdout=None, env=None): """Returns True in the command was executed successfully""" try: command_list = command if isinstance(command, list) else command.split() env_vars = os.environ.copy() if env: ...
5849fd97dfa08d8402f08e730c3364d2c1e0d15c
49,793
def ts_grismc_sim(pixels): """ Simple analytic wavelength calibration for Simulated GRISMC data """ disp = 0.0010035 ## microns per pixel (toward positive X in raw detector pixels, used in pynrc) undevWav = 4.0 ## undeviated wavelength undevPx = 1638.33 wavelengths = (pixels - undevPx) ...
f3491fea1fa1e8833384711076e6187f0f6cb42b
49,794
from typing import Callable def get_admin_principal_by(authentication_manager: AuthenticationManager) -> Callable[[Request], PrincipalService]: """ admin only """ return get_principal_by(authentication_manager, [UserRole.ADMIN])
8737f6a271d766560cb2f5c17e271d297c520195
49,795
def get_profile_avatar_upload_to(instance, filename): """ Returns a valid upload path for the avatar associated with a forum profile. """ return instance.get_avatar_upload_to(filename)
840e7482b225c0a456dbc8cd967203aa542945f8
49,796
from typing import Optional def calc_r(alphas: np.ndarray, colvars: np.ndarray, calc_jac: bool) -> tuple[np.ndarray, Optional[np.ndarray]]: """ Calculate linear combination of reaction coordinates given a weights vector and colvars matrix. Also returns the jacobian with respect to the alphas if...
2e14ddd98c296eb0250ff59cc84597594873c383
49,797
def discretized_exponential(lamb, up_bound, steps): """ Exponential distribution on discretized interval [0, up_bound] """ return discretized_state(lambda x: stats.expon.pdf(x, scale=1 / lamb), 0, up_bound, steps)
8ed948c7e7652fa15aefd41f02470864dfd5d1df
49,798
def timedelta_to_string(dt): """ Return hh:min:sec from a timedelta64. There doesn't seem to be a standard pandas or numpy function to do this strangely. """ total_sec = dt / np.timedelta64(1, 's') hours = int(total_sec // 3600) minutes = int((total_sec // 60) % 60) seconds = int(to...
2615dc0f54272183325ddc441d8f489f323c1cfb
49,799