content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def download_from_url_if_not_in_cache(cloud_path: str, cache_dir: str = None): """ :param cloud_path: e.g., https://public-aristo-processes.s3-us-west-2.amazonaws.com/wiqa-model.tar.gz :param to_dir: will be regarded as a cache. :return: the path of file to which the file is downloaded. """ retu...
f0549e14b4219303ce48f992d684330338958370
3,648,800
from mne.viz.backends.renderer import _get_renderer from mne_connectivity.base import BaseConnectivity def plot_sensors_connectivity(info, con, picks=None, cbar_label='Connectivity'): """Visualize the sensor connectivity in 3D. Parameters ---------- info : dict | None ...
3d236d8e8802f65c6388eeeafa327a252f9a75be
3,648,801
import re import json def str_to_list_1(string): """ Parameters ---------- string : str The str of first line in each sample of sample.txt Returns --------- final_list: lst """ final_list = [] li = re.findall(r'\[...
92b4b11a339d2101a0af5408caee58cc9b9668a1
3,648,802
import torch def batched_nms(boxes, scores, idxs, iou_threshold): """ Same as torchvision.ops.boxes.batched_nms, but safer. """ assert boxes.shape[-1] == 4 # TODO may need better strategy. # Investigate after having a fully-cuda NMS op. if len(boxes) < 40000: return box_ops.batched...
2800d7e488fd018350c98c846138675b2ef79090
3,648,803
def one_mini_batch(data, batch_indices): """ 产生每一次的小的batch :param data: :param batch_indices: :return: """ batch_data = { "raw_data": [data[i] for i in batch_indices], "word_id_list": [], "label_vector": [] } for data in batch_data["raw_data"]: batch_d...
2bbbd62a00422431bb3322ebfce26d7fe95edc09
3,648,804
def reset_password(reset_key): """Checks the reset key. If successful, displays the password reset prompt.""" username = auth_utils.check_reset_key(reset_key) if username is None: flask.flash( 'Invalid request. If your link has expired, then you will need to generate a new one. ' ...
4f8e30a1669837c31b3dc2f77df441c50c6439dd
3,648,805
import scipy def williams_diff_test(corr_func: SummaryCorrFunc, X: np.ndarray, Y: np.ndarray, Z: np.ndarray, two_tailed: bool) -> float: """ Calculates the p-value for the difference in correlations using Williams' Tes...
afda90296b544233ba34f3abdd87d72b360de832
3,648,806
from typing import Tuple from typing import List import sqlite3 def load_students(max_meeting_seconds: int) -> Tuple[List[str], int]: """Loads student names and wait times from the database.""" try: with sqlite3.connect("students.db") as conn: cursor = conn.cursor() try: ...
b5b2a003216507df413cba7bea1171cd4667ee1f
3,648,807
def coords(gd0, c, pad=True): """Return coordinates along one of the three axes. Useful for plotting:: import matplotlib.pyplot as plt plt.plot(gd.coords(0), data[:, 0, 0]) plt.show() """ L = np.linalg.norm(gd0.cell_cv[c]) N = gd0.N_c[c] h = L / N p = gd0.pbc_c[c] or...
42541198f7a57fe6346b49eeaa4961336bd47c3a
3,648,808
def get_associated_genes(variants_list: list) -> pd.DataFrame: """ Get variant gene information from BioMart. More information on BioMart here: https://www.ensembl.org/info/data/biomart/index.html :param variants_list: the list with variant ids. :return: dataframe with variant and gene information ...
e267afb387496a99701872db94b46543e8c7406a
3,648,809
def crc16(data) : """Compute CRC16 for bytes/bytearray/memoryview data""" crc = _CRC16_START for b in data : crc = ((crc << 8) & 0xFFFF) ^ _CRC16_TABLE[(crc >> 8) ^ b] return crc
ac7dc27ebc47d1bc444050b9adba81d0ac26167a
3,648,810
def sigma(j: int, N: int = 1) -> np.ndarray: """ """ s = [s0, s1, s2, s3] dims = [4] * N idx = np.unravel_index(j, dims) return tensor(s[x] for x in idx)
c312222f5a037723f9b7920a971d93e36e3b3e4b
3,648,811
def backcasting( predictor, window, curves, distance="RMS", columns=("cases", "deaths"), min_series=14, step=1, ): """ Perform a backcasting performance analysis of the given model. For the sake of this method, the model is just a function that receives an epidemic curve data...
0e0eafc06ab6ab4578be1b299fc70ae88796a72d
3,648,812
from typing import Dict from typing import Callable from typing import List def find_keys(d: Dict[K, V], predicate: Callable[[V], bool]) -> List[K]: """Find keys where values match predicate.""" return [k for k, v in d.items() if predicate(v)]
68febd42bcd65ff52a786e4941dd5abf7d6a36ee
3,648,813
def get_maya_property_name(prop, ignore_channel=False): """ Given a property, return a reasonable Maya name to use for it. If ignore_channel is True, return the property for the whole vector, eg. return '.translate' instead of '.translateX'. This doesn't create or query anything. It just generates...
591a49f054db3936d5a345919a2c69491b6f345e
3,648,814
from typing import Concatenate def model_deepFlavourReference_test(Inputs,nclasses,dropoutRate=0.1,momentum=0.6): """ reference 1x1 convolutional model for 'deepFlavour' with recurrent layers and batch normalisation standard dropout rate it 0.1 should be trained for flavour prediction first. after...
f92f977a5570e647bf394d450bd5a5dea918aeba
3,648,815
import pathlib def load_spyrelet_class(spyrelet_name, cfg): """Load a spyrelet class from a file (whose location is defined in cfg)""" # discover spyrelet file and class spyrelet_path_str, _ = get_config_param(cfg, [CONFIG_SPYRELETS_KEY, spyrelet_name, CONFIG_SPYRELETS_FILE_KEY]) spyrelet_class_name, ...
877c8a626e7abe3e41146475dc030966c0b9f41e
3,648,816
def see_documentation(): """ This function redirects to the api documentation """ return jsonify({ '@context': responses.CONTEXT, 'rdfs:comment': 'See http://www.conceptnet.io for more information about ConceptNet, and http://api.conceptnet.io/docs for the API documentation.' })
46de921c855797b1b7d231a4cb88c57026ece947
3,648,817
import time def fit_imputer(df, tolerance=0.2, verbose=2, max_iter=20, nearest_features=20, imputation_order='ascending', initial_strategy='most_frequent'): """ A function to train an IterativeImputer using machine learning Args: df: dataset to impute tolerance: Tolerance ...
9ca798c61ee555ad7d58da16660aeb12518c9b7e
3,648,818
from django.shortcuts import render def jhtml_render(request, file_type=None,json_file_url=None, html_template=None, json_render_dict=None, json_render_func=None, file_path=None, url_name=None, app_name=None): """ :param request: :param file_type: json/temp_json :param json_file_url: :param html_...
b5d61d69a2c27d883aad60953c7366c6724b905e
3,648,819
import sys import os import tempfile def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name) if not os.path....
123f18287ae54bf257cbb74e0fe2d4bfca1df564
3,648,820
from PIL import Image import os def image(cache_path, width, height): """ Generate a custom-sized sample image """ # Create unique path size = (width, height) filename = "%sx%s.png" % (width, height) path = os.path.join(cache_path, filename) # Check if image has already been created if no...
df58a08937b5740fb5e4bc433f99c8de9b779c73
3,648,821
def truncate(text, length=30, indicator='...', whole_word=False): """Truncate ``text`` with replacement characters. ``length`` The maximum length of ``text`` before replacement ``indicator`` If ``text`` exceeds the ``length``, this string will replace the end of the string ``who...
82bf86407f57fc8f3524120c27c9231ad39ec2b2
3,648,822
def prefix_sums(A): """ This function calculate of sums of eements in given slice (contiguous segments of array). Its main idea uses prefix sums which are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array. Args: A: an array represents number of mushroom...
d61e49eb4a973f7718ccef864d8e09adf0e09ce2
3,648,823
from run4it.api.scripts import script_import_polar_exercices as script_func def polar_import(): """Import data from Polar and save as workouts""" return script_func('polar_import')
6a7075184e5c44a3092670fffc94360ef9a363c4
3,648,824
def dijkstra(G, Gextra, source, target_set, required_datarate, max_path_latency): """ :returns a successful path from source to a target from target_set with lowest path length """ q = DynamicPriorityQueue() q.put((source, 0.0), priority=0.0) marked = set() parents = {source: None} while not q.empty(): path_l...
6a8ff88b7a56308e099d3f9e50c8645c3281a68e
3,648,825
def build_single_class_dataset(name, class_ind=0, **dataset_params): """ wrapper for the base skeletor dataset loader `build_dataset` this will take in the same arguments, but the loader will only iterate over examples of the given class I'm just going to overwrite standard cifar loading data for n...
c8d05ecc1292562e846bc62724a224c20746037a
3,648,826
def gamma_trace(t): """ trace of a single line of gamma matrices Examples ======== >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \ gamma_trace, LorentzIndex >>> from sympy.tensor.tensor import tensor_indices, tensorhead >>> p, q = tensorhead('p, q', [LorentzInd...
8eb5bf4ba1f1d0e170a88a7b798b65273db8c1fd
3,648,827
import copy def preprocess(comment): """Pre-Process the comment""" copy_comment = copy.deepcopy(comment) # Replacing link final_comment = replace_link(copy_comment) nftokens = get_nf_tokens(comment) return final_comment, nftokens
f7286d5ca3e668b70385cd72485bb81eb8f9eec1
3,648,828
def voc_label_indices(colormap, colormap2label): """Map a RGB color to a label.""" colormap = colormap.astype('int32') idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256 + colormap[:, :, 2]) return colormap2label[idx]
481eccab328da13c4a49b2cf69d8e0e1cf1e48ab
3,648,829
def make_noisy_linear(w=1, std=1): """Factory for linear function <w,x> perturbed by gaussian noise N(0,std^2)""" @Oracle def noisy_linear(x): return np.dot(x, w) + np.random.normal(scale=std) return noisy_linear
80ec4a37dbbe6dc837707fa9a6e93e27d8dea9b9
3,648,830
def distance(turtle, x, y=None): """Return the distance from the turtle to (x,y) in turtle step units. Arguments: turtle -- the turtle x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distan...
f09b320c2b07374bebd2fd8c16084e7bf676523d
3,648,831
import copy def asy_ts(gp, anc_data): """ Returns a recommendation via TS in the asyuential setting. """ anc_data = copy(anc_data) # Always use a random optimiser with a vectorised sampler for TS. if anc_data.acq_opt_method != 'rand': anc_data.acq_opt_method = 'rand' anc_data.max_evals = 4 * anc_data....
1514263314cd92b053bfcd655872a03785b47af0
3,648,832
import re def checkParams(opts): """ 检查模块名是否符合命名规则 检查目录是否存在 """ res = {} for opt, arg in opts: if opt in ('--name'): if re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', arg): res['name'] = arg else: return res elif opt in ('--dir'): ...
5b8306a1c9805786e4a98509dcea3af59ffd04d1
3,648,833
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'): """ Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms """ best_bboxes = [] while len(bboxes) > 0: max_ind = np.argmax(bboxes[:, 4]) best_bbox = bboxes[max_ind] be...
10f3f65bd00599aa77f2d832754febfeeed7ca55
3,648,834
def smart_cast(value): """Intelligently cast the given value to a Python data type. :param value: The value to be cast. :type value: str """ # Handle integers first because is_bool() may interpret 0s and 1s as booleans. if is_integer(value, cast=True): return int(value) elif is_flo...
73676278e8c8bf54536fd3c9982cad7f6064cb75
3,648,835
from rdkit.Chem import Draw from rdkit.Chem import AllChem from IPython.display import SVG, display import io import matplotlib.pyplot as plt import matplotlib.image as mpimg def _draw_mol_with_property( mol, property, **kwargs ): """ http://rdkit.blogspot.com/2015/02/new-drawing-code.html Parameters ...
5f680f750b01d2f178df125dbaff6f737bbbcfc8
3,648,836
from typing import List from typing import Dict import math def find_host_biz_relations(bk_host_ids: List[int]) -> Dict: """ 查询主机所属拓扑关系 :param bk_host_ids: 主机ID列表 [1, 2, 3] :return: 主机所属拓扑关系 [ { "bk_biz_id": 3, "bk_host_id": 3, "bk_module_id": 59, "b...
9cd9891a97b5ad3db88a0e8a631775b1dc8c24c7
3,648,837
def atom_to_atom_line(atom): """Takes an atomium atom and turns it into a .cif ATOM record. :param Atom atom: the atom to read. :rtype: ``str``""" name = get_atom_name(atom) res_num, res_insert = split_residue_id(atom) return "ATOM {} {} {} . {} {} . {} {} {} {} {} 1 {} {} {} {} {} {} 1".forma...
30e9f9191947b23dffd9e3f6d63f697de325e5f0
3,648,838
from .....main import _get_bot from typing import Union from typing import Optional async def edit_chat_invite_link( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target channel (in the format @channelusername)'), ...
7c83316e0e86eb223b40ed9bf69126d79a4651b4
3,648,839
def post_live_migrate_at_source(adapter, host_uuid, instance, vif): """Performs the post live migrate on the source host. :param adapter: The pypowervm adapter. :param host_uuid: The host UUID for the PowerVM API. :param instance: The nova instance object. :param vif: The virtual interface of the i...
0a4165abe0373a96b2b222d4eaa9316649d607b2
3,648,840
import re def conv2date(dtstr,tstart=None): """Convert epoch string or time interval to matplotlib date""" #we possibly have a timeinterval as input so wrap in exception block m=re.search("([\+\-])([0-9]+)([dm])",dtstr) if m: if m.group(3) == "m": dt=30.5*float(m.group(2)) #s...
b848f45c04bf9ef77fa3af395afb992f6302fb4f
3,648,841
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(MaskedBasicblock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet...
94e339a390723e7dbdec4d95b7f4bb3600faae1f
3,648,842
def logioinfo(func): """ This function is to add IO information """ def write(exec_info): """ This function is to add bucket and object Io information Parameters: exec_info Returns: write """ log.info('in ...
ef8f1361e87cd246353debab11d7ad5c97f62058
3,648,843
import pytz def weather(api_token, city, start, end): """ Returns an hourly report of cloud cover, wind and temperature data for the given city. The report is always in full days. Timestamps are in UTC. Start and end dates are interpreted as UTC. """ a = Astral() city = a[city] # hour...
2d8457cc8388613825dad54686988194eed85b2b
3,648,844
from skimage.transform import iradon def skimage_radon_back_projector(sinogram, geometry, range, out=None): """Calculate forward projection using skimage. Parameters ---------- sinogram : `DiscreteLpElement` Sinogram (projections) to backproject. geometry : `Geometry` The projecti...
8158569eca46907091bfbca6aba57cd2a6afa6bf
3,648,845
def get_segment_hosts(master_port): """ """ gparray = GpArray.initFromCatalog( dbconn.DbURL(port=master_port), utility=True ) segments = GpArray.getSegmentsByHostName( gparray.getDbList() ) return segments.keys()
565921e4b7d46ec357666d50dee7dcdb7127759e
3,648,846
from typing import List from typing import Dict from typing import Any def get_saved_albums(sp: Spotify) -> List[Dict[str, Any]]: """Returns the list of albums saved in user library""" albums = [] # type: List[Dict[str, Any]] results = sp.current_user_saved_albums(limit=50) albums.extend(results["ite...
525074d9f957b71c0b355d3d343e088d29792363
3,648,847
def createMergerCatalog(hd_obj, obj_conditions, cosmo, time_since_merger=1): """ Function to create Major Merger (MM) catalog @hd_obj :: header file for the object of interest @obj_conditions :: prior conditions to define the object sample @cosmo :: cosmology used in the notebook (Flat Lambda CDM) ...
ee0ac59fe1a8fa9a40a934caa32ff53cd171f3dc
3,648,848
import subprocess def get_test_subprocess(cmd=None, **kwds): """Return a subprocess.Popen object to use in tests. By default stdout and stderr are redirected to /dev/null and the python interpreter is used as test process. It also attemps to make sure the process is in a reasonably initialized sta...
85d62aeb20b56c604199fc3c2812cf366e7fa1ee
3,648,849
from typing import Union from typing import Dict from typing import List from typing import Any import json def make_response(code: int, body: Union[Dict, List]) -> Dict[str, Any]: """Build a response. Args: code: HTTP response code. body: Python dictionary or list to jsonify. Returns: ...
bae0a8720085bdf3734724b00df8d856e362602a
3,648,850
def sql2dict(queryset): """Return a SQL alchemy style query result into a list of dicts. Args: queryset (object): The SQL alchemy result. Returns: result (list): The converted query set. """ if queryset is None: return [] return [record.__dict__ for record in queryset]
c55fa18773142cca591aac8ed6bdc37657569961
3,648,851
from typing import OrderedDict import itertools def build_DNN(input_dim, hidden_dim, num_hidden, embedding_dim=1, vocab_size=20,output_dim=1 ,activation_func=nn.Sigmoid): """ Function that automates the generation of a DNN by providing a template for pytorch's nn.Sequential class Parameters --------...
5b7476b20aacb0d6b0f78da6f97f9a1d3262d43c
3,648,852
def float_to_bin(x, m_digits:int): """ Convert a number x in range [0,1] to a binary string truncated to length m_digits arguments: x: float m_digits: integer return: x_bin: string The decimal representation of digits AFTER '0.' Ex: Input 0.75...
f95e72d9449b66681575b230f6c858e8b3833cc2
3,648,853
from typing import Callable from typing import List def apply(func: Callable, args: List): """Call `func` expanding `args`. Example: >>> def add(a, b): >>> return a + b >>> apply(add, [1, 2]) 3 """ return func(*args)
f866087d07c7c036b405f8d97ba993f12c392d76
3,648,854
def random_energy_model_create(db: Session) -> EnergyModelCreate: """ Generate a random energy model create request. """ dataset = fixed_existing_dataset(db) component_1 = fixed_existing_energy_source(db) return EnergyModelCreate(name=f"EnergyModel-{dataset.id}-" + random_lower_string(), ...
db5ac3decf6094bef271005732fd9b78a3870be3
3,648,855
def _indices_3d(f, y, x, py, px, t, nt, interp=True): """Compute time and space indices of parametric line in ``f`` function Parameters ---------- f : :obj:`func` Function computing values of parametric line for stacking y : :obj:`np.ndarray` Slow spatial axis (must be symmetrical a...
43a1f8761fb4e2ad32225ebf9e96f0aa2cdf0afd
3,648,856
def indicators_listing(request,option=None): """ Generate Indicator Listing template. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param option: Whether or not we should generate a CSV (yes if option is "csv") :type option: str :returns: ...
772ec90af7b104b4a9712742064d3aba758aab6f
3,648,857
def parse_sensor(csv): """ Ideally, the output from the sensors would be standardized and a simple list to dict conversion would be possible. However, there are differences between the sensors that need to be accommodated. """ lst = csv.split(";") sensor = lst[SENSOR_QUANTITY] if sen...
6673e12403090d130f0ac5590097794ae8f191aa
3,648,858
from datetime import datetime def samiljeol(year=None): """ :parm year: int :return: Independence Movement Day of Korea """ year = year if year else _year return datetime.date(int(year), 3, 1)
6ae717e12aa3dc5bd1d273e240294d2bc6a294ff
3,648,859
def get_entries(xml_file): """Get every entry from a given XML file: the words, their roots and their definitions. """ tree = get_tree(xml_file) # each <drv> is one entry entries = [] for drv_node in tree.iter('drv'): node_words = get_words_from_kap(drv_node.find('kap')) ro...
f9647cf79be68afa03908433890e1abbff9284bf
3,648,860
def comoving_radial_distance(cosmo, a, status): """comoving_radial_distance(cosmology cosmo, double a, int * status) -> double""" return _ccllib.comoving_radial_distance(cosmo, a, status)
72066b4b51a7728608d52c920bade33ecef0b920
3,648,861
import dateutil def make_legacy_date(date_str): """ Converts a date from the UTC format (used in api v3) to the form in api v2. :param date_str: :return: """ date_obj = dateutil.parser.parse(date_str) try: return date_obj.strftime('%Y%m%d') except: return None
5a2ed526c7bd0dae5a73a55c93d14ec158a0e6df
3,648,862
import torch def l2_mat(b1, b2): """b1 has size B x M x D, b2 has size b2 B x N x D, res has size P x M x N Args: b1: b2: Returns: """ b1_norm = b1.pow(2).sum(dim=-1, keepdim=True) b2_norm = b2.pow(2).sum(dim=-1, keepdim=True) res = torch.addmm(b2_norm.transpose(-2, -1),...
ad254c2c11dccab5dd97c7e72ef3b00c7b6143fb
3,648,863
import fnmatch import os def find_files(base, pattern): """Return list of files matching pattern in base folder.""" return [n for n in fnmatch.filter(os.listdir(base), pattern) if os.path.isfile(os.path.join(base, n))]
e84dd19e6746d92de1852f162eaa997734ac245c
3,648,864
def take_rich(frame, n, offset=0, columns=None): """ A take operation which also returns the schema, offset and count of the data. Not part of the "public" API, but used by other operations like inspect """ if n is None: data = frame.collect(columns) else: data = frame.take(n, of...
de3514d64a74addae76628c37f679693ba68550b
3,648,865
def default_name(class_or_fn): """Default name for a class or function. This is the naming function by default for registries expecting classes or functions. Args: class_or_fn: class or function to be named. Returns: Default name for registration. """ return camelcase_to_s...
1ed04a87916ae5d0fa9f1173d5fb9f97c26b32e9
3,648,866
import pathlib import shutil import random import logging def main(config_file: str, log_level: int) -> int: """Main function Parameters ---------- TODO """ coloredlogs.install( level=log_level * 10, logger=LOG, milliseconds=True, ) # Parse config file con...
8d176c597f28588a54c2e24016be0e2caf048c0d
3,648,867
def get_ip_result_by_input_method( set_input_method, module_input_method, var_ip_selector, username, bk_biz_id, bk_supplier_account, filter_set, filter_service_template, produce_method, var_module_name="", ): """ @summary 根据输入方式获取ip @param var_module_name: 模块属性名 @...
aa12179a5706f213894962579e5d0be30209f14e
3,648,868
from typing import cast from typing import Sized def function_size(container: Result) -> Result: """ The size() function applied to a Value. Delegate to Python's :py:func:`len`. (string) -> int string length (bytes) -> int bytes length (list(A)) -> int list size (map(A, B)) -> int map size ...
33470b886ba2a632c98d2de8342e8a793a5b1ac4
3,648,869
def cluster_from_metis_config(config): """ Construct a Cluster from a metis-flavored object. Args: config (dict): Metis data. Returns: Cluster """ curie_settings = curie_server_state_pb2.CurieSettings() cluster = curie_settings.Cluster() cluster.cluster_name = config["cluster.name"] log.info...
3c5abca482d89e7142129b2fb76accb2fc5aa5f2
3,648,870
def _single_style_loss(a, g): """ Calculate the style loss at a certain layer Inputs: a is the feature representation of the real image g is the feature representation of the generated image Output: the style loss at a certain layer (which is E_l in the paper) """ N = a.shape...
f19d8fcfc467d4760a44d2cdb872791cc2ad2ffe
3,648,871
def hyp_dist_o(x): """ Computes hyperbolic distance between x and the origin. """ x_norm = x.norm(dim=-1, p=2, keepdim=True) return 2 * arctanh(x_norm)
8864d8625798a8b41e2dd645cfe11e8d73d6d9d3
3,648,872
def check_image(url): """A little wrapper for the :func:`get_image_info` function. If the image doesn't match the ``flaskbb_config`` settings it will return a tuple with a the first value is the custom error message and the second value ``False`` for not passing the check. If the check is successful...
d0587dc987a079d49eb9a863d5203908acab41c4
3,648,873
def preprocess(dataset_file_path, len_bound, num_examples = None, reverse = False): """ It reads the required files, creates input output pairs. """ min_sentence_length = len_bound[0] max_sentence_length = len_bound[1] lines = open(str(dataset_file_path), encoding='utf-8', errors = 'ignore'...
5849c1957ccab997bcf835bce2fec71b0a93cd6d
3,648,874
def read_transcriptome(transcriptome): """ Parse transcriptome as a dictionary. """ result_dict = {} for sequence in SeqIO.parse(transcriptome, 'fasta'): result_dict[sequence.name] = sequence.seq return result_dict
008df223435de465cd6f36978305ca95bb15b270
3,648,875
from re import X def magnus(w, n): """ The 'Magnus' map """ expr = w.subs(x,1+eps*X).subs(y,1+eps*Y) - 1 return limit(expr / eps**n, eps, 0)
7faf1935b9348f41e6968b7da5fa59576ad874a5
3,648,876
import logging def initCmdLineParser(): """ Initiate the optparse object, add all the groups and general command line flags and returns the optparse object """ # Init parser and all general flags logging.debug("initiating command line option parser") usage = "usage: %prog [options]" p...
0a311909888b441bf6dfc559df6f31ea5a5c9c5a
3,648,877
def translate_node_coordinates(wn, offset_x, offset_y): """ Translate node coordinates Parameters ----------- wn: wntr WaterNetworkModel A WaterNetworkModel object offset_x: tuple Translation in the x direction, in meters offset_y: float Translation in ...
da886a624b9038296d47ffe85a04e62f71f49def
3,648,878
def get_demo_board(): """Get a demo board""" demo_board_id = 1 query = Board.query.filter(Board.id == demo_board_id) query = query.options(joinedload(Board.tasks)).options(raiseload('*')) board = query.one() return BoardDetailsSchema().dump(board).data
69b20a6c7446dc3813ec8d8c454a7a35443bf103
3,648,879
def cool_KI(n, T): """ Returns Koyama & Inutsuka (2002) cooling function """ return 2e-19*n*n*(np.exp(-1.184e5/(T + 1e3)) + 1.4e-9*T**0.5*np.exp(-92.0/T))
707b9e8d42e4d1b7db069c05b3b74e3f0b37f2e6
3,648,880
def main(args): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_query(rest) ...
b89e68c6ef98722a55ff15e8473dec8c8437bf8d
3,648,881
def compute_correlations(states): """compute_correlations. Calculate the average correlation of spin 0 and every other spin. Parameters ---------- states : list of states. ``len(states)`` must be >= 1! Returns ------- correlations : list of floats. """ return [ ...
471949aa63a3d65b262fb9dad1c77d160a3f5ac7
3,648,882
from typing import Sequence from typing import Any def parse_sample_str(elems: Sequence[Any]) -> AOList[str]: """ Choose n floats from a distribution. Examples: >>> c = parse_sample_str([4, ["choose", ["one", "two"]]]) >>> c Sample(4, ChooseS([StrConst('one'), StrConst('two')])) """ str...
5996a3b0ed072d4a7a00d7e01cc74efdc65aa8ee
3,648,883
def htlc(TMPL_RCV, TMPL_OWN, TMPL_FEE, TMPL_HASHIMG, TMPL_HASHFN, TMPL_TIMEOUT): """This contract implements a "hash time lock". The contract will approve transactions spending algos from itself under two circumstances: - If an argument arg_0 is passed to the script ...
9288458b228dabc1663901e03011feaa8ff9765c
3,648,884
def parse(*args, is_flag=False, **kwargs): """alias of parser.parse""" return _parser.parse(*args, is_flag=is_flag, **kwargs)
f40499277a12bd6e492e43fd7e4328124ac59814
3,648,885
def oauth_callback(): """ return: str """ auth = tweepy.OAuthHandler(env.TWITTER_API_KEY, env.TWITTER_API_SECRET) try: auth.request_token = session['REQUEST_TOKEN'] verifier = request.args.get('oauth_verifier') auth.get_access_token(verifier) session['AUTH_TOKEN'],ses...
a15d7c88c97b23a3ce625e363882fff3197c55b5
3,648,886
from typing import Tuple from typing import List import random def generate_random_instance(n_instants: int, cost_dim: int, items_per_instant: int = 1) -> \ Tuple[List[List[float]], List[List[List[float]]], float, float]: """Generates random values, costs and capacity for a Packing Problem instance. I...
57ccf4cd5410d2358c434d94beb9bfbb0ca04820
3,648,887
def recommend_tags_questions(professional_id, threshold=0.01, top=5): """ Recommends tags for an professional depending on answered questions. :param professional_id: ID of the professional :param threshold: Minimum percentage of questions with the tags. :param top: Top N recommende...
1b4bc6d37569d4794294028036e59437f66dc552
3,648,888
from .tools import make_simulationtable from .model import reservoirs def simulationtable(request): """ called when the simulation page starts to get used """ # convert to the right name syntax so you can get the COM ids from the database selected_reservoir = request.body.decode("utf-8") rese...
eaa60d02ee095d5efcc6a4f458bd4bb6745675d0
3,648,889
from datetime import datetime def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.head...
eed6504d712e91110763e28f400dab5faf9300a1
3,648,890
import numpy def plot_breakdown_percents(runs, event_labels=[], title=None, colors=None): """ Plots a bar chart with the percent of the total wall-time of all events for multiple runs. Parameters ---------- runs: Run object or list of Run objects The list of ...
788c0c466223a2e2aaa695c616fdfc649248b963
3,648,891
def gen3_file(mock_gen3_auth): """ Mock Gen3File with auth """ return Gen3File(endpoint=mock_gen3_auth.endpoint, auth_provider=mock_gen3_auth)
ee2af5d8b89c02e205101e0fe56dc58025d72e38
3,648,892
def rhs_of_rule(rule): """ This function takes a grammatical rule, and returns its RHS """ return rule[0]
004b99ac97c50f7b33cc798997463a28c3ae9a6f
3,648,893
from typing import Union from typing import Optional from typing import Any def flow_duration_curve( x: Union[np.ndarray, pd.Series], log: bool = True, plot: bool = True, non_exceeding:bool = True, ax: Optional[Union[SubplotBase, Any]] = None, **kwargs ) -> Uni...
3bec0159553a814ac4c68b198a29bf3075f6d202
3,648,894
def get_fields(filters): """ Return sql fields ready to be used on query """ fields = ( ("(SELECT p.posting_date FROM `tabPurchase Invoice` p Join `tabPurchase Invoice Item` i On p.name = i.parent WHERE i.item_code = `tabItem`.item_code And p.docstatus = 1 limit 1) as pinv_date"), ("CONCAT(`tabItem`._default_...
592d7c051e3af4cb510e43caa774054976f68865
3,648,895
from typing import Counter def count_POS_tag(df_pos): """Count how often each POS tag occurs Args: df_pos ([dataframe]): dataframe, where the entries are list of tuples (token, POS tag) Returns: df_pos_stats ([dataframe]): dataframe containing POS tag statistics """ # POS tag l...
a9ac14f34c020b78b02d6ae629cbddcdde39af8d
3,648,896
import json def catch_all(path): """ Gets dummy message. """ return json.dumps({ 'message': 'no one was here', 'ms': get_epochtime_ms() })
b93190b546705c1115c1612e4bd79210ab0d8f85
3,648,897
import os import zipfile def make_archive_obj(filepath, fileobj=None, inmemory_processing=True, allow_unsafe_extraction=False): """This method allows for smart opening of an archive file. Currently this method can handle tar and zip archives. For the tar files, if the python library has issues, the file is attempt...
7a5490b091ae0ca55c591fe16139d0df793a71e5
3,648,898
import typing from typing import List from functools import reduce def dimensions_to_space_time_index(dims, t_idx = (), t_len = (), s_idx = (), s_len = (), next_idx_valid = 0, invalid = False, min_port_width = 0, max_port_width = 0, total_time = 0,...
bdb24e237ba99288be98112db0f09d6782193594
3,648,899