content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sourcecontrol_repos_repo_id_refs_get(repo_id): # noqa: E501 """sourcecontrol_repos_repo_id_refs_get # noqa: E501 :param repo_id: Source control repository identifier :type repo_id: str :rtype: None """ return 'do some magic!'
880635586cca99cbd759f33ce5cfa6b8f56ee3eb
3,621,851
from typing import Union def duration_offpeak( ts_left: Union[pd.Timestamp, pd.DatetimeIndex], freq: str = None ) -> Union[Q_, pd.Series]: """ Total duration of offpeak periods in a timestamp. See also -------- .tools.stamps.duration """ return duration_base(ts_left, freq) - duration_...
c0dfeb82477597d72c61a5d9073ad4827de749db
3,621,852
def truncate_labels(labels): """ (1) replacing row[0] by 10, and move it to the last of row (2) replace the second 10 by -1 row wise """ def do_one_row(row): erase = False for i, _ in enumerate(row): if erase: row[i] = -1 else: ...
0cbf05f935ee12e123475ac58cfb47918ac9b4da
3,621,853
import warnings import math def sample(problem, N, calc_second_order=True, seed=None, skip_values=1024): """Generates model inputs using Saltelli's extension of the Sobol' sequence. Returns a NumPy matrix containing the model inputs using Saltelli's sampling scheme. Saltelli's scheme extends the Sobol' s...
af179d538a9ab51a07332199fe37573c5f6a6535
3,621,854
def create_wall(obj_name, document): """Create a wall.""" obj = document.addObject('Part::FeaturePython', obj_name) origin = document.addObject('App::Origin', 'WallOrigin') Wall(obj, origin) WallViewProvider(obj.ViewObject) return obj
b2352fc4dff59f1854cdce3eec73cef83d1ba557
3,621,855
def prepare_roi(image5d, roi_size, roi_offset): """Extracts a region of interest (ROI). Calls :meth:`prepare_subimage` but expects size and offset variables to be in x,y,z order following this software's legacy convention. Args: image5d: Image array as a 5D array (t, z, y, x, c), or 4D if ...
867c33140b9413434e442025599562369a489443
3,621,856
from arbiter.async import run_tasks from arbiter.task import create_task def test_no_dependencies(): """ run dependency-less tasks (with threads) """ executed_tasks = set() def make_task(name, dependencies=(), should_succeed=True): """ Make a task """ function = ...
66ac6963eaee611dc1613fb4f4308d78f0ef937e
3,621,858
import json def decode(s): """ Deserialize a DMRS object from a DMRS-JSON string. """ return from_dict(json.loads(s))
340f5a184a565de06f7139158896127a9ddf91b8
3,621,859
import copy def cross_multiply_array(array_1, array_2=None, axis=0): """Cross multiply the arrays along the given axis. Cross multiplies along axis and computes array_1.conj() * array_2 if axis has length M then a new axis of size M will be inserted directly succeeding the original. Parameters -...
0c27c8b27dd1d3cc4cc07bba4f9b211e725b2b95
3,621,860
from typing import Union def Create( allow_multiple=True, ) -> Union[ZeroOrMorePhraseItem, OptionalPhraseItem]: """\ ('@' <name> <<Arguments>>? <newline>?)* - or - ('@' <name> <<Arguments>>? <newline>?)? # If 'allow_multiple' is False """ phrase_item = PhraseItem.Create( ...
0e783eceaf3f1f206a9ed3d72af82a85800c2b7e
3,621,861
def return_largest_region(image_bin): """Returns the largest region in the input image. Parameters ---------- image_bin : (M, N) ndarray A binary image. Returns ------- image_bin : (M, N) ndarray The input binary image containing only the largest region. """ props =...
40f6745b0908c7ee08c1563f3991a5e7880c720e
3,621,862
def stretchedAmplitude(TA_file, pol_time, peak_min, peak_max, time_zero=None): """Takes in TA data and picks out the peak for the polaron state and returns the average value so it can be used for fitting function. Must make sure to pick the right energy range, peak_min and max are in eV.""" TA = np.loa...
8f734bf778f0a1e768ab35acd1fc7b8a39eb3183
3,621,863
def _write_rollup_config( ctx, root_dir, filename = "_%s.rollup.conf.js", downlevel_to_es2015 = False): """Generate a rollup config file. Args: ctx: Bazel rule execution context root_dir: root directory for module resolution (defaults to None) filename: output ...
f9b8cf2621e0cf68f0bad9a02802c2500dda9b53
3,621,864
def raw_images_to_array(images): """ Decode and normalize multiple images from tfrecord data :param images: list of images encoded as a png in a string :return: a numpy array of size (N, 56, 56, channels), normalized for training """ image_list = [] for image_str in images: image = d...
adac8756926ba92536ae4fdd0a7b32620d37d028
3,621,865
from typing import Dict def create_model(model: str, config: Dict) -> object: """ Creates a model with a given configuration Args: model (str): name of the model config (dict): dictionary of parameters Returns: (object): created model (HHVAEM, HMCVAEM, ...) """ if mod...
19bdb172fb8890bee08ac63de929c213dc85996d
3,621,866
import torch def make_positions(tensor, padding_idx, onnx_trace=False): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. """ mask = tensor.ne(padding_idx).long() return torch.cumsum(mask, dim=1) * mask + padding_idx
f59fad86a23ff76f184c0dd6a21a92722f4817f5
3,621,867
import requests def get_song_list(playlist_url): """ This function get the song list in the form of "name creator" from the spotify page """ # validating the data if not playlist_url.startswith("https://open.spotify.com"): print("this is not a spotify url") return [] elif play...
10bc3b6f14cd93c9a4f525883c7a2d56f66bf234
3,621,868
import unittest def makeTestSuiteV201101(): """Set up test suite using v201101. Returns: TestSuite test suite using v201101. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(CustomTargetingServiceTestV201101)) return suite
05b925b4bcdd38ab9a6e4b71374a6ff44fe8eb57
3,621,869
def add_bond_features(X_df): """ Using the information about standard C-H,N-H and O-H bond distances, we compute features which aims to find a notion of deviation from the expected bond distances. """ assert len(set(['atom_1', 'atom_0', 'x_0', 'x_1', 'y_0', 'y_1', 'z_0', 'z_1']) - set(X_df.columns))...
9798a97d9ebd308552334db64672ee23e8c6a666
3,621,870
def port_to_ip_mapping(index): """ A user defined mapping port_id (kni) to ipv4. """ return {"vEth0_{}".format(index): "192.167.10.{}".format(index + 1)}
81d981bc8742e1295cb279d6b47d0e97f012b679
3,621,871
def quote(): """Get stock quote.""" current_userid = session["user_id"] userbalance = get_userbal(db, current_userid) userstocks = get_userstock(db, current_userid) stocklist = get_stocklist(db, stocksid=True, prices=True) if request.method == "POST": response = lookup(request.form.get("...
506b0a2398269f73d6dc2e78f31ac5a9743cf01b
3,621,872
from typing import OrderedDict def cleanup_dataframe(df, logger=None): """Cleans the dataframe - strips new lines, double, single quotes; None -> nan, etc - formats the column names for Bigquery input """ if logger: logger.log_text("Cleaning up the dataframe", severity='INFO') ...
4fd7788bc5c99a220845d93a7c0549acbc67bdf6
3,621,873
import re def organize_key(filename): """用于sorted的key参数""" if filename[0:2].upper() == 'AD': return 0 name = re.findall(r"-([0-9]+[A-Z]*).pdf", filename)[0] num = get_group_index(filename) alpha = name.replace(num, '') if len(alpha) == 1: return int(num)*100+ord(alpha)-64 # 使用...
eee3c3e9f0f967212e7f38ea8781291b4794ed38
3,621,874
def launch_svr(X, y, sample_weight=None, kernel='linear', C=1): """Fit the classification SVMs according to the given training data. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vectors. y : array-like, shape (n_samples,) Target values. sample_weig...
02ae4f86a6cac32e0af862cb24f6565f932e6729
3,621,875
def cancel_candidacy(request, candidacy): """Cancel your own, yet-unapproved candidacy.""" user = request.user cd = get_candidacy(candidacy) if user != cd.user: return HttpResponseForbidden(u"Vous ne pouvez annuler que vos propres candidatures.") m.JournalEntry.log(user, "Cancelled own appli...
0a8f93934ccf3b530e6d27a5be1bad76798c7607
3,621,876
import random def generate_rsa_keys(prime_lenth=4): """Return tuple of (open, close, mod)""" start = 10 ** (prime_lenth-1) end = (10 ** (prime_lenth)) - 1 p, q = get_generate_prime_pair(start=start, end=end) n = p * q print("p: {} q: {}".format(p, q)) print("n: {}".format(n)) eul...
8c2e5b6b6d4db6d2667ac6e935c8a9ae429b28ef
3,621,877
def cache_by_hashed_args(obj): """ Decorator for caching a function values .. deprecated:: v0.9.8.3 :func:`cache_by_hashed_args` will be removed in pyGSTi v0.9.9. Use :func:`functools.lru_cache` instead. """ return lru_cache(maxsize=128)(obj)
2fc95b7a248febd206703e48bdd0494dd0bca04d
3,621,878
import numpy def setBadRegions(exposure, badStatistic="MEDIAN"): """Set all BAD areas of the chip to the average of the rest of the exposure Parameters ---------- exposure : `lsst.afw.image.Exposure` Exposure to mask. The exposure mask is modified. badStatistic : `str`, optional ...
90b987039b13264ac205f28a12c90bb341e04a80
3,621,879
def humanize_list(elements): """" splits a list and add punctuations to it elements """ humanize_string = '' if len(elements) > 1: for element in elements: if element == elements[len(elements)-2]: # second to last item humanize_string = humanize_string + element....
3172ac89f763d7faca4ce31c41611ca6b6731896
3,621,880
import typing def ark(row: typing.Mapping[str, str]) -> str: """The item ARK (Archival Resource Key) Args: row: An input CSV record. Returns: The item ARK. """ ark_prefix = "ark:/" if row["Item ARK"].startswith(ark_prefix, 0): return row["Item ARK"] return ark_pre...
ea428fcddf26a5bfdad3ec1c4906e765b72b1f47
3,621,881
def common_member(a, b, natural_sort=True): """ Checks if two lists (or sets) have a common member, and if so, returns the common members. :param a: First list (or set) :param b: Second list (or set) :param bool natural_sort: Sort the resulting items naturally (default: True) :return: Tr...
160f1429f412a52513be60d331d7cb15d03e64e7
3,621,883
import copy def transforms_description(f): """ Decorator which deepcopies the description and extracts ['rnn'][0] from it. Desperately needs to be obsoleted. """ @wraps(f) def wrapper(description, *args, **kwds): description = copy.deepcopy(description) try: desc = description[...
04343be02ec049d98e548b378a5965adb929c61b
3,621,885
async def close(ctx): """issueをcloseします。""" try: bot.close_issue(ctx.channel.id) except ValueError: return await ctx.send("issueがオープンされていません。", delete_after=5) await ctx.message.add_reaction("\U0001f44d")
c6f6c9aac62855361d09f066f81344d13012ac3b
3,621,886
import numpy as np def read_data(fname, filter_params, time_windows, time_units, fps, is_manual_index): """ Reads the timeseries_data and the blob_features for a given file within every time window. return: timeseries_data_list: list of timeseries_data for each time window (length of lists = numbe...
aad55507d0bec581f072c173fb78f8fd1a470d8d
3,621,887
def forecast( precip, velocity, timesteps, threshold, extrap_method="semilagrangian", extrap_kwargs=None, slope=5, ): """ Generate a probability nowcast by a local lagrangian approach. The ouput is the probability of exceeding a given intensity threshold, i.e. P(precip>=thres...
09bbeebdfe99277bdf8f77903d6d3e2fd812133e
3,621,888
def train_svm(documents, ntesting=500): """ :param documents- politeness-annotated training data :type documents- list of dicts each document must be preprocessed and 'sentences' and 'parses' and 'score' fields. :param ntesting- number of docs to reserve for testing :type ntesting- ...
d756911708fd26116b990131cffaffc069cd6eb7
3,621,889
from typing import Union from typing import Optional from datetime import datetime from typing import Sequence def get_logs_for_action( data: Union[LogData, pd.DataFrame], log_action: str, selected_day: Optional[datetime.date] = None, rows: Optional[Union[str, int, Sequence[int]]] = None, ) -> Union[p...
07d098ce6af982a1cc50a9d88121b84721bee181
3,621,890
import math def is_mc_multiplier(multiplier, modulus): """ Checks if multiplier is a MC multiplier w.r.t. modulus. :param multiplier: an integer in (0, modulus). :param modulus: a prime number. :return: True if multiplier is a MC multiplier w.r.t. modulus. """ return (modulus % multiplier)...
6d210f8de081ae0a468692b2f93e5145170917e9
3,621,891
from typing import List from typing import Container async def buckets_get(buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Bucket]: """ returns all buckets configured """ return buckets.get_all()
3f8d4a9db3a3648b00f79ba4a9108aef554415c2
3,621,892
def group_without_decoys(peptides, target_column, proteins): """Retrieve the protein group with a target-only FASTA. Build a dictionary mapping the decoy peptides to a plausible unique target peptide. Then proceed to map as with the targets. Parameters ---------- peptides : pandas.DataFrame ...
57c528aef970855a3cdce029d1c101485d5e401f
3,621,893
from typing import Any def get_endpoint_stats(netid: str, client: ShrunkClient) -> Any: """``GET /api/stats/endpoint`` Returns visit statistics for each Flask endpoint. Response format: .. code-block:: json { "stats": [ { "endpoint": "string", "total_visits": "number", "unique_visits": "number" ...
b4d0d22ad0014da66fd1b99448d6fcf863071eeb
3,621,894
import requests import jsonschema def create_project(project, notify_user=True): """ Create an OpenLDAP project. Args: project (Project): Project instance - required notify_user (bool): Issue a notification email to the project technical lead? - optional """ url = ''.join([setting...
022ab097e9df0be19def36fc9a418a1bf8d976ac
3,621,895
def readToTuple(f_path): """Reads in a two-col file (tab-delim) and returns a list of tuples""" f = open(f_path) ls = [] for l in f: if l.startswith("#"): continue ls.append(tuple(l.strip().split("\t"))) return ls
726d1b4a4682c4e11afbf59e342340e0cf5ccc63
3,621,896
from typing import List from typing import Tuple import tqdm def _preprocess_file(input_file: str, lang: str) -> List[Tuple[List[str]]]: """ Performs initial preprocessing, i.e., urls formatting, removal of "_trans" from Ru set Args: input_file: path to a file in google TN format lang: da...
8dfdba600ed2efe419983e90f2a7b7e7355bd534
3,621,897
from .methods import FaceNet from .methods import GoogleNet from .methods import AlexNet from .methods import SqueezeNet from .methods import VGGFace from .methods import OpenFace from .methods import FaceRecognition def predict(image, method_name, **kwargs): """ Get descriptor of image with an specific metho...
ea6de2b4bdfd70a079ea911f78239cf26641e4cd
3,621,899
import csv def buildUsageAndRatingByCityJs(): """Builds several strings defining variables used for visualization. Reads a CSV file containing the usage-by-city data and uses it to build a JavaScript string defining a DataTable containing the data. Returns: {string} of the form <var_name>=<json>, where ...
4869a64c8ef91fd2ce3940ce5d4ab28ed8278092
3,621,900
def _get_Abc(c, c0=0, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, x0=None, undo=[]): """ Given a linear programming problem of the form: Minimize:: c @ x Subject to:: A_ub @ x <= b_ub A_eq @ x == b_eq lb <= x <= ub where ``lb = 0`` and ...
c177b919626f13d2d0b5cddeecb2c7678af23d6d
3,621,902
def obj2np(obj): """Wraps an object into an np.array.""" ar = np.zeros((1,), dtype=np.object_) ar[0] = obj return ar
e35be1f05a0bb62a573592802c86ba823f727530
3,621,903
def masking(tokens, p = 0.1, mask='[MASK]'): """ Returns a new list by replacing elements in `tokens` by `mask` with probability `p`. Args: tokens (list): list of tokens or token ids. p (float): probability to mask each element in `tokens`. Returns: A new list by replacing eleme...
da19ca09fb76557c58c96a77986276a98feaac86
3,621,904
import string from typing import Counter def singlebyte_xor_cipher(hex): """ Takes a hex string and finds the best xor key and returns (ResultString, Confidence) """ common = ['n', 'i', 'o', 't', 'e', ' '] ret = None score = 0 key=0 if not isinstance(hex, bytearray): hex = hex.decode('hex') hex = bytearr...
1611372d05bfa7753d77cc389e58420a2efb0c99
3,621,905
def absolute_url(context, route, *args, **kwargs): """The absolute url for a request and a route""" return context.request.build_absolute_uri(reverse(route, args=args, kwargs=kwargs))
cfaff5366b115bdc318168669efb753c4164ca53
3,621,906
def get_Kernels(test_vectors,img_width): """ Creates 3x3 kernel which is operated by the conv2d Parameters ---------- test_vectors : numpy array Generated test vectors 3x1. img_width : integer with of test matrix. Returns ------- Kernel : numpy array Kernel t...
f9da65a87fd497ec3f4ef851fa7acb1ad8101405
3,621,907
def get_solc_version() -> Version: """ Get the version of the active `solc` binary. Returns ------- Version solc version """ solc_binary = get_executable() return wrapper._get_solc_version(solc_binary)
680d72cbeb2ceef5453722afde0dc238dbba3376
3,621,908
def epoch2dt64(ep_time): """ Convert from epoch time (seconds since 1/1/1970 00:00:00) to numpy.datetime64 array Parameters ---------- ep_time : xarray.DataArray Time coordinate data-array or single time element Returns ------- time : numpy.datetime64 The converted...
9fe7734d36a44cf4c4d63823190e7bab83b8a2f5
3,621,909
import requests import tarfile def get_file_from_recipe_url(url): """Downloads file at url and returns tarball""" r = requests.get(url, timeout=MULLED_SOCKET_TIMEOUT) return tarfile.open(mode="r:bz2", fileobj=BytesIO(r.content))
1bda8c89560c1af0da8ff0a6d8eb3a70281ae66a
3,621,910
def df_to_dict_single(df, curation_id=None): """ Purpose: Convert a single entry pandas DataFrame into a dictionary and strip out indexing information :param df: pandas DataFrame with single entry (e.g., use df.loc[] to filter) :param curation_id: integer providing the curation_id. Default: ...
5a63e4cb56f8492adfae48cfd0c54f0fa6f6e104
3,621,911
def check_lines_valid(left_line, right_line, last_left_line=None, last_right_line=None): """ Checks validity of two given lines based on there geometry and optionally based on the deviation to the previous detected lines. Also calculates the Mean Absolute error and the Mean Squared Error of the x values bet...
5b9bb2369d6eccb4c2c1ba4288b5939f6c290574
3,621,912
import requests def get_the_manifest(filter_string, api_url, manifest_file, max_files=None): """ This function takes a JSON filter string and uses it to download a manifest from GDC """ # # 1) When putting the size and "return_type" : "manifest" args inside a POST document, the result comes #...
04fd2006b42bf5478c7c5b6ee6a87da128ce7131
3,621,913
def imageseg(Cont_Image): """imageseg('Image Name') This program takes an image that has been pre-proccessed by an edge finding script as its sole input, segments it, and spits out a segmented image file and a pandas dataframe of individual particle positions. This function works by creating a binary of a...
7d786863cb668c7ba1d7cc643180fe33bcb1d318
3,621,914
import re def getSisters(tree, t="g"): """Some nasty regex to get pairs of sister taxa (only at terminal branches)""" if t == "s": l = re.findall("\(([1-9][0-9]|\d),([1-9][0-9]|\d)\)", tree) else: l = re.findall( "\(([1-9][0-9]|\d):\d\.\d\d\d,([1-9][0-9]|\d):\d\.\d\d\d\)", ...
b5c3d26b406847bfd0858181bd3becb90fccb878
3,621,915
from typing import Optional import warnings def cluster_ensembles( labels: np.ndarray, nclass: Optional[int] = None, solver: str = 'hbgf', random_state: Optional[int] = None, verbose: bool = False) -> np.ndarray: """Generate a single consensus clustering label by using base...
2d996860fd05418f676b22d2fd795a1478266dc6
3,621,916
def ReadFromXMLStream (istream, options = XML_STRICT_HDR | XML_LOAD_DROP_TOP_LEVEL | XML_LOAD_EVAL_CONTENT, # best option for invertibility array_disposition = ARRAYDISPOSITION_AS_NUMERIC_WRAPPER, prepend_char=XML_PREPEND_CHAR) : """Read XML from...
757caaf44bb50a0391e8561b9c08209469f40aa0
3,621,917
def AngleRA (angle,unit=units.hourangle,raise_errors=False): """ An object which represents a right ascension angle see `astropy.coordinates.RA` for more extensive documentation The primary difference with astropy is that if the call to coordinates.RA errors you have the option to ignore it an...
01d2d5d7aedfb73f2189fba2bb7ef0d5076d49a2
3,621,918
def k_euclidean_neighbors(k, x1, x2, exclude_identity=False, identities=None): """ For each row vector in x1 the k-nearest neighbors in x2. :param k: :param x1: M x Feat-dim :param x2: N x Feat-dim :param exclude_identity: :param identities: :return: M x k """ all_cross_pairwise_dist...
746b6100eb0e6724178633093b02725a30022ec9
3,621,919
def get_train_feed_dict(model, reviews, win_reviews, batch_length, ote_labels, ts_labels, opn_labels, stm_lm_labels, lr, dropout_rate=1.0, train_flag=True): """Construct feed dictionary.""" feed_dict = dict() feed_dict.update({model.reviews: reviews}) feed_dict.update({model.win_reviews: win_reviews}) ...
d1abf917a6fc0db66102aebda61ce431a508988f
3,621,920
def pass_through_third_point(marking_points, i, j, thresh): """See whether the line between two points pass through a third point.""" x_1 = marking_points[i][1][0] y_1 = marking_points[i][1][1] x_2 = marking_points[j][1][0] y_2 = marking_points[j][1][1] for point_idx, point in enumerate(marking_...
fbd38906e1266e8e4690e3c1eae99825009a6fab
3,621,921
def increment_ctr(ctr): """ Increments one the counter. Parameters ---------- ctr : string Counter Returns ------- incremented_counter : string Incremented Counter """ ctr_inc_int = int.from_bytes(bytes.fromhex(ctr), byteorder="big") + 1 return bytes.hex(c...
0ef04e10283f02b6b7df46cf196493a3ad4a95c8
3,621,922
from typing import Any def _instantiate(config: Any, *args: Any, **kwargs: Any) -> Any: """ :param config: An config object describing what to call and what params to use. In addition to the parameters, the config must contain: _target_ : target class or callable name (st...
82527dbf49f5af837435ef0498a2c74785806594
3,621,923
import json import torch from re import T import time import math def test_emb( opt, batch_size=16, img_size=(1088, 608), print_interval=40, ): """ :param opt: :param batch_size: :param img_size: :param print_interval: :return: """ data_cfg = opt.data_cf...
a2931c824ca69701611ab078770a46ca3167196a
3,621,924
def is_supported(value, check_all=False, filters=None, iterate=True): """Return True if the value is supported, False otherwise""" assert filters is not None if not is_editable_type(value): return False elif not isinstance(value, filters): return False elif iterate: if isinst...
b9f557b779121fa36f88e79318357d36849a3186
3,621,925
def box_net(images, level, num_anchors, num_filters, is_training, act_type, repeats=4, separable_conv=True, survival_prob=None): """Box regression network.""" for i in range(repeats): orig_images = images ...
4541b6498fe821fc113b22b7b5d7142a2c24e4b1
3,621,927
def process_folder(repo_path, folder): """Find files and send for processing.""" folder_path = repo_path + folder + "\\" vars()[folder] = dict() json_queries = enum_json(folder_path) vars()[folder].update(json_queries) yaml_queries = enum_yaml(folder_path) vars()[folder].update(yaml_queries...
d84434ed931c61ac94f1a53467c86da5e4d85ebc
3,621,928
def img_to_array(img, data_format=None, dtype=None): """Converts a PIL Image instance to a Numpy array. # Arguments img: PIL Image instance. data_format: Image data format, either "channels_first" or "channels_last". If omitted (`None`), then `backend.image_data_format()` is used. ...
0e297731b9f069995bf7faa350ea556e343274d8
3,621,929
import array def C3(theta): """ Parameters ---------- theta : float Angle 'theta' to be rotated around the X axis in rad. Returns ------- array Cossine matix (3X3) of a 'theta' rotation around the Z axis. """ return array([[cos(theta), sin(theta), 0], ...
6a0249a4e4ee3517809a22b7587a12ebc3522a56
3,621,930
def open_url(filename, basepath=None): """Opens and reads a certain file from a web or remote location. Opens and reads a certain file from a web or remote location. This function utilizes the urllib2 module, which means that it is restricted to the types of remote locations supported by urllib2. ...
346bdbe1a508458dc216c95e582d2854bd9470e1
3,621,934
def build_login(): """ Construye la ventana del inicio de sesion del usuario""" layout =[[sg.T("Usuario", size=(8,1)), sg.InputText(key='-USER-')], [sg.T("Contraseña", size=(8,1)), sg.InputText(key='-PASS-')], [sg.Submit("LogIn", size=(15,1), pad=(0,15))], [sg.T("No estas r...
7b8a6acc2891d82b745323f7605856e63653d8f5
3,621,936
def get_tif_image_layer_count(file_name): """ :param file_name: :return: """ with tifffile.TiffFile(file_name) as tif: return len(tif.pages)
945118d8849dbe3af8f4d7b8db1cd59d08ded774
3,621,937
def sonify_chromagram_with_signal(chroma_data, x, frame_rate, Fs, fading_msec=5, stereo=True): """Sonify the chroma features from a chromagram together with a corresponding signal Parameters ---------- chroma_data : NumPy Array A chromagram (e.g. gathered from a list of note events by list_to_c...
e05151412a8f0e8f7a23bcaaad37a9c283234a27
3,621,938
def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) ...
e4890c18b918bc0939a594eb0de19767a73e9898
3,621,939
import asyncio def pytest_pyfunc_call(pyfuncitem): """Run coroutines in an event loop instead of a normal function call.""" if asyncio.iscoroutinefunction(pyfuncitem.function): existing_loop = pyfuncitem.funcargs.get('loop', None) with _passthrough_loop_context(existing_loop) as _loop: ...
a78518681acd2c9d3e8ed8f015573d4f42c135c2
3,621,940
import re from datetime import datetime def get_forecast_times(forecast_length, forecast_date=None, forecast_time=None): """ Generate a list of python datetime objects specifying the desired forecast times. This list will be created from input specifications if provided. Otherwi...
9fe3c8a58b4dabb1513419d9e082e3a6bbf023be
3,621,941
import requests def human_output(): """Get request with human output params""" response = requests.request("GET", BASE_URL, params=querystring) return response
c15c07baaba60dc469aaf71443a3bad57b310180
3,621,943
def multiset(left, right, pairwise): """ Calculate the multiset distance between two vectors. :arg array_like left, right: Vector. :arg function pairwise: A pairwise distance function. :return: The multiset distance between `left` and `right`. :rtype: float Note that `function` must be ve...
bbeb929963e92ebd371fcb52153763c1519b06d2
3,621,944
def json_response(func): """ A decorator thats takes a view response and turns it into json. If a callback is added through GET or POST the response is JSONP. """ def decorator(request, *args, **kwargs): objects = func(request, *args, **kwargs) if isinstance(objects, HttpResponse...
1b49343e2f583bc9ba05092d4203177d7e23db3f
3,621,945
def sample_CRP(N, alpha,d =0): """ sample from a Pitman-Yor process via the Chinese Restaraunt process, default value of d=0 samples from a Dirichlet process Parameters ----------- N : scalar, integer number of samples to return alpha : scalar > -d concentration parameter ...
be809c64c54b18c28554fadbfc351bc1d7f55d3f
3,621,946
def iotest(fh, eof, blocksize=512, t=10): """io test""" io_num = 0 start_ts = time.time() while time.time() < start_ts+t: io_num += 1 # freebsd8: need 512B sector alignment and at least one whole block left pos = random.randint(0, eof - blocksize) & ~0x1ff fh.seek(pos) ...
a205b9cf30d171df4b0c51c1a136c907b3db23af
3,621,947
def calc_info_frames(site_results_filtered, remove_multiple=None): """Return the info frames for the input.""" dat, conf_both, conf_any = get_pipeline_stats(site_results_filtered, log=False) df_all = get_conf_dfs(conf_any) if remove_multiple: url_by_leak = df_all.groupby(["browser", "url"])[["me...
efcf4360febc44bb6d413b84bb2bb7f704eedb02
3,621,949
def _cleaner( vbo ): """Construct a mapped-array cleaner function to unmap vbo.target""" def clean( ref ): try: _cleaners.pop( vbo ) except Exception as err: pass else: vbo.implementation.glUnmapBuffer( vbo.target ) return clean
f478025165cc9ea1bfbc8f5980df8cf752b575ab
3,621,950
def winrate_match(timebox, size, map_category): """ Returns civs with winrate data based on matches. """ sql = QUERIES["win_rates_match"].format(*timebox, filters(map_category, size)) civs = CivDict(WinrateCivilization, size, map_category, "match") bottom_civs = CivDict(BottomWinrateCivilization, size, ...
ef1924be54d462f362467cfb297220924d9f7dd6
3,621,951
def powerLaw(t, m, a, b): """ Model for the shower dominated part of a ratescan """ return m*np.power(t, a)+b
b0aaa838bc523d40322b621d4e4cae526cdaeb88
3,621,952
def update_unified_dataset( session: Session, project: SchemaMappingProject ) -> Operation: """Apply changes to the unified dataset and wait for the operation to complete Args: project: Tamr Schema Mapping project """ unified_dataset = unified.from_project(session, project) op = unified...
e9e628d9fb4e6da9331f7b0f2198db220123084c
3,621,953
def make_v_spacer() -> QSpacerItem: """Make vertical QSpacerItem.""" widget = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Expanding) return widget
11216ae878058593e05a6542f3b14be91ef7c1e2
3,621,954
def combine_measurements(values): """Combines a np.array of measurements into one ufloat""" return ufloat(mean(values), stdDevOfMean(values))
1e6df9fa79dbcab5d7476cc7f4b59b6c82c37584
3,621,955
def rename_guided(expr, resolution_guide): """ resolution_guide is a dictionary whose keys are expressions and values are tuples (previous_pred, new_pred) that guide the renaming. """ replacements = resolution_guide.get(expr, []) for prev_pred, new_pred in replacements: expr = expr.r...
d12a8ab0968e07b47f429ce8fbf7d3a6f8e1c02b
3,621,956
def get_base_required_fields_uframe(): """ Get required fields for base asset in uframe. """ base_required_fields = [ 'assetId', 'assetType', '@class', 'dataSource' 'de...
233e9c8985b82335d32765daab3cc29ae5959354
3,621,957
def get_comparative_forms(tokens): """Identify, color and count comparatives and superlatives""" # find comp. forms of adjectives comparatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo.comp == 'Comp'] superlatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo...
020ce0f3a4959a2525698bfac4c45ac497e5cc67
3,621,958
from typing import Optional def fit_hypsometric_bins_poly(hypsometric_bins: pd.DataFrame, value_column: str = "value", degree: int = 3, iterations: int = 1, count_threshold: Optional[int] = None) -> pd.Series: """ Fit a polynomial to the hypsometric bins. :param hypsometric_...
d54d03cff1f65aa13a5b8678626e5a3000ad755a
3,621,960
def get_nvidia_model(summary=True): """ Get the keras Model corresponding to the NVIDIA architecture described in: Bojarski, Mariusz, et al. "End to end learning for self-driving cars." The paper describes the network architecture but doesn't go into details for some aspects. Input normalization, a...
3195f7880f3deaa4f7b4f4919579252597feea84
3,621,961
def templateXcorr(datastream, template): """ Normalized cross correlation of short template trace against longer data stream Based off matlab function coralTemplateXcorr.m by Justin Sweet Args: datastream: obspy trace of longer time period to search for template matches template: obspy ...
bae76c7bd4cc7b40e533acb868a2a2c3215ce60a
3,621,962
from datetime import datetime def _load_dates(): """Return a dict with the dates from the start_date to the current date. Returns ------- dates : dict Dictionary containing dates and indicies. """ dates = {} end_date = datetime.datetime.now() curr_date = datetime.datetime(...
8fe0bffefe46ef57d857ccd13caaec14db003fbf
3,621,963