content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def removePEOversampling(src, axes=(-2, -1), dicom_offset=DICOM_OFFSET): """ Remove phase encoding (PE) oversampling. This is implemented such that they match with the DICOM knee images. :param src: input image (np.array) :param axes: tuple of axes containing the [nFE, nPE] dimension. :param...
b94cb7d7beba58e15ef275b18da2567e32cdc599
70,648
def is_rlp_structured_access_list(val): """Returns true if 'val' is a valid rlp-structured access list.""" if not is_list_like(val): return False for item in val: if not is_list_like(item): return False if len(item) != 2: return False address, storage_...
b21d3d45277a2a015f3a7b86fb767c3b7e7593a7
70,649
import ctypes def eul2m( angle3: float, angle2: float, angle1: float, axis3: int, axis2: int, axis1: int ) -> ndarray: """ Construct a rotation matrix from a set of Euler angles. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2m_c.html :param angle3: Rotation angle about third rotat...
78529692795b617b392a6552f0db71c8e5ca155d
70,650
from datetime import datetime def create_upcoming_test_datetime() -> datetime: """ Based on 2025-01-01 00:00:00 """ return datetime(2024, 1, 1, 0, 0, 0, 0)
9a6bc020fd44e0e59441a83b75d2e7fb7630d386
70,652
def urlsplit(url): """ Splits a URL like "https://example.com/a/b?c=d&e#f" into a tuple: ("https", ["example", "com"], ["a", "b"], ["c=d", "e"], "f") A trailing slash will result in a correspondingly empty final path component. """ split_on_anchor = url.split("#", 1) split_on_query = split_o...
47cd2b556f842dd3ed499f841ff41d16c0747cbc
70,653
from typing import Any def validator(message: ErrorMessage): """ Turn a bare checker function into a descriptive validator function """ def decor(fun: CheckerFunction) -> ValidatorFunction: def inner(value: Any) -> ValidatorReturn: ok = fun(value) if not ok: ...
d13ddf5f691850e22633a7d8d011f70153826772
70,654
def separate(df, key, into, splitter=default_splitter): """Given a data frame, separates one of its columns, the key, into new variables. """ assert type(df) is pd.DataFrame assert key in df.columns # Hint: http://stackoverflow.com/questions/16236684/apply-pandas-function-to-column-to-creat...
dff62cda31086dcdf0aa8f5aa4ffb28e0fed01f4
70,655
def build_old_belief( belief_type, num_agents=NUM_AGENTS, *, low_pole=LOW_POLE, high_pole=HIGH_POLE, step=BELIEF_STEP, consensus_value=CONSENSUS_VALUE): """Builds the initial belief state according to the `belief_type`. Helper function when iterating over...
6ef5222c536acc5c9cf4496e697dd9520388c8a4
70,656
def create_markup(s, modifiers=None, targets=None, span=None, prune_inactive=True): """Creates a markup object from a sentence. s is a sentence from a list of a split report. span is the tuple of the span of the sentence. Optional. Returns a named tuple where markup=markup, span=span """ markup ...
c454010cfe272f35e11e111c29027bdc28d09c35
70,657
def sub_timedelta(date, delta, units='hours since 1800-01-01 00:00', calendar='standard'): """ Wrapper method to subtract a timedelta to a netcdftime.datetime or datetime.datetime or pd.Timestap object Parameters ---------- date : scalar_like Date to subtract <delt...
d309f58a1bf309ab11a7fd8bef1e5ba1b3cb6ac2
70,658
from typing import Optional from typing import Mapping from typing import Any def _process_environ(environ: Optional[Mapping[str, Any]] = None, ext_environ: Optional[Mapping[str, Any]] = None, enable_ext: bool = False) -> Mapping[str, str]: """ process environment var...
7ded58157f59fdb63ced8d680fd9cb1c5041416c
70,659
def rotate_key(element): """Returns a new key-value pair of the same size but with a different key.""" (key, value) = element return key[-1] + key[:-1], value
e9407e87a24571bb17e484d7954764dce38003dc
70,660
def labels_to_tags(labels): """Converts integer labels to component type labels. Input: array of integer labels Output: arry of string tags """ tag_dict = {v:k for k, v in config['arg_components'].items()} tag_dict[len(tag_dict)] = 'pad' return [tag_dict[i] for i in labels]
d7a6fcf6d77699d4f4ef4d748838ad487431d979
70,661
import math def hypotenuse_length(leg_a, leg_b): """Find the length of a right triangle's hypotenuse :param leg_a: length of one leg of triangle :param leg_b: length of other leg of triangle :return: length of hypotenuse >>> hypotenuse_length(3, 4) 5 """ return math.sqrt(leg_a**2...
7a59ede73301f86a8b6ea1ad28490b151ffaa08b
70,662
def build_add_trunk_vlan(interface, vlan, action): """Build BGP config using Jinja2""" with open(build_vlan_to_trunk) as trunk_file: build_vlan_trunk_template = Template(trunk_file.read(), keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) vlan_trunk_config_j2 = build_vlan_trunk_...
ff611bb055e0852e483ff3c7e330a8e27b50c8b4
70,663
def getParent(obj): """ Returns the container the object was traversed via. See `ITraversalAPI` for details. """ try: location_info = ILocationInfo(obj) except TypeError: pass else: return location_info.getParent() # XXX Keep the old implementation as the fallba...
b05f9158fc60e440f86edf25cf8b06b91190d887
70,664
def minimize_ucq_in_dnf(query): """Convert UCQ to DNF form and minimise. Parameters ---------- query : LogicExpression. query in UCQ semantics. Returns ------- LogicExpression minimised query in UCQ semantics. """ query = convert_to_dnf_ucq(query) head_varia...
94f4c1e54f2b2a5dae4099902b8c2fad065d1104
70,665
def vsh_larionov_tertiary(gr, sand_line, shale_line): """ Apply Larinov equation (Larinov, 1969) to correct Gamma Ray index Vshale values. """ shale_line = float(shale_line) sand_line = float(sand_line) vsh_grindex = (gr - sand_line)/(shale_line - sand_line) vsh_larionov = 0.08...
d38092f79f4c50af2ef8f6865271a7d35a4d3b69
70,666
from typing import Union from typing import List def bincoeff(n: int, k: int = None) -> Union[int, List[int]]: """Computes the binomial coefficients of `(1 + x)^n` or returns the k-th coefficient """ if k is not None: return comb(n, k) else: result = [] for i in range(0, n + 1)...
b82a4c03470c3ded25738bc664ede8d4d2e7a217
70,667
import re def key_search (search_string, dict, silent=True): """Поиск нужного объекта в словаре, выбор по списку совпадений.""" # Создаётся регистронезависимая поисковая строка: p = re.compile(search_string, re.I) # Создаём словарь совпадений: d_found = {} counter = 0 # Поиск в словаре: ...
eea262b433f85ccb076bad34dde47b31fe02723e
70,668
def Or(a: Bit, b: Bit) -> Bit: """ Or gate out = True if (a == True or b == True) , False otherwise ``` +-------+ | | a +--+ NOT +--+ +--------+ | | +--+ | +-------+ | NAND +--+ out +---+ | +---...
0d3c3393089102370c46d8361fadd66758c42e59
70,669
import numpy def ddspline(alpha, control_points): """Computes the second derivative of a Cubic Bezier curve wrt alpha. Args: alpha: scalar or list of spline parameters to calculate the curve at. control_points: n x 4 matrix of control points. n[:, 0] is the starting point, and n[...
4b739195183991c81dae968196339719597bf846
70,671
def make_rowcol(string): """ Creates a rowcol function similar to the rowcol function of a view Arguments: string -- The string on which the rowcol function should hold Returns: A function similar to the rowcol function of a sublime text view """ rowlens = [len(x) + 1 for x in string.s...
87a0c162c69dd8f1e4e50f3b40da8772e645772e
70,672
def sigmoid(x, derivative=False): """ Returns the sigmoid function applied to x. Alternatively, can return the derivative or the sigmoid function. Args: x (np.ndarray): The input to the sigmoid function. derivative (bool): Whether to return the derivative or not. Default: Fa...
b23e7316f902b8632de7751d1a1715172fb75846
70,673
def search_service(): """Connect to Google's Search API service with oauth2 using the discovery service.""" return google_service(DCLK_SEARCH_SCOPE)
065cba99bbd7258828b50c9cae8368130363c68c
70,674
def compute_llr(c, means, sds): """Compute the pulse log-likelihood supporting Target 1.""" # Define the generating distributions m0, m1 = means s0, s1 = sds d0, d1 = stats.norm(m0, s0), stats.norm(m1, s1) # Compute LLR of each pulse l0, l1 = np.log10(d0.pdf(c)), np.log10(d1.pdf(c)) llr...
16c769699a5df77eba344abda5033b5e7f2743c9
70,675
def fake_gauss_1(num_list): """Fake Gauss v1""" a = num_list[0] b = num_list[-1] n = b - a + 1 return int(n * (n + 1)/2)
d99cff9196e8a365e1260eee6625db22a25da70c
70,676
def get_activation_function(activation_fn_name: str): """Convert from an activation function name to the function itself.""" if activation_fn_name is None: return None activation_fn_name = activation_fn_name.lower() string_to_activation_fn = { "linear": None, "tanh": tf.nn.tanh,...
8d814aa9a3b53402fbd7b33653e12fb71269268b
70,677
import http from typing import Optional import gzip from datetime import datetime def export( request: http.HttpRequest, pklist: str, workflow: Optional[models.Workflow] = None, ) -> http.HttpResponse: """Export the actions given as comma separated list of ids. :param request: :param pklist: ...
4c5b4f1faae08896a275dbb05a39bcfa22f53f57
70,678
def check_conf_validity(config_dict): """A configuration validity test. Return false if any required option is not valid. """ if not config_dict["sample.sample_id"].isdigit(): error("Config Validity Check: sample id -- %s should be specified and be an integer!" % config_dict["sample.sample_id"]) ...
e8c04847c9e9e209a09184b98d16525143c45397
70,680
def pathManager(fileName,writingMode,askedForGoAhead,showedOverwriting,filesThatExistedBeforeExe,createdFileNames,lineNum): """Takes care of file location, naming conventions, and confirmation to overwrite filtered files.""" goAhead = False subDirName = [] subDirName.append('FL') splitFileName ...
a7e5127a64ca6d5a2e1f9fadc1cfaca1da0c46fb
70,681
from typing import List import statistics def remove_outliers(numbers: List[float], num_deviations: float = 3): """ >>> remove_outliers([0, 1, 2, 3, 4, 5, 50, 6, 7, 8, 9], num_deviations=1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ if len(numbers) < 2: return numbers avg = statistics.mean(num...
251e739a301bc06f40e4847f5bdb7282012bfce9
70,682
def test_ironic_create_node( mocker, admin_context: "RequestContext", ironic_worker: "IronicWorker", database: "utils.DBFixtures", ): """Test that new nodes are created if not already existing.""" get_node_count = 0 patch_node_count = 0 fake_hw = get_fake_hardware(database) def _fak...
2cafaadca9706245b6fb23c1bde08c36e1adb94c
70,683
import requests def _get_page_num_gpzy_distribute_statistics_bank() -> int: """ 东方财富网-数据中心-特色数据-股权质押-质押机构分布统计-银行 http://data.eastmoney.com/gpzy/distributeStatistics.aspx :return: int 获取 质押机构分布统计-银行 的总页数 """ url = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get" params = { ...
452f1353475315277a820486de4c30f8886784f9
70,684
from anndata.base import _normalize_index from scipy.sparse import dok_matrix def rna_velocity(adata, loomfile, copy=False): """Estimate RNA velocity [LaManno17]_ This requires generating a loom file with Velocyto, which will store the counts of spliced, unspliced and ambiguous RNA for every cell and eve...
b4cc0ed98be63279fbb10fc290356ae73001f0d1
70,685
def commonPoints(lines): """ Given a list of lines, return dictionary - vertice -> count. Where count specifies how many lines share the vertex. """ count = {} for l in lines: for c in l.coords: count[c] = count.get(c, 0) + 1 return count
1b838ddd4d6a2539b0270cd319a2197e90372c3a
70,686
def compare(isamAppliance1, isamAppliance2): """ Compare access policies between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) obj1 = {'rc': 0, 'data': []} obj2 = {'rc': 0, 'data': []} for attr in ret_obj1["data"]: if search(isamApplia...
ddb55360bd9d316210598d9575de1cda50100a24
70,687
def entity_in(entity, entities, primary_field=ct.default_int64_field_name): """ according to the primary key to judge entity in the entities list :param entity: dict {"int": 0, "vec": [0.999999, 0.111111]} :param entities: list of dict [{"int": 0, "vec": [0.999999, 0.111111]}, {"...
997661015fecd562aaa064ad097747de222d5153
70,688
def miller_rabin_test(candidate, iterations, randfunc=None): """Perform a Miller-Rabin primality test on an integer. The test is specified in Section C.3.1 of `FIPS PUB 186-4`__. :Parameters: candidate : integer The number to test for primality. iterations : integer The maximum...
a334003b7467921246313784d60407ddafa0221e
70,690
from typing import Any async def change_account_password( schema_in: schemas.SendEmailChangePassword, db: AsyncSession = Depends(deps_auth.db_session) ) -> Any: """Send email to change user password""" auth_data = AuthorizationData.where( login=schema_in.login, registration_type=enums....
51aab1dee48faa7efd1a535f3c200a9c2467a400
70,691
import struct def load(input_data, key_is_name=False): """ py:function:: piexif.load(filename) Return exif data as dict. Keys(IFD name), be contained, are "0th", "Exif", "GPS", "Interop", "1st", and "thumbnail". Without "thumbnail", the value is dict(tag name/tag value). "thumbnail" value is JPEG as byte...
0bac04b7d533514e96f4dea694bd2865ff4ae495
70,693
def _enum_wordnetsyn_match(enum_hypothesis_list, enum_reference_list, wordnet=wordnet): """ Matches each word in reference to a word in hypothesis if any synonym of a hypothesis word is the exact match to the reference word. :param enum_hypothesis_list: enumerated hypothesis list :param enum_re...
52b42dd87f693c3681f3fa94a68096e3f4ff3f79
70,694
def spring_model(): """ Creates a SpringMassModel object. """ return SpringMassModel(mass=1.5, time_step=1.0, cost=1.0)
ecf68b593c0118b5b49304232318a3a214682adf
70,696
def plotting_context(): """Context for plotting with Quantity objects Based on : https://docs.astropy.org/en/stable/_modules/astropy/visualization/units.html#quantity_support """ # Get all subclass for Quantity, since matplotlib checks on class, # not subclass. def all_issubclass(...
06768c3aaad5bb28c8b81d6900adc2db05ff4e04
70,697
from typing import List def vr_persistence_l1( point_cloud: Tensor, max_dimension: int, max_ball_diameter: float = 0.0 ) -> List[List[Tensor]]: """Returns the barcodes of the Vietoris-Rips complex of a given point cloud w.r.t. the l1 (manhatten) distance. Args: point_cloud...
e8e77868f079d36e25efd1634709befe28938bd3
70,700
from typing import Optional from typing import Union from typing import List def list_cube_caches( connection: "Connection", nodes: Optional[Union[List[str], str]] = None, cube_id: Optional[str] = None, loaded: Optional[bool] = False, db_connection_id: Optional[str] = None, project_ids: Option...
3651f51027d047d52b2191301266cc571eaabb12
70,701
import gettext def beforeRequest(): """ Processing of URL before any routing """ # Force https on prod if constants.HTTPS: if not request.url.startswith("https") and "ogn.dev" not in request.url_root: return redirect(request.url.replace("http", "https", 1)) selected_lang = None ...
a8a69a3691101be61bb4fa27141d73f306a00fbd
70,702
from typing import Union from typing import Optional from typing import List from typing import Any from typing import Dict def compute_bivariate( df: Union[pd.DataFrame, dd.DataFrame], col1: Union[str, LatLong], col2: Union[str, LatLong], cfg: Config, dtype: Optional[DTypeDef], ) -> Intermediate:...
ddc0cec853c7aaf0a177eaeb78cd626d04d93e27
70,703
def psd_multitaper(inst, fmin=0, fmax=np.inf, tmin=None, tmax=None, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, proj=False, n_jobs=1, verbose=None): """Compute the power spectral density (PSD) using multitapers. Cal...
c27e5db06edbba3b64c1317701a0ed3204ee91aa
70,704
def silhouette( adata, group_key, embed, metric='euclidean', scale=True ): """ Wrapper for sklearn silhouette function values range from [-1, 1] with 1 being an ideal fit 0 indicating overlapping clusters and -1 indicating misclassified cells B...
ea23c0d6563af312565948dcd3214de181b845a9
70,705
from re import MULTILINE def parseConfiguration(condition: str) -> tuple: """Extract the config and platform from the condition string. Args: condition (str): The string from the csproj file. Returns: tuple: The config and the platform. """ condition = condition.strip() config_platform_regex = r"^\'\$\(Co...
24506efb3a9a98bc5354a6bd01f9efc0413f2810
70,706
def isostring(dt): """Convert the datetime to ISO 8601 format with no microseconds. """ if dt: return dt.replace(microsecond=0).isoformat()
db7326e53402c0982514c4516971b4460840aa20
70,707
def listAllChats(): """docstring for listAllChats""" all_chats = Message.query.order_by(Message.date).all() sessionIDs = [] sessions = [] # Organize per sessions for chat in all_chats: # Do we already have this session? if chat.session in sessionIDs: sessionIndex = se...
4a8a7fae4b063a2dc04ca1fab4cd83a89dd879ab
70,708
def country(ip_address): """ Return the country code of a given IP Address :param ip_address: IP Address (string) """ return geo.get_country(ip_address)
fe83dcac8bcbbe765c1bfba0eeb3d07c24442ca5
70,709
def read_hadsst4(filename, adjust_clim=False): """ Read data from HadSST4 :param str filename: infile to read :returns: Timeseries object with upper and lower bounds. """ # Colin's global temperature files (observed) indata = np.genfromtxt(filename, dtype=(float), delimiter=",", skip_he...
73f25d76b5c43c8f957433538abd5d25496906a1
70,710
def add_all(application, project_id, control_client, loader=service.Loaders.FROM_SERVICE_MANAGEMENT): """Adds all endpoints middleware to a wsgi application. Sets up application to use all default endpoints middleware. Example: >>> application = MyWsgiApp() # an existing WSGI applicati...
ad164c55def209e15f450ea466f2ab28591a17d0
70,712
def standardize(ts,cap,method): """ use cap_weighted mean to standardize the factor Params: ts: pd.Series, cross section factor data cap: pd.Series, cross section cap data, the secID is matched one by one available for cap_weighted method: ...
99451dfa014e83363d05234a2558d4f1422fd72f
70,714
from typing import Optional def download_one_segment( segment_id: str, start_date: dt.date = dt.datetime.now().date() - dt.timedelta(weeks=1), end_date: dt.date = dt.datetime.now().date(), out_filepath: pl.Path = None, api_token: Optional[str] = None ) -> pd.DataFrame: """R...
5df9d9b98453d323b00f01dc612f389b0877f346
70,716
import base64 def image_encoder(img_path): """Function to verify API status. Parameters ---------- img_path : str The path to the image to be encoded. Returns ------- encoded_img : str A UTF-8 string containing the encoded image. """ with open(img_pat...
7ef4c5c4a0fad340ab50c798e70b0f0c4ceb0d22
70,717
def Make_Soft_RGG_Given_Positions(positions,Kernel,metric="Euclidean",return_connection_probs = False,kernel_params=[],distance_metric_function=None): """ Sample the adjacency matrix of a single Soft RGG given positions in some domain. Parameters --------------- positions : list List of positions in the em...
f1cb87739b73540f56a6847ebcada6ed1d7b62a4
70,718
def gen_TP_mask2(norm_lines, h = 256, w = 256, with_ext=False): """ 1 cengter + 4 dis + 2 return [7, h, w] """ # note that in norm_lines, each line is like: line = [pt[0][0], pt[0][1], pt[1][0], pt[1][1]] # and they are already expressed in the H/2 x W/2 array img_diag = np.sqrt(h**2 + w*...
9571d15f183d45b043b89e27a02d99e350117b5b
70,719
def inject_menu_items() -> dict: """Defines items of navbar""" return dict(menu_items=[ { 'title': '<i class="fa fa-home" aria-hidden="true"></i> Home', 'url': '/', 'function_name': 'home', 'children': None }, { 'title': '<i cla...
dfca070335ed11a60cc721056de6a90f62f66749
70,720
def deblend_segments(image, segm, npixels=None, fwhm=8., kernel_size=4, nlevels=30, contrast=1/1000): """ Deblend overlapping sources labeled in a segmentation image. Parameters ---------- image : array like Input image. segm : `~photutils.segmentation.SegmentationImage` or `None` ...
d47ef9d8c4ed5c0dcfbcb816d297664ead7963f8
70,721
def jobresults_download(jobname,results_file_name): """get the contents of one of the results outputs and iniate a download. If no file name or results type is sent as a parameter, by default just sent the rendered html. """ # sanitize the filename using a method for job module results_file_name ...
5f338ac323cd72a3bfabe5c6db762619d615d9b6
70,724
def ce_metric(probs, labels): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ epsilon = 1e-12 def one_hot(a, num_classes)...
7002b738bb62bce34074e8ec4fc70fd48cef791d
70,725
def filenameDictForDataPacketType(dataPacketType): """ Return a dict of fileDescriptors for a given DataPacket type. """ foo = dataPacketType(None, None) return foo.filenames
6853add9035e3b7aad86a001ee7f46e5e69336a8
70,727
def git_origin_url(git_repo): # pylint: disable=redefined-outer-name """ A fixture to fetch the URL of the online hosting for this repository. Yields None if there is no origin defined for it, or if the target directory isn't even a git repository. """ if git_repo is None: return None ...
d1f301a31aca6fae2f687d2b58c742ee747c4114
70,728
from typing import Any def argument(*name_or_flags: Any, **kwargs: Any) -> tuple: """Convenience function to properly format arguments to pass to the subcommand decorator. """ return (list(name_or_flags), kwargs)
22b2cbda7a3c2e4113c47896d60290b124cf85f1
70,729
from datetime import datetime def create_virtual_machine(module, azure): """ Create new virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine and/or cloud service was created, false otherwise ""...
722c88aa17528000c6be4cb1e974992062025bc9
70,730
def viterbi(y, A, B, Pi=None): """ Return the MAP estimate of state trajectory of Hidden Markov Model. Parameters ---------- y : array (T,) Observation state sequence. int dtype. A : array (K, K) State transition matrix. See HiddenMarkovModel.state_transition for detail...
c16f70847efc84140af43950b397c3b0ac54190b
70,731
def home(): """Redirect from root to topologies listing.""" return RedirectResponse(url=app.url_path_for("topologies_page"))
9bdac9a21c7f9b00094b43a4d8804287a4c7b3a9
70,732
from typing import Generator import ast from textwrap import dedent def _parse_and_compile_gen( source: str, *, return_mode: str = "last_expr", quiet_trailing_semicolon: bool = True, mode="exec", filename: str = "<exec>", flags: int = 0x0, ) -> Generator[ast.Module, ast.Module, CodeType]: ...
cfd8ebdc792c090b21793de0663aabe52bff900f
70,734
def AuthorYr(r): """ Author yr format Smith et al. 2010 : Smith10 """ tentative_key = Author(r) + Yr(r) return tentative_key
bc03b42ace696d4c72dd4801aeff700182c027c0
70,735
def is_callback(func: t.Callable[..., t.Any]) -> bool: """Check if function is safe to be called in loop.""" return getattr(func, "__odss-callback__", False) is True
52b10dbf763f6b9d8963346e7f3c74f10de451f4
70,739
def safe_quote(value): """ Safe encoding of value taking care of unicode value urllib.quote doesn't like unicode values """ return quote(to_utf8(value))
9dd6cfcd58ab7371a8a6282e57df82b51bbadee5
70,741
def as_str_any(value): """Converts to `str` as `str(value)`, but use `as_str` for `bytes`. Args: value: A object that can be converted to `str`. Returns: A `str` object. """ if isinstance(value, (bytes, bytearray)): return as_str(value) else: return str(value)
2e200c4c7b00508c88bdc7c9805d31577f4fe9f3
70,743
import torch def encode(matched, priors, variances=[0.1, 0.2]): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shap...
a34cb00a959515537237b937b01e857aaf93245b
70,744
import gzip import json def bin_wikidata_entities_by_popularity( wikidata_info_path: str, num_bins: int, max_ents_per_pop: int = 10 ): """Groups a list of Wikidata entities with the specified entity type into one of `num_bins` equally sized bins based on entitye popularity. We only include entities wi...
69a0c3292ea85003fec764f0e6528979b58741c5
70,745
def get_closest_point(point, node_list): """Get the closest point to each nodes in the list. Args: point (str): Node to evaluate the distance to. node_list (list): List of nodes to search for the closest to the point. Returns: str: The closest node. """ compare = float("inf...
bc653324cd9928a2d5ff08a15bf54840f06f99c8
70,746
def emp_entropy(x, bins=1000): """Computer empirical entropy of array x. Argument is first partitioned into the histogram. Then the entropy is computed over the histogram. Args: x: an array of floats. bins: number of bins in the histogram. Returns: entropy """ if not np.isnan(x).any(): ...
d529fb46a4296a02b7ef2eaf2aa8d0f4d20664f7
70,748
from typing import List def unbiased_evaluator(user_embed: np.ndarray, item_embed: np.ndarray, train: np.ndarray, test: np.ndarray, num_users: int, num_items: int, pscore: np.ndarray, model_n...
3fa96288b699a24f4f77a42a99207c692deee420
70,749
import unicodedata def remove_accents(input_str): """Replaces accented chars by their ascii equivalents.""" nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
21be3562c4a836f1d73dfc07228ef618c9ad68e9
70,751
import re def trim_money_string(s): """Trims excess characters from a monetary value. Only keeps the digits within a monetary value, such as trimming `$123,456` to `123456`. Trims dollar signs and commas. Args: s (:obj:`str`): The monetary amount to trim. Returns: :obj:`str`: The sa...
c85cd8004c5a6ddd2aa883f691adbf3276d709f0
70,752
def build_model(input): """ Nearest Neighbors Model for song suggestions """ df = pd.read_csv('suggestor/clean_US.csv') # configure song index Nearest Neighbor result output mask = ['combined', 'url'] df_result = df[mask] # set up data DataFrame for numerical features only data = df....
f613b95393ddb60b2a0a411bfe1622f39aa2c821
70,753
def unprocess_obs_dict(obs_dict): """ Prepare processed observation dictionary for saving to dataset. Inverse of @process_obs. Args: obs_dict (dict): dictionary mapping observation keys to np.array or torch.Tensor. Leading batch dimensions are optional. Returns: new_dic...
337e5b981b271c8fe084b0e1726ff5daec45e6fc
70,754
def expand_sun_params(new_params, base_result, seed=0): """ Implements the expansion from an existing set cover instance as described in [1]. Parameters ---------- new_params: tuple New params for sun_params base_result: tuple Tuple of (costs, sets) that represent instance param...
fd03e8d809c2726e4a6543e12122f559f20d281e
70,755
import json def create_folder(folder, provider): """ Create a folder on the remote provider :param folder: :param provider: :return: the storage_key of the created folder on the remote provider """ r = _connect(provider) storage_key = _get_key_for_file(folder.rel_path) r.set(stora...
6d64a885fb06e5723ba71860fea54d85f70856f9
70,756
def convolution_2d( n_H_prev, n_W_prev, n_C_prev, n_C, *, kernel_size, stride=1, padding=0, activation="relu"): """Creates a 2D convulational layer. Args: n_H_prev: height of inputs n_W_prev: width of inputs n_C_prev: number of input channels n_C: number of outpu...
1470fd27630493bf05334de10c3dbfe00d848808
70,760
def drm_get(io_current): """ expects a list of GPIO pins, returns user friendly DRM representation """ if io_current == [1, 0]: return 2 elif io_current == [0, 1]: return 3 elif io_current == [0, 0]: return 0 else: abort("ERROR: unknown pin state: %s" % (io_current))
da3980cd16e4f30d9daacf5f5a17e67a51ca9e76
70,761
def special_len(tup): """ comparison function that will sort a document: (a) according to the number of segments (b) according to its longer segment """ doc = tup[0] if type(tup) is tuple else tup return (len(doc), len(max(doc, key=len)))
81154c8e1b31dc37cffc43dfad608a5cd5281e4c
70,762
def token_required(view_func): """Decorator which ensures the user has provided a correct user and token pair.""" @csrf_exempt @wraps(view_func) def _wrapped_view(request, *args, **kwargs): user = None token = None basic_auth = request.META.get('HTTP_AUTHORIZATION') use...
bce7fbf9f67af27554a2932f1df152fc022b337f
70,763
import re def format_match(card, num): """ Format a match. """ card_unique = ('{} '.format(EMOJIS['[unique]']) if card.get(lotr.CARD_UNIQUE) else '') card_name = card[lotr.CARD_NAME] card_type = card[lotr.CARD_TYPE] sphere = card.get(lotr.CARD_SPHERE, '')...
120be8f3840ab9afb28d487ca4555ea52dde3c86
70,764
def opener(wrapped, instance, args, kwargs): """ opener(yaml.load)("conf.yaml") opener(json.load)("conf.json") """ path = args[0] with open(path) as f: return wrapped(f)
05c42f0e668f2419b4e478e8602c056a8cda634b
70,766
def make_header_lines(all_bits): """ Formats header lines """ lines = [] # Bit names bit_names = ["%d_%d" % (b[0], b[1]) for b in all_bits] bit_len = 6 for i in range(bit_len): line = "" for j in range(len(all_bits)): bstr = bit_names[j].ljust(bit_len).replac...
6c48eb125f39ca55ae47c5f6a21732fdb60c9de0
70,767
def _log_prior_trace(trace, model): """ Computes the contribution of the log prior to the log posterior. Parameters ---------- trace : PyMC3 trace object. Trace from the PyMC3 sampling. model : PyMC3 model object Model under which the sampling was performed Returns ----...
08bac37b8e26e7342189aa9361394a4593d79c21
70,768
def elina_abstract0_manager(a): """ Return a reference to the manager contained in an ElinaAbstract0. The reference should not be freed. Parameters ---------- a : ElinaAbstract0Ptr Pointer to the ElinaAbstract0. Returns ------- man : ElinaManagerPtr Pointer to t...
8d19f1317f3844dc0fe49a258744b6fec0b6d13f
70,770
def _pair_product(p, i, j): """Return product of counts of i and j from data.""" try: return sum(p[i].values())*sum(p[j].values()) except KeyError: return 0
7a7a19d62544ee88f6755c64f08438c0ab95033f
70,771
from typing import Optional def optional_arg_return(some_str: Optional[str]) -> Optional[int]: """Optional type in argument and return value.""" if not some_str: return None # OK # Mypy will infer the type of some_str to be str due to the check against None return len(some_str)
8125965fb1fe1f11f4f5045afc8107bcdfc95fc0
70,773
from typing import List from typing import Dict def launch_jobs_for_sra_ids( sra_import_app: DXApp, sra_ids: List[str], folder ) -> Dict[str, DXJob]: """Launch sra_import_app on a list of sra_ids Args: sra_import_app: app instance sra_ids: list of SRA ids folder: output folder on ...
b540ff4b9d18d5ecf43227b4b8c625dda52448f0
70,774
def get_blob(digest, models_ref): """ Find a blob by its digest. """ Blob = models_ref.Blob return Blob.select().where(Blob.digest == _ensure_sha256_header(digest)).get()
93d00b7bb6a84ef227898c6875277e531286f94a
70,775