content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_format(name: str, pattern: str, label: bool) -> str: """Create snippet format. :param name: Instruction name :param pattern: Instruction regex pattern """ snip: str = f"{name:7s}" + pattern.format(**SNIPPET_REPLACEMENTS) snip = snip.replace("(", "") snip = snip.replace(")", "") ...
ec25ecf4f2d46db398c389b479620e0cbcf30ee2
17,790
import torch def make_observation_mapper(claims): """Make a dictionary of observation. Parameters ---------- claims: pd.DataFrame Returns ------- observation_mapper: dict an dictionary that map rv to their observed value """ observation_mapper = dict() for c in...
43052bd9ce5e1121f3ed144ec48acf20ad117313
17,791
def toCSV( dataset, # type: BasicDataset showHeaders=True, # type: Optional[bool] forExport=False, # type: Optional[bool] localized=False, # type: Optional[bool] ): # type: (...) -> String """Formats the contents of a dataset as CSV (comma separated values), returning the resulting CSV a...
9d998891a9712f42af8744513c1f61540eee0e2e
17,792
def add_record(session, data): """ session - data - dictionary {"site":"Warsaw"} """ skeleton = Skeleton() skeleton.site = data["site"] skeleton.location = data["location"] skeleton.skeleton = data["skeleton"] skeleton.observer = data["observer"] skeleton.obs_date = data["obs_dat...
f91df4459b37b7df4d313fd01323451bf897a754
17,793
def hue_angle(C): """ Returns the *hue* angle :math:`h` in degrees from given colour difference signals :math:`C`. Parameters ---------- C : array_like Colour difference signals :math:`C`. Returns ------- numeric or ndarray *Hue* angle :math:`h` in degrees. Exa...
599f594eff92280df06a4c6ef88ccf286f146475
17,794
def get_submodel_list_copasi(model_name: str, model_info: pd.DataFrame): """ This function loads a list of Copasi model files, which all belong to the same benchmark model, if a string with the id of the benchmark model id is provided. It also extracts the respective sbm...
ea889e5ea836131d8febc94dd69806b2acf47559
17,795
def GetNextBmask(enum_id, value): """ Get next bitmask in the enum (bitfield) @param enum_id: id of enum @param value: value of the current bitmask @return: value of a bitmask with value higher than the specified value. -1 if no such bitmasks exist. All bitmasks are so...
d2c415e1a3ad63c651dc2df771dbe43a082613d9
17,796
def annotate_link(domain): """This function is called by the url tag. Override to disable or change behaviour. domain -- Domain parsed from url """ return u" [%s]"%_escape(domain)
26b5c8979cc8cd7f581a7ff889a907cf71844c72
17,797
def kmeans(data, k, num_iterations, num_inits=10, verbose=False): """Execute the k-means algorithm for determining the best k clusters of data points in a dataset. Parameters ---------- data : ndarray, (n,d) n data points in R^d. k : int The number of clusters to separat...
3cc3681ac0d0306fc7dce2da5757e6c162f7c457
17,798
def point_on_bezier_curve(cpw, n, u): """ Compute point on Bezier curve. :param ndarray cpw: Control points. :param int n: Degree. :param u: Parametric point (0 <= u <= 1). :return: Point on Bezier curve. :rtype: ndarray *Reference:* Algorithm A1.4 from "The NURBS Book". """ b...
3e4a494ff9ffabf6ad0d2711beba0e55647e7071
17,799
import requests def list_with_one_dict(sort_type, url_param=None): """ Search by parameter that returns a list with one dictionary. Used for full country name and capital city. """ extra_param = "" if sort_type == 2: url_endpoint = "/name/" user_msg = "full country name" ...
79f96ab76c123bfa3c3faee57e9af6c1900c3cd7
17,800
def get_form(case, action_filter=lambda a: True, form_filter=lambda f: True, reverse=False): """ returns the first form that passes through both filter functions """ gf = get_forms(case, action_filter=action_filter, form_filter=form_filter, reverse=reverse) try: return gf.next() except S...
b0e8caeb6fae1f56407aaf14475c5f06c9b4a3d0
17,801
from datetime import datetime def csv_to_json_generator(df, field_map: dict, id_column: str, category_column: str): """ Creates a dictionary/json structure for a `single id dataframe` extracting content using the `extract_features_by_category` function. """ id_list = find_ids(df=df, id_column=id_c...
40bf0657d8ca7d141af919f03b9b6e7cc6887749
17,802
def sunset_hour_angle(sinLat, cosLat, sinDec, cosDec): """ Calculate local sunset hour angle (radians) given sines and cosines of latitude and declination. """ return np.arccos(np.clip(-sinDec / cosDec * sinLat / cosLat, -1, 1))
43e9e6d5026ea16f348f6704a8226763f0d08786
17,804
def handle_enable(options): """Enable a Sopel plugin. :param options: parsed arguments :type options: :class:`argparse.Namespace` :return: 0 if everything went fine; 1 if the plugin doesn't exist """ plugin_names = options.names allow_only = options.allow_only settings = ut...
e3b931fcd8f90e7570f80604d7690cf8c8485cd9
17,805
def compare_img_hist(img_path_1, img_path_2): """ Get the comparison result of the similarity by the histogram of the two images. This is suitable for checking whether the image is close in color. Conversely, it is not suitable for checking whether shapes are similar. Parameters ---------- ...
4fa34b3186b69464be15052a9427bb274f95d28f
17,806
import json def recombinant_example(resource_name, doc_type, indent=2, lang='json'): """ Return example data formatted for use in API documentation """ chromo = recombinant_get_chromo(resource_name) if chromo and doc_type in chromo.get('examples', {}): data = chromo['examples'][doc_type] ...
1a6cfe474425ba4d62472f571ca0eae0d3cfbff0
17,807
def _integral_diff(x, pdf, a, q): """Return difference between q and the integral of the function `pdf` between a and x. This is used for solving for the ppf.""" return integrate.quad(pdf, a, x)[0] - q
616cfba7361c92f7cbdf8bac55f9a65a60c2c32f
17,808
def Fcomplete(t,y,k0m,k1,k2m,k2p,k3,k4,k5m,k6m,k7,Kr0,Kr1,Kr2,Kr2p,Km5,Km6,Km7,Gt,Rt,Mt,k_Gp,Gpt,n): """ Right hand side of ODE y'(t) = f(t,y,...) It receives parameters as f_args, as given py param_array (see param.py) 3 components: G, R, M """ k0=k0m*Kr0 # kmi =ki/Kri or ki/Kmi k2=k2m*Kr2...
a6b614a34fb0c2dcaf29107c05eb397312825568
17,809
def lu_solve(l: np.ndarray, u: np.ndarray, b: np.ndarray) -> np.ndarray: """Решение СЛАУ, прошедшей через LU-разложение. Требуется предварительно умножить вектор правых частей на матрицу перестановки. :param l: нижняя треугольная матрица :param u: верхняя треугольная матрица :param b: вектор правых...
5429fe91dfb15a5cf306871d07f0204f8f23a405
17,810
def zr_bfr_tj(): """ Real Name: b'Zr bfr Tj' Original Eqn: b'Zr aftr Dam-Wr sup aftr Zr Dam+(Wr sup aftr Zr Dam*0.2)' Units: b'' Limits: (None, None) Type: component b'' """ return zr_aftr_dam() - wr_sup_aftr_zr_dam() + (wr_sup_aftr_zr_dam() * 0.2)
aae58ac349a7039afd0f3f3f12166a39de8afe31
17,812
def simplify(n): """Remove decimal places.""" return int(round(n))
9856c8f5c0448634956d1d05e44027da2f4ebe6a
17,813
def resnet_qc_18(**kwargs): """Constructs a ResNet-18 model.""" model = ResNetQC(BasicBlock, [2, 2, 2, 2], **kwargs) return model
a1554e044dd69e96474602c88e8e73d4d697c861
17,814
import scipy.sparse def sparse_from_npz(file, **_kw): """ Possible dispatch function for ``from_path_impl``'s ``from_npz``. Reads a scipy sparse matrix. """ return scipy.sparse.load_npz(file)
9909975ff0309cde98117e64718fe292de574987
17,815
import copy def get_config(): """ Read the configuration :returns: current configuration """ global config return copy.deepcopy(config)
3e9b064123ed9165c04cbc7e1c2b0d646703cb7a
17,816
def resnext20_2x64d_cifar100(classes=100, **kwargs): """ ResNeXt-20 (2x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 100 Number of classification classes. p...
147b9ff5565fdbbcaab68d66fbfa3e8a5a4b6062
17,817
def test_target(target): """Returns the label for the corresponding target in the test tree.""" label = to_label(target) test_package = label.package.replace("src/main/", "src/test/", 1) return Label("@{workspace}//{package}:{target_name}".format( workspace = label.workspace_name, packag...
8b4391a5acdea7b851ef6606ad3dfa0b21132ae1
17,818
def pred_fwd_rc(model, input_npy, output_fwd, output_rc, replicates=1, batch_size=512): """Predict pathogenic potentials from a preprocessed numpy array and its reverse-complement.""" y_fwd, _ = predict_npy(model, input_npy, output_fwd, rc=False, replicates=replicates, batch_size=batch_size) y_rc, _ = predi...
90ed6c3a29dd3e24cef45415ec51381bf32a8b37
17,819
def get_api_version(version_string): """Returns checked APIVersion object""" version_string = str(version_string) api_version = APIVersion(version_string) check_major_version(api_version) return api_version
9bbc88c3aee2139dc39367d4788d6c382f711903
17,821
def evaluate_g9( tau7, tau8, tau9, tau10, tau11, s9 ): """ Evaluate the ninth constraint equation and also return the Jacobian :param float tau7: The seventh tau parameter :param float tau8: The eighth tau parameter :param float tau9: The ninth tau parameter :param float tau10: The tenth tau pa...
9f8181e4d6abac9207eec721d6b347a560778ecf
17,822
def iterable(value, allow_empty = False, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs): """Validate that ``value`` is a valid iterable. .. hint:: This validator checks to ensure that ``value`` supp...
57de6a43243d9c611725f1e9987e881cf1485b63
17,824
from typing import List def settings_notification(color: bool, messages: List[ExitMessage]) -> Form: """Generate a warning notification for settings errors. :param messages: List of messages to display :param color: Bool to reflect if color is transferred or not :returns: The form to display """ ...
a1ff085c76e84e01ba293f17b662626a39fda26f
17,825
def message_type(ctx: 'Context', *types): """Filters massage_type with one of selected types. Assumes update_type one of message, edited_message, channel_post, edited_channel_post. :param ctx: :param types: :return: True or False """ m = None if ctx.update.update_type is UpdateType.me...
231bbb3b802d6f6dcf4a22af7704fae3ce24e783
17,826
import math def VSphere(R): """ Volume of a sphere or radius R. """ return 4. * math.pi * R * R * R / 3.
9e99d19683d9e86c2db79189809d24badccc197b
17,827
from typing import Optional from typing import Any def resolve_variable( var_name: str, var_def: BlueprintVariableTypeDef, provided_variable: Optional[Variable], blueprint_name: str, ) -> Any: """Resolve a provided variable value against the variable definition. Args: var_name: The na...
1df7d4804f104c8f746999aaaad5f91ca96b5f78
17,828
def additional_args(**kwargs): """ Additional command-line arguments. Provides additional command-line arguments that are unique to the extraction process. Returns ------- additional_args : dict Dictionary of tuples in the form (fixed,keyword) that can be passed to an argument...
1b0f10f7f9c60077de9c580163b5e3893da63a83
17,830
import html def extract_images_url(url, source): """ Extract image url for a chapter """ r = s.get(url) tree = html.fromstring(r.text) if source == 'blogtruyen': return tree.xpath('//*[@id="content"]/img/@src') elif source == 'nettruyen': return tree.xpath('//*[@class="read...
f2299d3e1dde38fc7ac2d3789e8145f5a71a1299
17,831
from typing import Dict from typing import Any from typing import Optional from typing import Literal from typing import List import pathlib def _ntuple_paths( general_path: str, region: Dict[str, Any], sample: Dict[str, Any], systematic: Dict[str, Any], template: Optional[Literal["Up", "Down"]], ...
efb96f1b977c30c83890c2030f312c0066eed4d8
17,832
def svn_ra_do_diff2(*args): """ svn_ra_do_diff2(svn_ra_session_t session, svn_revnum_t revision, char diff_target, svn_boolean_t recurse, svn_boolean_t ignore_ancestry, svn_boolean_t text_deltas, char versus_url, svn_delta_editor_t diff_editor, void diff_baton, apr_pool_t pool)...
8964a6304582daf5631e8e26c8cf7ff9167837dd
17,833
def ntuple_dict_length(ntuple_dict): """Returns a dictionary from track types to the number of tracks of that type. Raises an exception of any value lists within one of its track properties dicts are different lengths.""" return dict(map(lambda track_type, track_prop_dict: (track_type, track_pr...
e5f7805dfb4a641268792e4e8982e21a05298f9e
17,834
def range_ngram_distrib(text, n, top_most=-1): """ List n-grams with theis probabilities from the most popular to the smaller ones :param text: text :param n: n of n-gram :param top_most: count of most popular n-grams to be returned, or -1 to return all :return: list of ngrams, list of probs ...
0822b2e7824aee6cc28e2a734dea5d9aff0df1ac
17,835
import functools def require_methods(*methods): """Returns a decorator which produces an error unless request.method is one of |methods|. """ def decorator(func): @functools.wraps(func) def wrapped(request, *args, **kwds): if request.method not in methods: allowed = ', '.join(methods) ...
6c02675836c95f9ee7bab124cc1287bc6d3dfb95
17,837
def getUnit3d(prompt, default=None): """ Read a Unit3d for the termial with checking. This will accapt and directon in any format accepted by Unit3d().parseAngle() Allowed formats * x,y,z or [x,y,z] three floats * theta,psi or [theta,psi], in radians (quoted in "" for degrees) * theta in...
dd39a706114c72ce9059686e342e8a1db1e3464b
17,838
def checkOverlap(ra, rb): """ check the overlap of two anchors,ra=[chr,left_start,left_end,chr,right_start,right_end] """ if checkOneEndOverlap(ra[1], ra[2], rb[1], rb[2]) and checkOneEndOverlap( ra[4], ra[5], rb[4], rb[5]): return True return False
9644ed7e2de9d9091e21a64c7c4cd43a0e0e1210
17,839
import typing def saveable(item: praw.models.reddit.base.RedditBase) -> dict[str, typing.Any]: """Generate a saveable dict from an instance""" result = {k: legalize(v) for k, v in item.__dict__.items() if not k.startswith("_")} return _parent_ids_interpreted(result)
6e9e7092045e321de2beeba7debbd6dc2a2b2e61
17,840
import re def decode_Tex_accents(in_str): """Converts a string containing LaTex accents (i.e. "{\\`{O}}") to ASCII (i.e. "O"). Useful for correcting author names when bib entries were queried from web via doi :param in_str: input str to decode :type in_str: str :return: corrected string :...
2a4bd71b53cdab047a1ddd1e0e6fd6e9c81b0e0a
17,841
from typing import Mapping def tensor_dict_eq(dict1: Mapping, dict2: Mapping) -> bool: """Checks the equivalence between 2 dictionaries, that can contain torch Tensors as value. The dictionary can be nested with other dictionaries or lists, they will be checked recursively. :param dict1: Dictionary to co...
db3d7d23e633f5a240d0d0d13f6836494dc44e20
17,842
def calculate_stability(derivatives): """ Calculate the stability-axis derivatives with the body-axis derivatives. """ d = derivatives if 'stability' not in d: d['stability'] = {} slat = calculate_stability_lateral(d['body'], np.deg2rad(d['alpha0'])) slong = calculate_stability_longi...
888f63454265b3811751ae91654a9de083f25fec
17,843
from datetime import datetime def read_malmipsdetect(file_detect): """ This function is used to read the MALMI detection file which contains detection information, that is for each detected event how many stations are triggered, how many phases are triggered. Those information can be used for quality ...
cf42172e9f286254f31b2e57361c25360ed73d10
17,846
def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'): """Generates the URL for authorizing access. This uses the "OAuth2 for Installed Applications" flow described at https://developers.google.com/accounts/docs/OAuth2InstalledApp Args: client_id: Client ID obtained by registe...
b4471e78eab772a57be8d3073451050fd78d904c
17,847
def get_scorekeeper_details(): """Retrieve a list of scorekeeper and their corresponding appearances""" return scorekeepers.get_scorekeeper_details(database_connection)
78092d0ae6bcb21ee86a1fddfc678472c81eb55f
17,849
def layer_norm(input_tensor, axis): """Run layer normalization on the axis dimension of the tensor.""" layer_norma = tf.keras.layers.LayerNormalization(axis = axis) return layer_norma(input_tensor)
9687dedf8c3a624013c5188401e86d7ef6d73969
17,850
def compute_depth(disparity, focal_length, distance_between_cameras): """ Computes depth in meters Input: -Disparity in pixels -Focal Length in pixels -Distance between cameras in meters Output: -Depth in meters """ with np.errstate(divide='ignore'): #ignore division by 0 ...
5ea475dae1d4aa0c429a7f6766293a39d403904d
17,851
def lecture(source=None,target=None,fseed=100,fpercent=100): """ Create conversion of the source file and the target file Shuffle method is used, base on the seed (default 100) """ seed(fseed) try: copysource = [] copytarget = [] if(source!=None and target!=None)...
b0878ab2b3d888db984aa0644080578a85e9e554
17,852
def getScale(im, scale, max_scale=None): """ 获得图片的放缩比例 :param im: :param scale: :param max_scale: :return: """ f = float(scale) / min(im.shape[0], im.shape[1]) if max_scale != None and f * max(im.shape[0], im.shape[1]) > max_scale: f = float(max_scale) / max(im.shape[0], im.s...
52ae195714c1d39bccec553797bf6dbf2c6c2795
17,853
def load_swc(path): """Load swc morphology from file Used for sKCSD Parameters ---------- path : str Returns ------- morphology : np.array """ morphology = np.loadtxt(path) return morphology
0b0a4f82344b6c16180b4a52b1077a0f28966fde
17,854
def quintic_extrap((y1,y2,y3,y4,y5,y6), (x1,x2,x3,x4,x5,x6)): """ Quintic extrapolate from three x,y pairs to x = 0. y1,y2...: y values from x,y pairs. Note that these can be arrays of values. x1,x2...: x values from x,y pairs. These should be scalars. Returns extrapolated y at x=0. """ # ...
41090e09f2b7f58e98fa9fc91ea6000d70594046
17,856
def answer_question_interactively(question): """Returns True or False for t yes/no question to the user""" while True: answer = input(question + '? [Y or N]: ') if answer.lower() == 'y': return True elif answer.lower() == 'n': return False
52a123cc2237441de3b0243da268e53b7cc0d807
17,857
def connect( instance_id, database_id, project=None, credentials=None, pool=None, user_agent=None, ): """Creates a connection to a Google Cloud Spanner database. :type instance_id: str :param instance_id: The ID of the instance to connect to. :type database_id: str :param d...
7cff910615df346a5a503dec5e1938476cb701e6
17,858
from typing import List def intersect(linked_list_1: List, linked_list_2: List): """Intersection point of two linked list.""" length_diff = len(linked_list_1) - len(linked_list_2) enum1 = list(enumerate(linked_list_1)) enum2 = list(enumerate(linked_list_2)) if length_diff < 0: enum2 = _he...
dea64a6618ab3bda421250036e4eea8fa316a6ec
17,859
import torch def content_loss(sharp_images, deblur_images, cont_net): """ Computes the Content Loss to compare the reconstructed (deblurred) and the original(sharp) images Takes the output feature maps of the relu4_3 layer of pretrained VGG19 to compare the content between images as proposed in...
f55b4c22391d6e562afb927251fb6af267f9da08
17,861
def generate_cashflow_diagram( cashflows, d=None, net=False, scale=None, color=None, title=None, **kwargs): """ Generates a barplot showing cashflows over time Given a set of cashflows, produces a stacked barplot with bars at each period. The height of each bar is set by the amount of cash produced...
88afbd975a20041dccd24b8dc25899347a0b44ae
17,862
import collections def is_iterable(obj): # type: (Any) -> bool """ Returns True if obj is a non-string iterable """ if is_str(obj) is True or isinstance(obj, collections.Iterable) is False: return False else: return True
92db9be57250a53cf27118c9a4c91344a9d14fcb
17,863
def other_players(me, r): """Return a list of all players but me, in turn order starting after me""" return list(range(me+1, r.nPlayers)) + list(range(0, me))
5c2d2b03bfb3b99eb4c347319ccaaa3fc495b6c4
17,864
def mock_dd_slo_history(*args, **kwargs): """Mock Datadog response for datadog.api.ServiceLevelObjective.history.""" return load_fixture('dd_slo_history.json')
963fbbe20373e4e207852be82b88e33ca2c24e9a
17,865
import torch def check_joints2d_visibility_torch(joints2d, img_wh): """ Checks if 2D joints are within the image dimensions. """ vis = torch.ones(joints2d.shape[:2], device=joints2d.device, dtype=torch.bool) vis[joints2d[:, :, 0] > img_wh] = 0 vis[joints2d[:, :, 1] > img_wh] = 0 vis[joints...
a276d93a66dfd5bca15a684f652a0eede3094868
17,866
def getIntervalIntersectionLength(aa, bb, wrapAt=360): """Returns the length of the intersection between two intervals.""" intersection = getIntervalIntersection(aa, bb, wrapAt=wrapAt) if intersection is False: return 0.0 else: if wrapAt is None: return (intersection[1] - i...
46924c149e8b5b802fc83e489417850f3a8dbd18
17,867
def test_jvp_construct_single_input_single_output_default_v_graph(): """ Features: Function jvp Description: Test jvp with Cell construct, single input, single output and default v in graph mode. Expectation: No exception. """ x = Tensor(np.array([[1, 2], [3, 4]]).astype(np.float32)) v = Ten...
edd6b1c93dc880310fc0af2012d3fbfca328b64c
17,868
def get_environment() -> Environment: """ Parses environment variables and sets their defaults if they do not exist. """ return Environment( permission_url=get_endpoint("PERMISSION"), media_url=get_endpoint("MEDIA"), datastore_reader_url=get_endpoint("DATASTORE_READER"), ...
2ce9b56c76fadcd19a861f00e8d880a181b676ed
17,869
from typing import Optional def get_kubernetes_cluster(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKubernetesClusterResult: """ Use this data source to access informatio...
38beb9a7a96e51364f35c658d85428991e0686a8
17,870
def gene_expression_conv_base(): """Hparams for GeneExpressionConv model.""" hparams = common_hparams.basic_params1() batch_size = 10 output_length = 2048 inputs_per_output = 128 chunk_size = 4 input_length = output_length * inputs_per_output // chunk_size hparams.batch_size = input_length * batch_size...
7bd239fb511a7f72837a139f236557278f0c1dab
17,871
import typing from typing import _GenericAlias import collections def is_callable(type_def, allow_callable_class: bool = False) -> bool: """ Checks whether the ``type_def`` is a callable according to the following rules: 1. Functions are callable. 2. ``typing.Callable`` types are callable. 3. Gen...
68c51cfc4da4891c90c376e8ff1b26dc630a96de
17,872
def vgg19(pretrained=False, **kwargs): """VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_pretrained_model(model_zoo.load_url(model_urls['vgg19...
7c7e43eb46ffeb20fd5901d5761e11f701650727
17,873
def get_formats(input_f, input_case="cased", is_default=True): """ Adds various abbreviation format options to the list of acceptable input forms """ multiple_formats = load_labels(input_f) additional_options = [] for x, y in multiple_formats: if input_case == "lower_cased": ...
a20a02a7e85c1711d8b9d779e5804ed8e1dec83a
17,874
def db_select_entry(c, bibkey): """ Select entry from database :argument c: sqlite3 cursor :returns entry_dict: dict """ fields = ['bibkey', 'author', 'genre', 'thesis', 'hypothesis', 'method', 'finding', 'comment', 'img_linkstr'] sql = "SELECT {:s} FROM note WHERE ...
a93425aa2487f28bc3215a65ad1f963ea1173fcd
17,875
def to_bytes(obj, encoding='utf-8', errors='strict'): """Makes sure that a string is a byte string. Args: obj: An object to make sure is a byte string. encoding: The encoding to use to transform from a text string to a byte string. Defaults to using 'utf-8'. errors: The error handler to use if ...
4f8a0dcfdcfd3e2a77b5cbeedea4cb2a11acd4c1
17,876
def compact(number, strip_check_digit=True): """Convert the MEID number to the minimal (hexadecimal) representation. This strips grouping information, removes surrounding whitespace and converts to hexadecimal if needed. If the check digit is to be preserved and conversion is done a new check digit is r...
ced106ed8c97d432a8059d8654cfb437620deb64
17,878
from typing import List def hashtag_getter(doc: Doc) -> List[str]: """ Extract hashtags from text Args: doc (Doc): A SpaCy document Returns: List[str]: A list of hashtags Example: >>> from spacy.tokens import Doc >>> Doc.set_extension("hashtag", getter=dacy.utili...
a85c5cf9bd2fec2ec74e70bf2dadfb1df688c128
17,879
def options(): """Stub version of the parsed command line options.""" class StubOptions(object): profile = None return StubOptions()
dea85d2956eb6cbf97f870a74b122896915c8c19
17,880
def plot_bootstrap_delta_grp(dfboot, df, grp, force_xlim=None, title_add=''): """Plot delta between boostrap results, grouped""" count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling() if dfboot[grp].dtypes != 'object': dfboot = dfboot.copy() dfboot[...
1d9d25604392433bc9cc10d645f0a8f2122a2a38
17,882
from typing import Tuple from typing import Optional from typing import Dict from typing import Any def inception_inspired_reservoir_model( input_shape: Tuple[int, int, int], reservoir_weight: np.ndarray, num_output_channels: int, seed: Optional[int] = None, num_filters: int = 32, reservoir_ba...
221c0c17035d44178ca460c011c92d37f26b4ed4
17,883
def midnight(date): """Returns a copy of a date with the hour, minute, second, and millisecond fields set to zero. Args: date (Date): The starting date. Returns: Date: A new date, set to midnight of the day provided. """ return date.replace(hour=0, minute=0, second=0, microseco...
b92086dd9d99a4cea6657d37f40e68696ad41f7c
17,884
from typing import Callable from typing import Any from typing import Sequence def foldr(fun: Callable[[Any, Any], Any], acc: Any, seq: Sequence[Any]) -> Any: """Implementation of foldr in Python3. This is an implementation of the right-handed fold function from functional programming. If the list i...
5648d8ce8a2807270163ebcddad3f523f527986e
17,886
def tj_dom_dem(x): """ Real Name: b'Tj Dom Dem' Original Eqn: b'( [(1,0.08)-(365,0.09)],(1,0.08333),(2,0.08333),(3,0.08333),(4,0.08333),(5,0.08333),(6\\\\ ,0.08333),(7,0.08333),(8,0.08333),(9,0.08333),(10,0.08333),(11,0.08333),(12,0.08333\\\\ ),(13,0.08333),(14,0.08333),(15,0.08333),(16,0.08333),(17,0.08333...
df670af98362fd67bece677aa85bf37d31a75389
17,887
def filter_chants_without_volpiano(chants, logger=None): """Exclude all chants with an empty volpiano field""" has_volpiano = chants.volpiano.isnull() == False return chants[has_volpiano]
3f03bbf3f247afd3a115442e8121a773aa90fb56
17,888
def sample_input(): """Return the puzzle input and expected result for the part 1 example problem. """ lines = split_nonblank_lines(""" position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> veloci...
e027d2831ef5d16776b5c5f7bb8e759042056e2f
17,891
def vector_angle(v): """Angle between v and the positive x axis. Only works with 2-D vectors. returns: angle in radians """ assert len(v) == 2 x, y = v return np.arctan2(y, x)
4402795a27ca20269dbfa5a5823c4e2768681ed0
17,892
def get_user_record_tuple(param) -> (): """ Internal method for retrieving the user registration record from the DB. :return: """ conn = mariadb.connect(host=DB_URI, user=DB_USERNAME, password=DB_PASSWORD, database=DB_NAME) db = conn.cursor() # discord_id provided if isinstance(param, ...
d35468b7b2141f6c19f0c5669f80c103a7499221
17,893
def A_weighting(x, Fs): """A-weighting filter represented as polynomial transfer function. :returns: Tuple of `num` and `den`. See equation E.6 of the standard. """ f1 = _POLE_FREQUENCIES[1] f2 = _POLE_FREQUENCIES[2] f3 = _POLE_FREQUENCIES[3] f4 = _POLE_FREQUENCIES[4] offset = _NO...
a4592939d3809da292c4f05f47ca69e41ad9d27a
17,894
import inspect def register(class_=None, **kwargs): """Registers a dataset with segment specific hyperparameters. When passing keyword arguments to `register`, they are checked to be valid keyword arguments for the registered Dataset class constructor and are saved in the registry. Registered keyword...
f1ce9a7abc8224fcd4bd80cddbf0d46e11ee997a
17,895
import random def random_population(pop_size, tune_params, tuning_options, max_threads): """create a random population of pop_size unique members""" population = [] option_space = np.prod([len(v) for v in tune_params.values()]) assert pop_size < option_space while len(population) < pop_size: ...
b5f2fa518e29bdd6ccb5d10213080f9c594f01b0
17,896
def check_genome(genome): """Check if genome is a valid FASTA file or genomepy genome genome. Parameters ---------- genome : str Genome name or file to check. Returns ------- is_genome : bool """ try: Genome(genome) return True except Exception: ...
5f51d74203b77f39b0c8054d36fa6b68399540dd
17,897
def extract_row_loaded(): """extract_row as it should appear in memory""" result = {} result['classification_id'] = '91178981' result['user_name'] = 'MikeWalmsley' result['user_id'] = '290475' result['user_ip'] = '2c61707e96c97a759840' result['workflow_id'] = '6122' result['workflow_name...
c5fd87149ab7dff6e9980a898013053ce309c259
17,898
def getb_reginsn(*args): """ getb_reginsn(ins) -> minsn_t Skip assertions backward. @param ins (C++: const minsn_t *) """ return _ida_hexrays.getb_reginsn(*args)
04f0141c0053e74981264b90b3bb0be1fbea8c08
17,899
from solith.li_nofk.int_nofk import calc_jp1d, calc_nk1d def convolve_nk(myk, nkm, gfunc, klim, nk, kmin=0.02, kmax=1.5): """Convolve n(k) by going to J(p); apply resolution; and back. Args: myk (np.array): k nkm (np.array): n(k) gfunc (callable): resolution function klim (float): maxmimum kvalue...
7b7c782b35e1a58c104d4e5fef38f867f85ba014
17,900
def label_connected_components(label_images, start_label=1, is_3d=False): """Label connected components in a label image. Create new label images where labels are changed so that each \ connected componnent has a diffetent label. \ To find the connected components, it is used a 8-neighborhood. Par...
670a90421237718e263de23987c4d646e0669ae1
17,901
def metadataAbstractElementEmptyValuesTest1(): """ No empty values. >>> doctestMetadataAbstractElementFunction( ... testMetadataAbstractElementEmptyValue, ... metadataAbstractElementEmptyValuesTest1(), ... requiredAttributes=["required1"], ... optionalAttributes=["optional1"...
6504b570a49876dfdbb84be4b56bd87978aef22c
17,904
def broadcast_dynamic_shape(shape_x, shape_y): """Computes the shape of a broadcast given symbolic shapes. When shape_x and shape_y are Tensors representing shapes (i.e. the result of calling tf.shape on another Tensor) this computes a Tensor which is the shape of the result of a broadcasting op applied in ten...
3716b11f62712d4fedd4f1c997e2ad022178848b
17,905
def extract_args_for_httpie_main(context, method=None): """Transform a Context object to a list of arguments that can be passed to HTTPie main function. """ args = _extract_httpie_options(context) if method: args.append(method.upper()) args.append(context.url) args += _extract_http...
7e6b4f9ff3bc5bc9d44d3a7537063f4dc0965ab3
17,906
def apply_configuration(dist: "Distribution", filepath: _Path) -> "Distribution": """Apply the configuration from a ``setup.cfg`` file into an existing distribution object. """ _apply(dist, filepath) dist._finalize_requires() return dist
0c5f8c3a8d41faacaa1c8a5c13fafbb67e561f64
17,907