content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def jaccard_similarity_coefficient(A, B, no_positives=1.0): """Returns the jaccard index/similarity coefficient between A and B. This should work for arrays of any dimensions. J = len(intersection(A,B)) / len(union(A,B)) To extend to probabilistic input, to compute the intersection, use ...
fe408565827f61323513d7d3b562bd79a23e47ec
13,700
def get_argument_from_call(call_node: astroid.Call, position: int = None, keyword: str = None) -> astroid.Name: """Returns the specified argument from a function call. :param astroid.Call call_node: Node representing a function call to check. :param int...
e4b7e054c4728f5b74bcbbe1678816a910f64bda
13,701
def snake_string(ls): """ Question 7.11: Write a string sinusoidally """ result = [] strlen = len(ls) for idx in xrange(1, strlen, 4): result.append(ls[idx]) for idx in xrange(0, strlen, 2): result.append(ls[idx]) for idx in xrange(3, strlen, 4): result.append(l...
391f7cef4289c5746f77598501aeaa7ae93d31bc
13,702
def _prepare_memoization_key(args, kwargs): """ Make a tuple of arguments which can be used as a key for a memoized function's lookup_table. If some object can't be hashed then used its __repr__ instead. """ key_list = [] for arg in args: try: hash(arg) key_li...
c83e08c42886ba0e7f6e4defe5bc8f53f5682657
13,703
def kl_divergence_with_logits(p_logits = None, q_logits = None, temperature = 1.): """Compute the KL between two categorical distributions from their logits. Args: p_logits: [..., dim] array with logits for the first distribution. q_logits: [..., ...
1950dea9e5c6d040ce464e0861b09469742810c4
13,704
from typing import Any from datetime import datetime def convert_bosch_datetime(dt: Any = None) -> datetime: """Create a datetime object from the string (or give back the datetime object) from Bosch. Checks if a valid number of milliseconds is sent.""" if dt: if isinstance(dt, str): if dt....
845e9de019b700b2ab37ebb4a1b577d0bd068638
13,705
def day_log_add_id(day_log): """ その日のログにID(day_id)を割り振る :param day_log: :return: """ for v in range(len(day_log)): day_log[v]['day_id'] = v + 1 return day_log
c4608b07e86c074a11cf78d171490ec152092eeb
13,706
def cisco_ios_l3_acl_parsed(): """Cisco IOS L3 Interface with ip address, acl, description and vlan.""" vlan = Vlan(id="300", encapsulation="dot1Q") ipv4 = IPv4(address="10.3.3.13", mask="255.255.255.128") acl_in = ACL(name="Common_Client_IN", direction="in") acl_out = ACL(name="TEST_ACL_03", direct...
25c7ad34695499bb6426ff71a9893c233b54a925
13,707
def brillance(p, g, m = 255): """ p < 0 : diminution de la brillance p > 0 : augmentation de la brillance """ if (p + g < m + 1) and (p + g > 0): return int(p + g) elif p + g <= 0: return 0 else: return m
b40169e487521c146c4c0777517492205951cf16
13,708
def fetch_fact(): """Parse the command parameters, validate them, and respond. Note: This URL must support HTTPS and serve a valid SSL certificate. """ # Parse the parameters you need token = request.form.get('token', None) # TODO: validate the token command = request.form.get('command', None) ...
8e5175b19d2548428e852dd9f476333dbe40481d
13,709
def payback(request): """ 微信支付回调函数 :param request: :return: """ return HttpResponse('payback')
e178abe0effe6359a664dca434e181390c1a56c1
13,710
from datetime import datetime def get_index_shares(name, end_date=None): """获取某一交易日的指数成分股列表 symbols = get_index_shares("上证50", "2019-01-01 09:30:00") """ if not end_date: end_date = datetime.now().strftime(date_fmt) else: end_date = pd.to_datetime(end_date).strftime(date_fmt) ...
7a9e2890d0508b00d15da4688980736776199cfa
13,711
def erfcx(x): """Elementwise scaled complementary error function. .. note:: Forward computation in CPU cannot be done if `SciPy <https://www.scipy.org/>`_ is not available. Args: x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable. Returns: ~chainer.Variable...
60f1655a6e390ca935f80d33e0d9156879b56c41
13,712
def fetch_data_async(blob, start_index, end_index, rpc=None): """Asynchronously fetches data for a blob. Fetches a fragment of a blob up to `MAX_BLOB_FETCH_SIZE` in length. Attempting to fetch a fragment that extends beyond the boundaries of the blob will return the amount of data from `start_index` until the ...
518f1ef45c19b8a7be55940d9abdeaf0fe014835
13,713
def get_legal_moves(color, size, board): """ Get Legal Moves """ legal_moves = {} for y in range(size): for x in range(size): reversibles = get_reversibles(color, size, board, x, y) if reversibles: legal_moves[(x, y)] = reversibles return legal_...
eaab0b7fededbe660b02974f675877b97e3327f4
13,714
def edition(self, key, value): """Translates edition indicator field.""" sub_a = clean_val("a", value, str) if sub_a: return sub_a.replace("ed.", "") raise IgnoreKey("edition")
715724dffb4ef6d72c173afbf8186acfdf9f20e3
13,715
from typing import Dict from typing import Set import itertools def get_site_data(hostname: str) -> SiteData: """Get metadata about a site from the API""" url = f"https://{hostname}/w/api.php" data = dict( action="query", meta="siteinfo", siprop="|".join( [ ...
83ca853c6fb2ebadf6473b8f5da0008b145717b0
13,716
def clear_monitor(nodenet_uid, monitor_uid): """Leaves the monitor intact, but deletes the current list of stored values.""" micropsi_core.runtime.get_nodenet(nodenet_uid).get_monitor(monitor_uid).clear() return True
ad39c344f41fcf307f85d09add71eeeac66b30c1
13,717
def loadGrammarFrom(filename, data=None): """Return the text of a grammar file loaded from the disk""" with open(filename, 'r') as f: text = f.read() lookup = mako.lookup.TemplateLookup(directories=[relativePath('grammars')]) template = mako.template.Template(text, lookup=lookup) # base_...
0a0bbd0f2af5db4c673d7dbd31259a3977adb9cf
13,718
def create_generator_selfatt(generator_inputs, generator_outputs_channels, flag_I=True): """ Add Conditional Self-Attention Modual to the U-Net Generator. By default, 256x256 => 256x256 Args: generator_inputs: a tensor of input images, [b, h, w, n], with each pixel value [-1, 1]. generator_...
bfcc81955c7849e84053c45ea7a593570059bf28
13,719
def by_tag(articles_by_tag, tag): """ Filter a list of (tag, articles) to list of articles by tag""" for a in articles_by_tag: if a[0].slug == tag: return a[1]
642472a89cb624ed02a6e8ec488b72856ac231a9
13,720
def experiment(dataset='SUPPORT', quantiles=(0.25, 0.5, 0.75), prot_att='race', groups=('black', 'white'), model='dcm', adj='KM', cv_folds=5, seed=100, hyperparams=None, plot=True, store=False): """Top level interface to train and evaluate proposed survival models. This is the top le...
79ec44d4d62a42dea4f7e612cd4291ce8fbc5585
13,721
def ldns_str2rdf_type(*args): """LDNS buffer.""" return _ldns.ldns_str2rdf_type(*args)
d121f8534c64b7597d775e5443b706c962ec738a
13,722
import hashlib import _crypt def scramble(password, message): """scramble message with password""" scramble_length = 20 sha_new = partial(hashlib.new, 'sha1') if not password: return b'' stage1 = sha_new(password).digest() stage2 = sha_new(stage1).digest() buf = sha_new() buf....
9ad006a5626d7b4ca3f8220dc4cbdd719a3cbac8
13,723
def dp_port_id(switch: str, port: str) -> str: """ Return a unique id of a DP switch port based on switch name and port name :param switch: :param port: :return: """ return 'port+' + switch + ':' + port
479891e41b51114744dcbb2b177180c19cd1bfd5
13,724
import requests def request_item(zip_code, only_return_po_boxes=False, spatial_reference='4326'): """ Request data for a single ZIP code, either routes or PO boxes. Note that the spatial reference '4326' returns latitudes and longitudes of results. """ url = BASE_URL.format( zip_code=str(...
956a2a86f0960a888046bfd5a8e3c2d7c56bc9dc
13,725
def smoothen_histogram(hist: np.array) -> np.array: """ Smoothens a histogram with an average filter. The filter as defined as multiple convolutions with a three-tap box filter [1, 1, 1] / 3. See AOS section 4.1.B. Args: hist: A histogram containing gradient orientation counts. ...
bdcc5de3df5aa2aad33653cce237f7f07d825b9d
13,726
from typing import Tuple def end_point(min_radius: float, max_radius: float) -> Tuple[int, int]: """ Generate a random goal that is reachable by the robot arm """ # Ensure theta is not 0 theta = (np.random.random() + np.finfo(float).eps) * 2 * np.pi # Ensure point is reachable r = np.rando...
8d6a79195108e8354fad986f93da5f089b6df0d7
13,727
def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
50adf652fff47418d1f8f1250a2a6d01f712da76
13,728
from typing import Mapping from typing import Any def parse_header( info: Mapping[str, Any], field_meta_data: Mapping[str, FieldMetaData], component_meta_data: Mapping[str, ComponentMetaData] ) -> Mapping[str, MessageMemberMetaData]: """Parse the header. Args: info (Mapping[st...
a8043c62070c540712074c60e01e3c9c3ebfe99b
13,729
def amina_choo(update, context): #3.2.1 """Show new choice of buttons""" query = update.callback_query bot = context.bot keyboard = [ [InlineKeyboardButton("Yes", callback_data='0'), InlineKeyboardButton("No", callback_data='00')], [InlineKeyboardButton("Back",callback_data='3....
b43d2e6d63e111b9a2f70fd71e5da765ef923746
13,730
def lighten(data, amt=0.10, is255=False): """Lighten a vector of colors by fraction `amt` of remaining possible intensity. New colors are calculated as:: >>> new_colors = data + amt*(1.0 - data) >>> new_colors[:, -1] = 1 # keep all alpha at 1.0 Parameters ---------- data : matplot...
195faa21ba30989f900b9b7f2b655a97074d8833
13,731
def _determine_function_name_type(node): """Determine the name type whose regex the a function's name should match. :param node: A function node. :returns: One of ('function', 'method', 'attr') """ if not node.is_method(): return 'function' if node.decorators: decorators = node....
d80cfd4aabdd79023d636c7425b04e747420ad36
13,732
from typing import Optional import platform import os import json def find_egl_engine_windows(association: str) -> Optional[UnrealEngine]: """Find Epic Games Launcher engine distribution from EngineAssociation string.""" if platform.system() != "Windows": return None if os.path.isfile(DAT_FILE): ...
c01ac3e18de3c851120847989ae5937cb7e81288
13,733
from typing import Tuple import datasets from typing import List from typing import Dict from re import T def create_dataset( template_path: str = 'com_github_corypaik_coda/projects/coda/data/coda/templates.yaml', objects_path: str = 'com_github_corypaik_coda/projects/coda/data/coda/objects.jsonl', ...
915bb616e165b55234f140f2ea1577644876ddb7
13,734
def escape_blog_content(data): """Экранирует описание блога.""" if not isinstance(data, binary): raise ValueError('data should be bytes') f1 = 0 f2 = 0 # Ищем начало блока div_begin = b'<div class="blog-description">' f1 = data.find(b'<div class="blog-content text">') if f1 >= 0...
285825b253de8ef9b67d7d3f1bdaa7a28f2e918c
13,735
import csv def read_csv(file_path, delimiter=",", encoding="utf-8"): """ Reads a CSV file Parameters ---------- file_path : str delimiter : str encoding : str Returns ------- collection """ with open(file_path, encoding=encoding) as file: data_in = list(csv....
a4f1da219b0e5d752ff606614e93abbfc3d30597
13,736
from typing import Tuple from pathlib import Path def get_cmd_items(pair: Tuple[str, Path]): """Return a list of Albert items - one per example.""" with open(pair[-1], "r") as f: lines = [li.strip() for li in f.readlines()] items = [] for i, li in enumerate(lines): if not li.startswi...
92d34ce5af3a3dbe162adf0766382120d0458c46
13,737
import importlib def import_activity_class(activity_name, reload=True): """ Given an activity subclass name as activity_name, attempt to lazy load the class when needed """ try: module_name = "activity." + activity_name importlib.import_module(module_name) return True e...
b4cea3fad1f08a5758972847d3e03a41f89f223c
13,738
def rgb2hsv(rgb): """ Reverse to :any:`hsv2rgb` """ eps = 1e-6 rgb = np.asarray(rgb).astype(float) maxc = rgb.max(axis=-1) minc = rgb.min(axis=-1) v = maxc s = (maxc - minc) / (maxc + eps) s[maxc <= eps] = 0.0 rc = (maxc - rgb[:, :, 0]) / (maxc - minc + eps) gc = (maxc - ...
febb268b1b691897c28447ff00a29785742dfc0c
13,739
def fig_colorbar(fig, collections, *args, **kwargs): """Add colorbar to the right on a figure.""" fig.subplots_adjust(right=0.8) cax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) cbar = fig.colorbar(collections, cax, *args, **kwargs) plt.pause(0.1) return cbar
a3156d24e28407938661c003d30b80a4d57638e6
13,740
def _merge_css_item(item): """Transform argument into a single list of string values.""" # Recurse lists and tuples to combine into single list if isinstance(item, (list, tuple)): return _merge_css_list(*item) # Cast to string, be sure to cast falsy values to '' item = "{}".format(item) if i...
c6f0c8769761640d5b0d98168cee1308f3209072
13,741
def extract_arguments(start, string): """ Return the list of arguments in the upcoming function parameter closure. Example: string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' arguments (output): '[{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, ...
8e6e3fecc0643aa3f55108916a7c6892a96f13aa
13,742
def augment_img(img): """Data augmentation with flipping and rotation""" # TODO: Rewrite with torchvision transform flip_idx = np.random.choice([0, 1, 2]) if flip_idx != 0: img = np.flip(img, axis=flip_idx) rot_idx = int(np.random.choice([0, 1, 2, 3])) img = np.rot90(img, k=rot_idx, axes...
4f124954b1dba8e27360a1c4664f0de46fd1a4d0
13,743
def iter_archive(path, method): """Iterate over an archive. Args: path: `str`, archive path method: `tfds.download.ExtractMethod`, extraction method Returns: An iterator of `(path_in_archive, f_obj)` """ return _EXTRACT_METHODS[method](path)
dda105efc20583f54aed26a55112cfc56380ad68
13,744
def unfoldPath(cwd, path): """ Unfold path applying os.path.expandvars and os.path.expanduser. Join 'path' with 'cwd' in the beginning If 'path' is not absolute path. Returns normalized absolute path. """ if not path: return path path = _expandvars(path) path = _expanduser(path...
ae11a69e6b2a3b0be4b3f266960d6004e99bd261
13,745
import os import sys import yaml def readConfig(config): """ This function reads configuration file and combine it with parameters from console input to generate the configuration list. Args: * config: configuration file to be readed Options: * keyfile (-k): str, path to a file c...
27d494c5e76f13def4785997565893caeddc59b2
13,746
import sys def main(argv): """Decide whether the needed jobs got satisfactory results.""" inputs = parse_inputs( raw_allowed_failures=argv[1], raw_allowed_skips=argv[2], raw_jobs=argv[3], ) jobs = inputs['jobs'] or {} jobs_allowed_to_fail = set(inputs['allowed_failures'] ...
4abc60eb17bc6ddb1e51611cecda7c1d2ecde686
13,747
def get_predictions(logits): """ Convert logits into softmax predictions """ probs = F.softmax(logits, dim=1) confidence, pred = probs.max(dim=1, keepdim=True) return confidence, pred, probs
c83a47140534e27bb14991d4c8b2192a2a02cd46
13,748
def lookup_capacity(lookup_table, environment, cell_type, frequency, bandwidth, generation, site_density): """ Use lookup table to find capacity by clutter environment geotype, frequency, bandwidth, technology generation and site density. """ if (environment, cell_type, frequency, bandwidth, ge...
c98b25611cf72cc202fea060063f3020732a5282
13,749
def contig_slow(fn, num): """brute force, quadratic""" data = parse(fn) for i in range(len(data)-2): for j in range(i + 2, len(data)-1): s = sum(data[i:j]) if s == num: return min(data[i:j]) + max(data[i:j])
69c086c605afc17a63def6e3958e340ddb7a32c3
13,750
def create_consts(*args) -> superclasses.PyteAugmentedArgList: """ Creates a new list of names. :param args: The args to use. """ return _create_validated(*args, name="consts")
b10ab2d0e30e5cfb54c284d4557a98c0b3eb69c6
13,751
def opts2constr_feat_gen(opts): """Creates ConstFeatPlanes functor by calling its constructor with parameters from opts. Args: opts (obj): Namespace object returned by parser with settings. Returns: const_feat_planes (obj): Instantiated ConstFeatPlanes functor. """ return Cons...
5f664aae10f0584aca14ff58d2a984c29fd0dc2d
13,752
def inhibit_activations(activations, times, window_length): """ Remove any activations within a specified time window following a previous activation. TODO - this is extremely slow for non-sparse activations Parameters ---------- activations : ndarray Provided activations times : nda...
5665ae196430d993d40f5f4941cecde0d79d7a80
13,753
def cmd_convert_items_to_cheetah_list(list): """ Cheetah templates can't iterate over a list of classes, so converts all data into a Cheetah-friendly list of tuples (NAME, DESCRIPTION, ENUM, HAS_BIT_OFFSET, BIT_OFFSET, BITS, TYPE, MIN, MAX, DEFAULT) """ temp = [] for i in list: ...
ff6933dce38d6ddcd74df72ce321d8f16dfd5074
13,754
def pose223(pose:gtsam.Pose2) -> gtsam.Pose3: """convert a gtsam.Pose2 to a gtsam.Pose3 Args: pose (gtsam.Pose2): the input 2D pose Returns: gtsam.Pose3: the 3D pose with zeros for the unkown values """ return gtsam.Pose3( gtsam.Rot3.Yaw(pose.theta()), gtsam.Point3(pose.x(...
0a6d738d9cbe035be55a884a1523c985d547f25f
13,755
import random def pivot_calibration_with_ransac(tracking_matrices, number_iterations, error_threshold, concensus_threshold, early_exit=False ): ...
0ce7c7bd8afbc88093793601da2b0333b40766cb
13,756
def find_companies_name_dict(): """ Finds companies names and addresses :return: a dict with resource name eg.area of companies and url of available data """ base = "https://data.gov.ro/api/3/action/" query = "Date-de-identificare-platitori" address = url_build.build_url_package_query(base,...
74526747f45a4c5491e4778759baca53a638c97f
13,757
import typing def error_to_response(request: web.Request, error: typing.Union[Error, ErrorList]): """ Convert an :class:`Error` or :class:`ErrorList` to JSON API response. :arg ~aiohttp.web.Request request: The web request instance. :arg typing.Union[Error, ErrorList] er...
792c3fccd8d7fee708d850169fd943010e92ab05
13,758
def read(handle): """read(handle)""" record = Record() __read_version(record, handle) __read_database_and_motifs(record, handle) __read_section_i(record, handle) __read_section_ii(record, handle) __read_section_iii(record, handle) return record
90921ec1779c313505a838863509838bd858d0b7
13,759
import json def validate_telegam(): """Validate telegram token and chat ID """ configs = InitialConfig() confs = ["chat_id", "bot_token"] conf_dict = {} if request.method == "GET": for conf in confs: conf_dict[conf] = getattr(configs, conf) conf_json = json.dump...
f597d75672639dc2a39eb100f7221c508f62cf06
13,760
def hour(e): """ :rtype: Column """ return col(Hour(ensure_column(e)))
492d9e21f2f7c3fd6107dd4000c8273efaa0357c
13,761
def infer_gaussian(data): """ Return (amplitude, x_0, y_0, width), where width - rough estimate of gaussian width """ amplitude = data.max() x_0, y_0 = np.unravel_index(np.argmax(data), np.shape(data)) row = data[x_0, :] column = data[:, y_0] x_0 = float(x_0) y_0 = float(y_0) ...
784e88e5cd58def8467cbe0a851b37cc1fefe9dd
13,762
import math def extract_freq(bins=5, **kwargs): """ Extract frequency bin features. Args: bins (int): The number of frequency bins (besides OOV) Returns: (function): A feature extraction function that returns the log of the \ count of query tokens within each frequency bi...
b07f2f1810a26c2d04366d5516aac0ca79b547bb
13,763
import typing def create_private_key_params(key_type: str) -> typing.Type[PrivateKeyParams]: """Returns the class corresponding to private key parameters objects of the given key type name. Args: key_type The name of the OpenSSH key type. Returns: The subclass of :any:`Pr...
6702f93f8cd8dc3fd104db5d63efd7db4bbaa38e
13,764
import json import requests def get_response(msg): """ 访问图灵机器人openApi :param msg 用户输入的文本消息 :return string or None """ apiurl = "http://openapi.tuling123.com/openapi/api/v2" # 构造请求参数实体 params = {"reqType": 0, "perception": { "inputText": { ...
9a542b56a3ed3db8b8a9306ea3d425054a4ca64b
13,765
import torch def lm_sample_with_constraints(lm_model, max_decode_steps, use_cuda, device, batch_size=1, alpha_0=1, alpha=1, ...
cbccd2c0a2b91fa3e5ff5efb8b394fe7418f5b8b
13,766
import torch import tqdm def validate_official(args, data_loader, model, global_stats=None): """Run one full official validation. Uses exact spans and same exact match/F1 score computation as in the SQuAD script. Extra arguments: offsets: The character start/end indices for the tokens in each cont...
09385e491c25ac238aebabe7d887f73b4c0bd091
13,767
def tuple_list_to_lua(tuple_list): """Given a list of tuples, return a lua table of tables""" def table(it): return "{" + ",".join(map(str, it)) + "}" return table(table(t) for t in tuple_list)
71ec1a29f5e23b8bf82867617fe157fbba4a2332
13,768
def reset_user_messages(request: Request): """ For given user reset his notifications. """ profile: Profile = get_object_or_404(Profile, user=request.user) profile.messages = 0 profile.save() return Response(status=status.HTTP_200_OK)
628347dea707b0bd2ecc63cc004a3f62cb85e967
13,769
import functools def define_scope(function, scope=None, *args, **kwargs): """ A decorator for functions that define TensorFlow operations. The wrapped function will only be executed once. Subsequent calls to it will directly return the result so that operations are added to the graph only once. Th...
988f2f711dc227bfe8df5c7074d354c37d079fdb
13,770
from typing import Union from typing import List from typing import Dict import yaml from typing import OrderedDict def load_yaml(fname: str) -> Union[List, Dict]: """Load a YAML file.""" try: with open(fname, encoding='utf-8') as conf_file: # If configuration file is empty YAML returns No...
5fd0b9d2dea7d07b7bb98f6a9ae3ce98be3962e0
13,771
def fancy_vector(v): """ Returns a given 3-vector or array in a cute way on the shell, if you use 'print' on the return value. """ return "\n / %5.2F \\\n" % (v[0]) + \ " | %5.2F |\n" % (v[1]) + \ " \\ %5.2F /\n" % (v[2])
2340f22aa87da00abad30b9946c374f34b38496d
13,772
def findpath_split(seq, ss1, ss2, md, th = 5, w = None): """ Calculate findpath barriers for smaller components. Args: seq: RNA sequence. ss1: Structure 1. ss2: Structure 2. md: ViennaRNA model details. th: Threshold of how many basepairs must change for an independent f...
2d52102df31dd014ac60e28c7258bff833353b6a
13,773
def get_root_relative_url(url_path): """Remove the root page slug from the URL path""" return _clean_rel_url('/'.join(url_path.split('/')[2:]))
7aca9c0ec8856615fe1777117f44a259d7b597c7
13,774
import os import subprocess def run_command(command, split=False, include_errors=False, cwd=None, shell=False, env=None): """Run command in subprocess and return exit code and output""" sub_env = os.environ.copy() if env is not None: sub_env.update(env) if include_errors: error_pipe = ...
f3d4c0c1180a513872d6821a763495f1b97e85ee
13,775
def exclusion_windows_matching(match_peaks): """ Discard the occurrences of matching and non-matchign ions when they are found in the window (+-losses_window_removal) around M-xx or free bases ions """ output_dic = match_peaks for key in match_peaks: if match_peaks[key]: fo...
9c2b5bcdb283b197102d50fdd2aaa8eb49e2fc3b
13,776
def any_of(elements): """ Check to see if the argument is contained in a list of possible elements. :param elements: The elements to check the argument against in the predicate. :return: A predicate to check if the argument is a constituent element. """ def predicate(argument): return a...
adacf8fd632d25452d22dab0a8a439021083ec83
13,777
def find_year(films_lst: list, year: int): """ Filter list of films by given year """ filtered_films_lst = [line for line in films_lst if line[1] == str(year)] return filtered_films_lst
f4c11e09e76831afcf49154234dd57044536bce1
13,778
def func_BarPS(HA_Open, HA_Close, HA_PS_Lookback, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False): """ 0. This function is for calculating price trend number of HA bar, by looking back HA_PS_Lookback HA bars, according to the previous bars' distribution, find the range (i.e. -4,-3,-2,-1,0,1,2,3,4) o...
8a57de8ee4e832afd6327afc808668d227bc2592
13,779
from typing import List def filter_whitespace(stream: List[Part]) -> List[Part]: """Remove whitespace tokens""" return flu(stream).filter(lambda x: x.token != Token.WHITESPACE).collect()
aa3b8d109b0d85db7c3aa286858426276afb80ba
13,780
def merge_partial_dicts(interfaces_dict, partials_dict): """Merges partial interface into non-partial interface. Args: interfaces_dict: A dict of the non-partial interfaces. partial_dict: A dict of partial interfaces. Returns: A merged dictionary of |interface_dict| with |partial_dict|. ...
7efc47325e1af5c06b19c1bba02ec8b53d9473e0
13,781
def gen_code_def_part(metadata): """生成代码中定义类的部分。 """ class_def_dict = validate(metadata) class_def_list = list(class_def_dict.values()) code = templates.t_def_all_class.render(class_def_list=class_def_list) return code
df01fb69984a0ba471a6e5ac24bbecb0a622dd1b
13,782
def clang_plusplus_frontend(input_file, args): """Generate LLVM IR from C++ language source(s).""" compile_command = default_clang_compile_command(args) compile_command[0] = llvm_exact_bin('clang++') return compile_to_bc(input_file, compile_command, args)
1b2701f3e0fac240843b302dd2056bac857ecb74
13,783
from django.db.models import Model def create_forward_many_to_many_manager(superclass, rel, reverse): """ Create a manager for the either side of a many-to-many relation. This manager subclasses another manager, generally the default manager of the related model, and adds behaviors specific to many-t...
c9c45ae0eca4a913affab0ed832a0568e46d9a4c
13,784
def grp_render_dashboard_module(context, module, index=None, subindex=None): """ Template tag that renders a given dashboard module, it takes a ``DashboardModule`` instance as first parameter and an integer ``index`` as second parameter, that is the index of the module in the dashboard. """ ...
515bf427c4c39dc28479f6fe7121dc1cb542745e
13,785
def serialize_routing(value, explicit_type=None): """Custom logic to find matching serialize implementation and returns it's unique registration string key :param value: instance to serialize :param explicit_type: explicit serialization type for value :return: str key to find proper serialize im...
792cb24fc68060fe7e24f064f411752c5d787c3d
13,786
def get_projection_matricies(az, el, distance_ratio, roll = 0, focal_length=35, img_w=137, img_h=137): """ Calculate 4x3 3D to 2D projection matrix given viewpoint parameters. Code from "https://github.com/Xharlie/DISN" """ F_MM = focal_length # Focal length SENSOR_SIZE_MM = 32. PIXEL_ASPE...
a8ef5852510982851487e349336e41e61f7b582e
13,787
def pix_to_coord(edges, pix, interp="lin"): """Convert pixel coordinates to grid coordinates using the chosen interpolation scheme.""" scale = interpolation_scale(interp) interp_fn = interp1d( np.arange(len(edges), dtype=float), scale(edges), fill_value="extrapolate" ) return scale.inv...
db9fcc47a273e9b39f6d5b6a39b59146866e5dd4
13,788
def create_action_urls(actions, model=None, **url_args): """ Creates a list of URLs for the given actions. """ urls = {} if len(actions) > 0: # Resolve the url_args values as attributes from the model values = {} for arg in url_args: values[arg] = getattr(model, u...
f26477e0d046bfe6f73f25b2b086fad3b05a2646
13,789
def check_vfvx(x0, fx, fx_args, dfx, dfx_args=None, delta=1e-5): """ Check derivatives of a (vectorized) vector or scalar function of a vector variable. """ if x0.ndim != 2: raise ValueError('The variable must have two dimensions!') if dfx_args is None: dfx_args = fx_args d...
a8cffcbf118394a1ea5d65835bade516035fe9fe
13,790
def add_hovertool(p1, cr_traj, traj_src, sat_src, traj_df): """Adds a hovertool to the top panel of the data visualization tool plot.""" # Create the JS callback for vertical line on radar plots. callback_htool = CustomJS(args={'traj_src':traj_src,'sat_src':sat_src}, code=""" const indices = cb_d...
f45245df7cd81ee8f0fc486d460be0c4338fd921
13,791
def backpage_url_to_sitekey(url): """http://longisland.backpage.com/FemaleEscorts/s-mny-oo-chics-but-oo-nn-lik-oo-me-19/40317377""" (scheme, netloc, path, params, query, fragment) = urlparse(url) sitekey = netloc.split('.')[0] return sitekey
6efa6d0bf73ab297144a7c6a35dbba920f77789e
13,792
import torch def batch_eye_like(X: torch.Tensor): """Return batch of identity matrices like given batch of matrices `X`.""" return torch.eye(*X.shape[1:], out=torch.empty_like(X))[None, :, :].repeat(X.size(0), 1, 1)
266ee5639ce303b81e2cb82892e64f37a09695ff
13,793
def cal_occurence(correspoding_text_number_list): """ calcualte each occurence of a number in a list """ di = dict() for i in correspoding_text_number_list: i = str(i) s = di.get(i, 0) if s == 0: di[i] = 1 else: di[i] = di[i] + 1 return di
aafabc6abdf4bf1df1b8d9e23a4af375df3ac75b
13,794
def subtract(v: Vector, w: Vector) -> Vector: """simple vector subtraction""" assert len(v) == len(w), 'Vectors need to have the same length' return [vi - wi for vi, wi in zip(v, w)]
c6f8a9b19e07206a4d2637557c721bd97ad56363
13,795
from re import I def f1(): """ Filtering 1D. """ # Get center of the filter c = int((size - 1) / 2) # Pad the flatten (1D array) image with wrapping If = np.pad(I.flatten(), (c), 'wrap') # Initialize the resulting image Ir = np.zeros(If.shape) # Apply 1D convulation in the image for x in range(c...
cc50f089148cdbaffbbdc7d6d734a066a6b08722
13,796
from typing import Optional def _unify_data_and_user_kwargs( data: 'LayerData', kwargs: Optional[dict] = None, layer_type: Optional[str] = None, fallback_name: str = None, ) -> 'FullLayerData': """Merge data returned from plugins with options specified by user. If ``data == (_data, _meta, _ty...
c0d472ef60bf69d67ef50d435715bfabe11c229e
13,797
def get_sentence_embeddings(data): """ data -> list: list of text """ features = temb.batch_tokenize(data, tokenizer) dataset = temb.prepare_dataset(features) embeddings = temb.compute_embeddings(dataset, model) return embeddings
cb1badd5cf9a244d7af8b40d219a467d0dff811e
13,798
def sample_user(phone="+989123456789", full_name="testname"): """ Create a sample user """ return get_user_model().objects.create_user(phone=phone, full_name=full_name)
418b12b4249c4beda4fed36664f2c9eb14f8adc4
13,799