content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def add_data( dates=None, product="AOD15", *, inv_type=None, latlonbox=None, siteid=None, daily=False, lunar=False, # # post-proc freq=None, detect_dust=False, interp_to_aod_values=None, # # joblib n_procs=1, verbose=10, ): """Load AERONET data fro...
a5ef56efa84d64b569a2ecb506f541d4556c7391
23,600
def _func(*args, **kwargs): """Test function used in some tests.""" return args, kwargs
7fb2aa947806578e5378e66ce7dc1b4f3f593dbe
23,601
def combine_parallel_circuits(IVprev_cols, pvconst): """ Combine crosstied circuits in a substring :param IVprev_cols: lists of IV curves of crosstied and series circuits :return: """ # combine crosstied circuits Irows, Vrows = [], [] Isc_rows, Imax_rows = [], [] for IVcols in zip(*...
31d6a96189b703bca0e9cf212472cb0c8870d3cd
23,602
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str, module_file: str, serving_model_dir: str, metadata_path: str) -> tfx.dsl.Pipeline: """Creates a three component penguin pipeline with TFX.""" # Brings data into the pipeline. example_gen = tfx.co...
6254505a2d0309a8576a277b95a521294f9f8901
23,603
def create_global_step() -> tf.Variable: """Creates a `tf.Variable` suitable for use as a global step counter. Creating and managing a global step variable may be necessary for `AbstractTrainer` subclasses that perform multiple parameter updates per `Controller` "step", or use different optimizers on different...
d1fc499b60d09d50e555977b73eec04971e11b3b
23,604
def supported_coins_balance(balance, tickers): """ Return the balance with non-supported coins removed """ supported_coins_balance = {} for coin in balance.keys(): if coin != "BTC": if f"{coin}/BTC" in tickers: supported_coins_balance[coin] = balance[coin] ...
aaea856c728d04f47f52c1b07c66be57ff17d8cf
23,605
def _identity_map(size): """Function returning list of lambdas mapping vector to itself.""" return [lambda x, id: x[id] for _ in range(size)]
6236d42d359fdc9b006bffcc597fccbc161eb53d
23,606
def With(prop, val): """The 'with <property> <value>' specifier. Specifies the given property, with no dependencies. """ return Specifier(prop, val)
fc4a167322ab5bde74eabf1b69efb5d37f643405
23,607
def pad_node_id(node_id: np.uint64) -> str: """ Pad node id to 20 digits :param node_id: int :return: str """ return "%.20d" % node_id
28cdaad2aa327143432c5be58598271139574a50
23,608
def ballcurve(x: ArrayLike, xi: float) -> ArrayLike: """ function to generate the curve for the nested structure, given a shape parameter xi. If xi= 1 is linear. input: ---------- x: 1D array, [0,1] initial values to be evaluated on the function xi: number, >=1 shape paramete...
6b261793e1bdccc39bc66f25f4013d07d3bfc376
23,609
def center_vertices(vertices, faces, flip_y=True): """ Centroid-align vertices. Args: vertices (V x 3): Vertices. faces (F x 3): Faces. flip_y (bool): If True, flips y verts to keep with image coordinates convention. Returns: vertices, faces """ vertices = verti...
85743c3b3e3838533e78c66b137cc9c8c7702519
23,610
def fingerprint_atompair(fpSize=2048, count=False): """Atom pair fingerprint (list of int). Args: fpSize: Size of the generated fingerprint (defaults to 2048). count: The default value of False will generate fingerprint bits (0 or 1) whereas a value of True will generate the count o...
cbacf8bdaae11520f2bb71ae825ea574258f6242
23,611
def bend_euler_s(**kwargs) -> Component: """Sbend made of euler bends.""" c = Component() b = bend_euler(**kwargs) b1 = c.add_ref(b) b2 = c.add_ref(b) b2.mirror() b2.connect("o1", b1.ports["o2"]) c.add_port("o1", port=b1.ports["o1"]) c.add_port("o2", port=b2.ports["o2"]) return c
55c3d4dc5cc2766463f088ede2b4f04c6018eac6
23,612
def phot_error(star_ADU,n_pix,n_b,sky_ADU,dark,read,gain=1.0): """ Photometric error including INPUT: star_ADU - stellar flux in ADU (total ADU counts within aperture) n_pix - number of pixels in aperture n_b - number of background pixels sky_ADU - in ADU/pix dark ...
45d3f335c2b7fad1e2e0f8e8e415a0bda0f774e8
23,613
def tan(x): """ tan(x) -> number Return the tangent of x; x in radians. """ try: res, x = _init_check_mpfr(x) gmp.mpfr_tan(res, x, gmp.MPFR_RNDN) return mpfr._from_c_mpfr(res) except TypeError: res, x = _init_check_mpc(x) gmp.mpc_tan(res, x, gmp.MPC_RNDNN...
651119ccd44f313b25f49e03a3f5094fa1c1a829
23,614
def test_wrapped_func(): """ Test uncertainty-aware functions obtained through wrapping. """ ######################################## # Function which can automatically handle numbers with # uncertainties: def f_auto_unc(angle, *list_var): return umath.cos(angle) + sum(list_var) ...
9f432e6fd0c796c733e43c2ca66d2d0373148ee4
23,615
def T2str_mag_simplified(K, TE, T2str, N): """Signal Model of T2str-weighted UTE GRE Magnitude Image S = K * [ exp(-TE/T2*) ] + N parameters: K :: constant (proportional to proton density) TE :: sequence echo time T2str :: relaxation due to spin-spin effects and dephasing N...
ddf829cf8e209602b141f1b13c8fbf5af566a8d7
23,616
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
099b5e513ab52353efbce8ba1e7465acf5b1f6bc
23,617
def getTimeString(t, centi=True): """ category: General Utility Functions Given a value in milliseconds, returns a Lstr with: (hours if > 0):minutes:seconds:centiseconds. WARNING: this Lstr value is somewhat large so don't use this to repeatedly update node values in a timer/etc. For that p...
12cbcf4fcfd8450af110f93c77c4c5b50285c0fd
23,618
def validation_supervised(model, input_tensor, y_true, loss_fn, multiclass =False, n_classes= 1): """ Returns average loss for an input batch of data with a supervised model. If running on multiclass mode, it also returns the accuracy. """ y_pred = model(input_tensor.float()) if multiclass: ...
901f4416fab5ebc23115ef2f3aab1b971607368e
23,619
import logging import sys def configure_logger(app): """ logging: based on the configured setting we :param app: :return: """ # # support stream and rotating handlers logger = app.logger logger.setLevel(logging.INFO) if app.config['HANDLER'] == "StreamHandler": class In...
163d9e8e81ddeae7121c1e9cf20b00a1db4d10f0
23,620
def timing(func=None, *, name=None, is_stage=None): """ Decorator to measure the time taken by the function to execute :param func: Function :param name: Display Name of the function for which the time is being calculated :param is_stage: Identifier for mining stage Examples: ...
e7368e64bda81811075a295b6e36f0f9e9e7bcd5
23,621
def is_skip_file(filename): """ Should the given file be skipped over for testing :param filename: The file's name :type filename: String :return: True if the given file should be skipped, false otherwise :rtype: Boolean """ filename_len = len(filename) for skip_name in SKIP_FILES: ...
066bcfbff6f984fb293c422f613746967713b31b
23,622
def lowercase_or_notify(x): """ Lowercases the input if it is valid, otherwise logs the error and sets a default value Args: String to lowercase Returns: Lowercased string if possible, else unmodified string or default value. """ try: return x.lower() ex...
a9e9cce9450f21f5cec80739d435e362288e8844
23,623
def is_not_null(node, eval_type, given_variables): """Process the is_not_null operator. :param node: Formula node :param eval_type: Type of evaluation :param given_variables: Dictionary of var/values :return: Boolean result, SQL query, or text result """ if eval_type == EVAL_EXP: # ...
a261731103f81f1e4fe2c6eb191d3127acb163fe
23,624
def search_for_rooms(filters, allow_admin=False, availability=None): """Search for a room, using the provided filters. :param filters: The filters, provided as a dictionary :param allow_admin: A boolean specifying whether admins have override privileges :param availability: A boolean specifying whether...
fe29ec5b4bf27d51b45ed2ba87cb7153d176583c
23,625
def get_scalar(obj): """obj can either be a value, or a type Returns the Stella type for the given object""" type_ = type(obj) if type_ == type(int): type_ = obj elif type_ == PyWrapper: type_ = obj.py # HACK { if type_ == type(None): # noqa return None_ elif t...
2b5c829a8a933ff5f80a1d17d0ba8c2a49c90643
23,626
def get_importable_subclasses(base_class, used_in_automl=True): """Get importable subclasses of a base class. Used to list all of our estimators, transformers, components and pipelines dynamically. Args: base_class (abc.ABCMeta): Base class to find all of the subclasses for. used_in_automl: Not...
39b858f9287e6413be4c73053a7f515c16d181e9
23,627
import math def sin(x, deg=None, **kwargs): """Computes the sine of x in either degrees or radians""" x = float(x) if deg or (trigDeg and deg is None): x = math.radians(x) return math.sin(x)
5f5809fac0fd6970fa58a20b8c70e9f6a53d96d7
23,628
def Debug(message, print_init_shape=True, print_forward_shape=False, print_inverse_shape=False, compare_vals=False, name='unnamed'): # language=rst """ Help debug shapes :param print_init_shape: Print the shapes :param print_forward_shape: Print the...
2054f8c56c853c3221a004a9721d22844b3e1e04
23,629
def bloated_nested_block(block_dets, *, repeat=False, **_kwargs): """ Look for long indented blocks under conditionals, inside loops etc that are candidates for separating into functions to simplify the narrative of the main code. """ bloated_outer_types = set() included_if = False for l...
fc25529485c9725cf0de3fe5917299b084f499a3
23,630
from typing import Any def _to_bytes(value: Any, type_str: str = "bytes32") -> bytes: """Convert a value to bytes""" if isinstance(value, bool) or not isinstance(value, (bytes, str, int)): raise TypeError(f"Cannot convert {type(value).__name__} '{value}' to {type_str}") value = _to_hex(value) ...
f324d915377cd281eacb25b3afbde7b83deedad1
23,631
def _map_sbs_sigs_back(df: pd.DataFrame) -> pd.Series: """ Map Back Single-Base Substitution Signatures. ----------------------- Args: * df: pandas.core.frame.DataFrame with index to be mapped Returns: * pandas.core.series.Series with matching indices to context96 """ def _c...
d6a8843c80acdaf5320191af51cb40c8ce7e0d42
23,632
def rmsd( coords1: np.ndarray, coords2: np.ndarray, atomicn1: np.ndarray, atomicn2: np.ndarray, center: bool = False, minimize: bool = False, atol: float = 1e-9, ) -> float: """ Compute RMSD Parameters ---------- coords1: np.ndarray Coordinate of molecule 1 c...
e5f430d3ddb330c7bf61e0674c29cba3d6fadd7f
23,633
def get_bridge_interfaces(yaml): """Returns a list of all interfaces that are bridgedomain members""" ret = [] if not "bridgedomains" in yaml: return ret for _ifname, iface in yaml["bridgedomains"].items(): if "interfaces" in iface: ret.extend(iface["interfaces"]) retu...
dad9e634a1c5306289e73d465b08b7ea857518e4
23,634
import os import sys def get_library_dirs(): """ Return lists of directories likely to contain Arrow C++ libraries for linking C or Cython extensions using pyarrow """ package_cwd = os.path.dirname(__file__) library_dirs = [package_cwd] if sys.platform == 'win32': # TODO(wesm): I...
376b1dac450133fd92293c27d5043a2056aa8edb
23,635
from typing import List import tqdm def get_entity_matched_docs(doc_id_map: List[str], data: List[dict]): """Gets the documents where the document name is contained inside the claim Args: doc_id_map (List[str]): A list of document names data (List[dict]): One of the FEVEROUS datasets Ret...
dd49d58bd2a4dc4eed06e16d5673c85bf1ed8b73
23,636
import requests def getTemplateKeys(k): """ Prints out templates key for license or gitignore templates from github api Params: str Return: code """ code = 0 if k.lower() == "license": r = requests.get(GITHUB_LICENSE_API) if r.status_code != 200: code = 1 ...
641e6aeb599fb206214530b55faea44be7de7d37
23,637
def get_num_conv2d_layers(model, exclude_downsample=True, include_linear=True): """ Check the number of Conv2D layers. """ num = 0 for n, m in model.named_modules(): if "downsample" in n and exclude_downsample: continue if is_conv2d(m) or (include_linear and isinstance(m, nn.Lin...
79d1453f4cc49d358329a7d59fdd07bcdbb97736
23,638
def im_list_to_blob(ims, RGB, NIR, DEPTH): """Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...). """ max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) if RGB & NIR & DEPTH: blob = np.zeros((...
96036933eddd742b9db4e211188c1716933d37dc
23,639
async def async_setup_entry(hass, config_entry, async_add_devices): """Set up entry.""" miniserver = get_miniserver_from_config_entry(hass, config_entry) loxconfig = miniserver.lox_config.json devices = [] for switch_entity in get_all_switch_entities(loxconfig): if switch_entity["type"] in ...
1cd4114645b7454c371bc23a13e212e2ae9f8173
23,640
import torch def gradU_from_momenta(x, p, y, sigma): """ strain F'(x) for momenta p defined at control points y a method "convolve_gradient" is doing a similar job but only compute (gradF . z) x (M, D) p (N, D) y (N, D) return gradU (M, D, D) """ kern = deformetrica.support.k...
03dc67bf8bc6b8a576b1ed96de841003bcb53383
23,641
def process(seed, K): """ K is model order / number of zeros """ print(K, end=" ") # create the dirac locations with many, many points rng = np.random.RandomState(seed) tk = np.sort(rng.rand(K)*period) # true zeros uk = np.exp(-1j*2*np.pi*tk/period) coef_poly = poly.polyfromro...
544d5116cf5ef3a2bff08253ee697d4a04994a2e
23,642
def _gen_sieve_array(M, factor_base): """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base that doesn't divide the coefficient `a` we add log_p over the sieve_array such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i` is an integer. When p = 2 then log_p i...
98a8e5bedaa56dbe53aa8a152c20a015d7b3556d
23,643
def yolo_eval_weighted_nms(yolo_outputs, anchors, num_classes, image_shape, score_threshold=.6): """ yolo evaluate Args: yolo_outputs: [batch, 13, 13, 3*85] anchors: [9, 2] num_cl...
7066f2dbb4908709a3d762443385376d44d7f9f6
23,644
def next_coach_id(): """ Generates the next id for newly added coaches, since their slugs (which combine the id and name fields) are added post-commit. """ c = Coach.objects.aggregate(Max("id")) return c['id__max']+1
55be7f6411685b391e9130bd9248588f3d0d8ffc
23,645
def get_unsigned_short(data, index): """Return two bytes from data as an unsigned 16-bit value""" return (data[index+1] << 8) + data[index]
9e3b7dc30eaedb99edfb35b944442d7386ad8f9e
23,646
def getObjDetRoI(imgSize, imgPatchSize, objx1, objy1, objx2, objy2): """ Get region of interest (ROI) for a given object detection with respect to image and image patch boundaries. :param imgSize: size of the image of interest (e.g., [1920x1080]). :param imgPatchSize: Patch size of the image patch of in...
2feedb9a5f79c24d0fda4eaa9b8db5bd6922b4ce
23,647
def sigma_pp(b): """pair production cross section""" return ( sigma_T * 3.0 / 16.0 * (1 - b ** 2) * (2 * b * (b ** 2 - 2) + (3 - b ** 4) * np.log((1 + b) / (1 - b))) )
a3745b5f39e71c5f5713e3d7e0c7fbdb53146d15
23,648
def compute_radii_simple(distances): """ Compute the radius for every hypersphere given the pairwise distances to satisfy Eq. 6 in the paper. Does not implement the heuristic described in section 3.5. """ n_inputs = tf.shape(distances)[1] sorted_distances = tf.sort(distances, direction="ASC...
a935bbe6539c32d9de87b80dbaa6314152979b07
23,649
def data_resolution_and_offset(data, fallback_resolution=None): """Compute resolution and offset from x/y axis data. Only uses first two coordinate values, assumes that data is regularly sampled. Returns ======= (resolution: float, offset: float) """ if data.size < 2: if data.s...
9cb5a14ff5be8509509e67b1576146231258583b
23,650
from typing import List def get_changed_files_committed_and_workdir( repo: Git, commithash_to_compare: str ) -> List[str]: """Get changed files between given commit and the working copy""" return repo.repo.git.diff("--name-only", commithash_to_compare).split()
1696c3bc41084db5d260bc1ddd7811dd9f143586
23,651
from typing import Optional from typing import Any def load_document_by_string( string: str, uri: str, loadingOptions: Optional[LoadingOptions] = None ) -> Any: """Load a CWL object from a serialized YAML string.""" yaml = yaml_no_ts() result = yaml.load(string) return load_document_by_yaml(result...
1750f0df653f155e112b3cbb363e4ee499f76ab6
23,652
import re def rename_symbol(symbol): """Rename the given symbol. If it is a C symbol, prepend FLAGS.rename_string to the symbol, but account for the symbol possibly having a prefix via split_symbol(). If it is a C++ symbol, prepend FLAGS.rename_string to all instances of the given namespace. Ar...
4c2291e3c604157df1f4d8f1f4e3b7a1277ceee2
23,653
from datetime import datetime def py_time(data): """ returns a python Time """ if '.' in data: return datetime.datetime.strptime(data, '%H:%M:%S.%f').time() else: return datetime.datetime.strptime(data, '%H:%M:%S').time()
53f1bb601ab08e06f67b759fdc9f41820ea0ff20
23,654
def create_empty_copy(G,with_nodes=True): """Return a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A NetworkX graph with_nodes : bool (default=True) Include nodes. Notes ----- Graph, node, and edge data is not propagated to the new ...
aea151473bd9f11b4e0cdfdf2ac4a689a1b5af49
23,655
def trim_resize_frame(frame, resize_ratio, trim_factor): """ Resize a frame according to specified ratio while keeping original the original aspect ratio, then trim the longer side of the frame according to specified factor. Parameters ---------- frame: np.array The input frame resize_ratio: floa...
55569da6aad4b24ef367828a2ce3353048f27ae9
23,656
def copy_doclist(doclist, no_copy = []): """ Save & return a copy of the given doclist Pass fields that are not to be copied in `no_copy` """ cl = [] # main doc c = Document(fielddata = doclist[0].fields.copy()) # clear no_copy fields for f in no_copy: if c.fields.has_key(f): c.fields[f] = No...
73e6554696abce1d94ace2b50cb8a28b0563fb30
23,657
def set_from_tags(tags, title, description, all=True): """all=True means include non-public photos""" user = flickr.test_login() photos = flickr.photos_search(user_id=user.id, auth=all, tags=tags) set = flickr.Photoset.create(photos[0], title, description) set.editPhotos(photos) return set
14e30d7334c75d29eccaf7957f53dadc164aedf0
23,658
import os from datetime import datetime def submit(): """Upload local file. Needs to follow the station register template. """ spec = get_layout_active_spec('Upload') if request.method == 'POST': filename = os.path.join( app.config['UPLOAD_FOLDER'], datetime.date.t...
75b9af46dc067977425c9714b13e9f516ded6bca
23,659
def heg_kfermi(rs): """ magnitude of the fermi k vector for the homogeneous electron gas (HEG) Args: rs (float): Wigner-Seitz radius Return: float: kf """ density = (4*np.pi*rs**3/3)**(-1) kf = (3*np.pi**2*density)**(1./3) return kf
4f210939ee7ec3c591c33ae7ec1b688ce2a257c6
23,660
import requests import json def stock_em_jgdy_detail(): """ 东方财富网-数据中心-特色数据-机构调研-机构调研详细 http://data.eastmoney.com/jgdy/xx.html :return: 机构调研详细 :rtype: pandas.DataFrame """ url = "http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/JGDYMX/GetJGDYMX" params = { "js": "datata...
5d161ef69a77243202e48d80743c6664d8487549
23,661
def intersect_with_grid(int_coords, fill=False): """ Args: - int_coords: projected coordinates to be used for intersection - fill: whether to include the interior of the intersected cells. I.e. if the coords of a box are provided and intersect with 0,0 and 4,4, this would inc...
460faccf0280749f96b34e676a936cf8a39d4b61
23,662
def safe_epsilon_softmax(epsilon, temperature): """Tolerantly handles the temperature=0 case.""" egreedy = epsilon_greedy(epsilon) unsafe = epsilon_softmax(epsilon, temperature) def sample_fn(key: Array, logits: Array): return jax.lax.cond(temperature > 0, (key, logits), lambda tup:...
cf9d09dcd82638c526fb9508161181af6452dad5
23,663
def get_object_from_controller(object_type, object_name, controller_ip, username, password, tenant): """ This function defines that it get the object from controller or raise exception if object status code is less than 299 :param uri: URI to get the object :param controller_ip: ip of controller ...
590107e0106b87faa4fc228b6225e2317047ec19
23,664
from typing import DefaultDict def scale_reshaping(scale: np.ndarray, op2d: common.BaseNode, kernel_channel_mapping: DefaultDict, in_channels: bool = True) -> np.ndarray: """ Before scaling a kernel, the scale factor needs is reshaped to the correct ...
edaa0ecbfc172f0a8a32a7bcc70629f1b51b3f57
23,665
import os def process_metadata(split_name, caption_data, image_dir): """Process the captions and combine the data into a list of ImageMetadata. Args: split_name: A train/test/val split name. caption_data: caption file containing caption annotations. image_dir: Directory containing the image ...
240b789b3164059765d5cfc3b0e9cda6f532fac6
23,666
def add_new_exif(info): """ 创建exif记录(从表) :param info: :return: """ return ExifInfo(make=info.get('Image Make'), model=info.get('Image Model'), orientation=info.get('Image Orientation'), date_original=info.get('EXIF DateTimeOriginal'), ...
55122efc1ef612b769be30a1e0735e237e12ab29
23,667
def prefetch_input_data(reader, file_pattern, is_training, batch_size, values_per_shard, input_queue_capacity_factor=16, num_reader_threads=1, shard_que...
b754c1163cb868214e9ab74e1ae127a794a04808
23,668
def Chat_(request): """ { "value" : "Your query" } """ print(request.data) serializer = PatternSerializer(request.data) try: response = ChatBot(serializer.data["value"]) except: response = { "error": "Data is in wrong formate use { 'value' : 'Your quer...
33cada0ccbbea0e65d01179d51e5f1ed28f498bd
23,669
def get_solubility(molecular_weight, density): """ Estimate the solubility of each oil pseudo-component Estimate the solubility (mol/L) of each oil pseudo-component using the method from Huibers and Lehr given in the huibers_lehr.py module of py_gnome in the directory gnome/utilities/weathering...
64a951e8a6d9579cf934893fe5c9bc0a9181d4cc
23,670
def build_1d_frp_matrix(func, x, sigma, B=1): """ Builds quadratic frp matrix respecting pbc. func: Kernel function x: position of points sigma: width of Kernel """ N = len(x) A = np.zeros((N, N)) shifts = np.arange(-5, 6) * B for r in range(N): for p in range(N): ...
cc2d2d51935847cc01aacb2afe5c42ad19c91fe8
23,671
def invalid_item(item_key, valid_flag=False): """ Update item valid_flag. """ if kind.str_is_empty(item_key): raise RequiredError("item_key") query = Registry.all() query.filter("item_key =", item_key) query.set("valid_flag", valid_flag) return query.update(context.get_us...
a99408dd770be0f8eb2e3c899b8d51160359b4fa
23,672
def ret_str() -> str: """ # blahs blahs # blahs Returns ------- """ # blahs # blahs # blahs return ''
56c182f971ff38444f5cc04fa1ea537ebbc3cb5f
23,673
from typing import Union def get_wh_words(document: Union[Doc, Span]): """ Get the list of WH-words\n - when, where, why\n - whence, whereby, wherein, whereupon\n - how\n - what, which, whose\n - who, whose, which, what\n Resources:\n - https://grammar.collinsdictionary.com/easy-l...
a3dd46902bf161358239a5613c5037dfe4e831ff
23,674
def sample_mixture_gaussian(batch_size, p_array, mu_list, sig_list, k=K, d=DIM): """ samples from a mixture of normals :param batch_size: sample size :param p_array: np array which includes probability for each component of mix :param mu_list: list of means of each component :param sig_list: lis...
80374ed474ccb284a0cdb5efb63e44652318f0a2
23,675
def sign(x: float) -> float: """Return the sign of the argument. Zero returns zero.""" if x > 0: return 1.0 elif x < 0: return -1.0 else: return 0.0
5998061fcb57ef0133c6ccd56e1ad79a31b06732
23,676
import numpy def CalculateLocalDipoleIndex(mol): """ Calculation of local dipole index (D) """ GMCharge.ComputeGasteigerCharges(mol, iter_step) res = [] for atom in mol.GetAtoms(): res.append(float(atom.GetProp('_GasteigerCharge'))) cc = [numpy.absolute(res[x.GetBeginAtom().GetIdx...
f4e1f0cd0130cc1e94430eac2df910946f4e98d0
23,677
def tile1(icon="", **kw): """<!-- Tile with icon, icon can be font icon or image -->""" ctx=[kw['tile_label']] s = span(cls="icon %s" % icon) ctx.append(s) d2 = div(ctx=ctx, cls="tile-content iconic") return d2
fdcdecbc81733ae6b615cf5db5bce60585337efe
23,678
from typing import Optional def config_server(sender_email:str, sender_autorization_code:str, smtp_host: Optional[str] = None, smtp_port: Optional[int] = None, timeout=10): """ smtp server configuration :param sender_email: sender's email :param sender_autorization_code: sender's smtp authorization ...
f93b9efff8e8f415242bb9dbb5e09529baa1e238
23,679
def try_to_import_file(file_name): """ Tries to import the file as Python module. First calls import_file_as_package() and falls back to import_file_as_module(). If fails, keeps silent on any errors and returns the occured exceptions. :param file_name: The path to import. :return: The loaded mod...
15ab5c695bb7801b894c4466994abbb9f4ad791a
23,680
def is_uppervowel(char: str) -> bool: """ Checks if the character is an uppercase Irish vowel (aeiouáéíóú). :param char: the character to check :return: true if the input is a single character, is uppercase, and is an Irish vowel """ vowels = "AEIOUÁÉÍÓÚ" return len(char) == 1 and char[0] i...
14e87fc53fbb31c2a1ba66d17082be533ef8c5a9
23,681
from typing import Optional def visualize_permutation_results( obs_r2: float, permuted_r2: np.ndarray, verbose: bool = True, permutation_color: str = "#a6bddb", output_path: Optional[str] = None, show: bool = True, close: bool = False, ) -> float: """ Parameters ---------- ...
cfdf84fd78cd54b39eb6db9b0af799a230a294c8
23,682
def htmlmovie(html_index_fname,pngfile,framenos,figno): #===================================== """ Input: pngfile: a dictionary indexed by (frameno,figno) with value the corresponding png file for this figure. framenos: a list of frame numbers to include in movie figno: integer with...
7be1cf8ffce35e51667a67f322fbf038f396e817
23,683
from pathlib import Path import re import io def readin_q3d_matrix_m(path: str) -> pd.DataFrame: """Read in Q3D cap matrix from a .m file exported by Ansys Q3d. Args: path (str): Path to .m file Returns: pd.DataFrame of cap matrix, with no names of columns. """ text = Path(path)....
35a79ff4697ba1df3b2c1754d8b28064b459201f
23,684
def get_DB(type='mysql'): """ Parameters ---------- type Returns ------- """ if type == 'mysql': return MySQLAdapter elif type == 'mongodb': return MongoAdapter
07a3f0c1fcac691855f616e2e96d5ab947ca7be3
23,685
def movstd(x,window): """ Computes the moving standard deviation for a 1D array. Returns an array with the same length of the input array. Small window length provides a finer description of deviation Longer window coarser (faster to compute). By default, each segment is centered, ...
e9c4bc43f92d6d22c8191d1d15b93a51aadef32c
23,686
def get_attribute(parent, selector, attribute, index=0): """Get the attribute value for the child element of parent matching the given CSS selector If index is specified, return the attribute value for the matching child element with the specified zero-based index; otherwise, return the attribute value for the first...
fff9ec0a30dd00431164c69f5ba3430ec09f804a
23,687
def rdd_plot( data, x_variable, y_variable, nbins=20, ylimits=None, frac=None, width=20.1, deg=1 ): """ Plots a Regression Discontinouity Design graph. For this, binned observations are portrayed in a scatter plot. Uses non-parametric regression (local polynomial estimation) to fit a curve on the or...
10d0624c3a734cd097c3c23850675b7ad013837a
23,688
import torch def cal_head_bbox(kps, image_size): """ Args: kps (torch.Tensor): (N, 19, 2) image_size (int): Returns: bbox (torch.Tensor): (N, 4) """ NECK_IDS = 12 # in cocoplus kps = (kps + 1) / 2.0 necks = kps[:, NECK_IDS, 0] zeros = torch.zeros_like(necks)...
546b4d4fcf756a75dd588c85ab467c21e9f45550
23,689
def my_json_render(docs, style="dep", options=None, manual=False) -> list: """ Render nlp visualisation. Args: docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. options (dict): Visualiser-specific options, e.g. colors. manual ...
a19068ae0c9e4eb89e810f378ccc8d5fbd14547a
23,690
import json def get_testcase_chain(testcase_id, case_type, chain_list=None, with_intf_system_name=None, with_extract=None, only_first=False, main_case_flow_id=None, childless=False): """ 根据testcase_id获取调用链, 包含接口用例和全链路用例 return example: [ { "preCaseId": 1, ...
92892c432a46287559c41fe9d1b5fb11dec35e86
23,691
from typing import Iterable def approximate_parameter_profile( problem: Problem, result: Result, profile_index: Iterable[int] = None, profile_list: int = None, result_index: int = 0, n_steps: int = 100, ) -> Result: """ Calculate profiles based on an approximati...
478a95b370360c18a808e1753a8ad60f6a7b1bb7
23,692
def _process_input(data, context): """ pre-process request input before it is sent to TensorFlow Serving REST API Args: data (obj): the request data, in format of dict or string context (Context): object containing request and configuration details Returns: (dict): a JSON-ser...
05d48d327613df156a5a3b6ec76e6e5023fa54ca
23,693
from ibmsecurity.appliance.ibmappliance import IBMError def update_policies(isamAppliance, name, policies, action, check_mode=False, force=False): """ Update a specified policy set's policies (add/remove/set) Note: Please input policies as an array of policy names (it will be converted to id's) """ ...
666fd658f8d6748f8705a098b0f773f3fa758bbe
23,694
def is_bullish_engulfing(previous: Candlestick, current: Candlestick) -> bool: """Engulfs previous candle body. Wick and tail not included""" return ( previous.is_bearish and current.is_bullish and current.open <= previous.close and current.close > previous.open )
ab46a10009368cbb057ddf79ee9eda56ab862169
23,695
import math def yaw_cov_to_quaternion_cov(yaw, yaw_covariance): """Calculate the quaternion covariance based on the yaw and yaw covariance. Perform the operation :math:`C_{\\theta} = R C_q R^T` where :math:`C_{\\theta}` is the yaw covariance, :math:`C_q` is the quaternion covariance and :math:`R` is ...
f98a7b996ea290f735214704d592c5926ca4d07f
23,696
import logging async def token(req: web.Request) -> web.Response: """Auth endpoint.""" global nonce, user_eppn, user_family_name, user_given_name id_token = { "at_hash": "fSi3VUa5i2o2SgY5gPJZgg", "sub": "smth", "eduPersonAffiliation": "member;staff", "eppn": user_eppn, ...
771d21043a1185a7a6b4bd34fda5ae78ad45d51e
23,697
def split_train_test(observations, train_percentage): """Splits observations into a train and test set. Args: observations: Observations to split in train and test. They can be the representation or the observed factors of variation. The shape is (num_dimensions, num_points) and the split is over t...
8b6aa5896c5ae8fc72414e707013248fcb320d88
23,698
def InitF11(frame): """F6 to navigate between regions :param frame: see InitShorcuts->param :type frame: idem :return: entrie(here tuple) for AcceleratorTable :rtype: tuple(int, int, int) """ frame.Bind(wx.EVT_MENU, frame.shell.SetFocus, id=wx.ID_SHELL_FOCUS) return (wx.ACCEL_NORMAL, w...
055852664e48154768353af109ec1be533a7ad4a
23,699