content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def print_to_terminal(self, step, data, count, unassigned_array_length, method, re=False, second_pass=False): """ Prints some information to the terminal if verbose == True """ if (re is False) and (second_pass is False): print('') print('Beginning analysis...') print('') ...
b905d0956602e22086a93245d694fb63c9c294ad
3,610,679
def get_num_params(vocab_size, num_layers, num_neurons): """Returns the number of trainable parameters of an LSTM. Args: vocab_size (int): The vocabulary size num_layers (int): The number of layers in the LSTM num_neurons (int): The number of neurons / units per layer Returns: ...
c9620e74206878cc3390895dacbf10c84da42829
3,610,680
import json def serialize_model_object(obj): """ Serialize model into a dict representable as JSON Args: obj (django.db.models.Model): An instantiated Django model Returns: dict: A representation of the model """ # serialize works on iterables so we need to wrap obj...
fdda44b00b4d779dd0034069bdf2af7f0b43a146
3,610,681
from typing import List def secure_clauses(file_system: FileSystem, clauses: List[Clause]) -> List[Arc]: """Construct a "safe" version of the given renaming clauses and update the file system. The resulting sequence is a reordered copy of the given clauses, with potentially the insertion of intermediate ...
91abf78068861e104bd0c7bd77e08ef7620490c7
3,610,682
from typing import Union from typing import List def create_benchmark_result( project_id: str, study_id: str, benchmark_id: str, data_sets: Union[DataSet, List[DataSet], DataSetCollection], ) -> BenchmarkResult: """Creates a benchmark result. Parameters ---------- project_id T...
f94192423faa14466b362c8875fc95c34b7e4994
3,610,683
from datetime import datetime def claims_scroll(curr_page, scroll_status): """Performs the query to get claims on the specified page.""" if curr_page is None: curr_page = 0 if scroll_status == "next": if curr_page >= 0: curr_page += 1 elif scroll_status == "init": ...
dcd033e42c306bed6e1a85db849f6b0851bdfbe7
3,610,684
def init(): """ initialisation funtion for animation """ p.set_data([],[]) p_highlight.set_data([], []) highlight_path.set_data([], []) return p, p_highlight, highlight_path
c1b4e9ec5bd36b616252fa20d60f879dab6d762a
3,610,685
from PIL import Image, ImageDraw, ImageFont def add_text(img, text, coords=(0.02, 0.95), fontsize=0.03, fill=(0, 0, 0)): """ Adds text to a provided image in numpy.ndarray format. Coords are in relative position """ img *= 255 img = Image.fromarray(img.astype(np.uint8)) width, height = img...
9fb2d9a6f77178c0104cf02b3b9db26b35b32750
3,610,686
import pickle def import_data(object_name): """Extract data from data dir.""" with open(f"data/{object_name}.pkl","rb") as my_file: return pickle.load(my_file)
d497048d53e3ba95bceccc172b7d47781c3bbc2c
3,610,689
def convert_to_nullable(input_val, cast_function): """For non-null input_val, apply cast_function and return result if successful; for null input_val, return None. Args: input_val (Any): The value to attempt to convert to either a None or the type specified by cast_function. The recognized ...
ba12f32d2bcced066257788188a2a9d91fcfec37
3,610,690
from typing import List def maxSubArray(nums: List[int]) -> int: """ Time: O(n) Space: O(1) """ local_max = 0 global_max = float('-inf') for n in nums: local_max = max(n, n + local_max) if local_max > global_max: global_max = local_max return globa...
f466884aa7b9d5865464e4db3c625abc8add23ec
3,610,691
def Nu_waste(Re_outtube_waste, Pr_coolwater_waste): """ Calculates the Nusselt criterion of coolwater. Parameters ---------- Re_outtube_waste : float The Reynold criterion, [dimensionless] Pr_coolwater_waste : float The Prandtl criterion, [dimensionless] Returns ------- ...
ae2dfb2cb026b1c8f05fa71a2936456f518fffd1
3,610,692
def fig_fire_assessment(assessment: SituationAssessment.WildfireCurrentAssessment, original_ignition: ty.Sequence[TimedPoint], max_time: float = np.inf) -> display.GeoDataDisplay: """Assessed wildfire map""" gdd = display.GeoDataDisplay.pyplot_figure(assessment.ge...
a9067b37a6f3df95e0d9de28a63774006876b8bf
3,610,693
def calc_pi(): """A crude (even for python) implentation of monte pi """ Nsample=100000000 x = np.random.rand(Nsample) y = np.random.rand(Nsample) count = np.sum(np.sqrt(x**2+y**2)<1) return 4*count/Nsample
4a99e5f2feeaef884a849cd88690ff86f6f8db93
3,610,694
def split_group(nsubj, ngroups): """Split the proposed group into random disjoint subgroups Parameters ---------- nsubj (int) the number of subjects to be split ngroups(int) Number of subbgroups to be drawn Returns ------- samples: a list of ngroups arrays containing the i...
4959819c55b871016840f2899e7c2d186b91a9ea
3,610,695
def reduce_table(table, params, exclude_any=None, exclude_all=None): """Returns the subset of a table that satisfy the specified variables table : pd.DataFrame table to reduce (pandas table) params : dict params that must all be satisfied (each value must be scalar) exclude : dict ...
9bdb133771aed147a3ad588a96e5a208f3729491
3,610,696
def get_maya_main_window(): """return the main window of maya :rtype: QtWidgets.QMainWindow """ ptr = mui.MQtUtil.mainWindow() return shiboken2.wrapInstance(long(ptr), qtgui.QMainWindow)
5536443f9a485a74808a9fde522b3a2496225e1a
3,610,697
def get_rank1(x, dict_y): """ Computes rank-1 distance between one vector given a set of other vectors. The higher the better. :param x: vector of appearances of the query object :param dict_y: dictionnary of appearances of the candidates objects """ # We create a 2D-array with all the feature...
b3dc3fbca3683df635863a5f951559548abc834b
3,610,698
def _align_column(strings, alignment, minwidth=0, has_invisible=True): """ [string] -> [padded_string] >>> list(map(str,_align_column( \ ["12.345", "-1234.5", "1.23", "1234.5", \ "1e+234", "1.0e234"], "decimal"))) [' 12.345 ', '-1234.5 ', ' 1.23 ', \ ' 1234.5 ', ' ...
67f302883e287ad8b8b622f9241cba4b5be92db3
3,610,699
def atan2(y, x) -> Expression[float]: """ Calculates the arc tangent of a given coordinate. """ return _binary_op("atan2", y, x)
b3ef45926fd63487c9b4cc5df3ab3a938ed87598
3,610,700
def parse_header(header): """Read header information from 2 bytes: - 1 byte for model id - 4 bits for metric - 4 bits for quality param """ model_id, code = header quality = (code & 0x0F) + 1 metric = code >> 4 return ( "YUV", inverse_dict(metric_ids)[metric], ...
e0d85ef9424f253ba18139003e421f58562aa96a
3,610,701
def piece_size(file_size): """ Based on the size of the file, we decide the size of the pieces. :param file_size: represents size of the file in MB. """ # print 'Size {0} MB'.format(file_size) if file_size >= 1000: # more than 1 gb return 2 ** 19 elif file_size >= 500 and file_size ...
8b48e98a22035f594c2582401cf4145acbf4d680
3,610,703
import random def create_mock_datapath(num_ports): """Mock a datapath by creating mocked datapath ports.""" dp_id = random.randint(1, 5000) dp_name = mock.PropertyMock(return_value='datapath') def table_by_id(i): table = mock.Mock() table_name = mock.PropertyMock(return_value='table'...
f9c1821d02e91f5fdfcc3b6b45f71df3da8c7746
3,610,705
import curses def get_gold(): """ Return the gilded symbol. """ symbol = u'\u272A' if config.unicode else '*' attr = curses.A_BOLD | Color.YELLOW return symbol, attr
1d0ebde3347e4dc48b83386482b22be63864a025
3,610,706
def _CharTraits_get_hdf5_memory_type(): """_CharTraits_get_hdf5_memory_type() -> hid_t""" return _RMF_HDF5._CharTraits_get_hdf5_memory_type()
c7467ff63725ad8e1f276abb1bf6356bbcb1d5d1
3,610,707
def operator_unassigned_ticket(request, structure_slug, structure, office_employee): """ Returns all unassigned tickets managed by operator :type structure_slug: String :type structure: OrganizationalStructure (from @is_operator) :type office_employee: OrganizationalS...
d272b2f81629ab8aa6b9d6671cf2cf238b1873fc
3,610,708
def raw_resolution(splitter=False): """ Round a (width, height) tuple up to the nearest multiple of 32 horizontally and 16 vertically (as this is what the Pi's camera module does for unencoded output). Originally Written by Dave Jones as part of PiCamera """ width, height = RESOLUTION i...
4579ee31fafe643ac1a6e8a8ac072bd50932c8b8
3,610,709
import math def odd_improvement(lst): """Calculates the improvement of odds compared to their base values. The higher above 0, the more the odds improved from base-value. The lower under 0, the more the odds deteriorated. Used https://en.wikipedia.org/wiki/Logit as a source for this formula. """ base...
4f8607d452fc96b57c9573ed0b07bd5a38791876
3,610,710
def next_named_type(*args): """ next_named_type(ti, name, ntf_flags) -> char const * Enumerate types. Returns mangled names. Never returns anonymous types. To include it, enumerate types by ordinals. @param ti (C++: const til_t *) @param name (C++: const char *) @param ntf_flags (C++: int) """ ...
5fbd4b059c4dbe57e86011f68ea587ff4bff0151
3,610,711
async def read_role_by_id( role_id: UUID, *, uow: IUnitOfWork = Depends(get_uow), current_user: models.User = Depends(get_current_active_admin), ) -> models.Role: """Gets a specific role by their unique ID.""" role = uow.role.get(role_id) if not role: raise HTTPException( ...
e2b82c240bbe5e34b1393d807e7d41884bc44c41
3,610,712
import socket def my_name(): """Returns the name of this BiBli""" # start with the database name = get_kv("name") # fall back to the hostname if not name: name = socket.gethostname() if "." in name: name = name[:name.index(".")] return name
a1f9ebb80ea250ecbc08fda38b27c51f5366fe78
3,610,713
def balanced_bst(sorted_list): """Return balanced BST constructed from sorted list.""" return balanced_bst_rec(sorted_list, 0, len(sorted_list))
f87c4402abbaf9f01cb8b2a340cfe21fa6e66820
3,610,714
def sql_query_tbr_create_table_dummy() -> TableDummySQL: """ returns table tbr create statement, dummy data insertion, and dummy data. The dummy data is not constructed correctly, all are equal to -1 for clarity. Message_id = -1 also ensures that first message_id will be set to 0. Example where the...
04e25404ada5b6e83e1e706387eb240403280418
3,610,715
from pixell import curvedsky import healpy as hp def enmap_from_healpix(hp_map, shape, wcs, ncomp=1, unit=1, lmax=0, rot="gal,equ", first=0, is_alm=False, return_alm=False, f_ell=None): """Convert a healpix map to an ndmap using harmonic space reprojection. The resulting map will be band-limited. Bright sou...
6bbc24db343de6ea843e3b183041a95fc4839f8c
3,610,716
def nearest(items, pivot): """Find nearest value in array, including datetimes Args ---- items: iterable List of values from which to find nearest value to `pivot` pivot: int or float Value to find nearest of in `items` Returns ------- nearest: int or float Valu...
0f8766e5680b3b271876a80055b99312bde8366f
3,610,717
def exclusively(f): """ Decorate a function to make it thread-safe by serializing invocations using a per-instance lock. """ @wraps(f) def exclusively_f(self, *a, **kw): with self._lock: return f(self, *a, **kw) return exclusively_f
58da6cd8822375f992ee33352310a01cf2def0e5
3,610,718
def _read_header(file_object): """Get the entire header from a file, and return as dictionary""" file_object.seek(0) if _header_read_one_parameter(file_object) != "HEADER_START": file_object.seek(0) raise ValueError("Missing HEADER_START") expecting = None header = {} while True:...
c2596c7a09bc5c9c1a4e2e7ffe6767951166f297
3,610,719
def _create_data_table( source: ColumnDataSource, schema: ProcSchema, legend_col: str = None ): """Return DataTable widget for source.""" column_names = [ schema.user_name, schema.user_id, schema.logon_id, schema.process_id, schema.process_name, schema.cmd_lin...
2c84211ed6d4ad3fb6c64bb7c6aeccb0e4d85695
3,610,720
def x_integral(a, b, c, x): """ function involved in computing the a_matrix (Rayleigh Ritz approx of the spectrum) @param a: @param b: @param c: @param x: @return: x_integral """ a_conj = np.conj(a) # helper variables to tidy up function k_0 = a * a_conj k_1 = np.sqrt((k...
e224188c62ad708b4afcd38e2fabde44d75f4a9b
3,610,721
def test() -> int: """ Testing that connection can be established :return: int """ try: connection = setup_connection() setup.test() cursor = connection.cursor() # Print PostgreSQL Connection properties print(connection.get_dsn_parameters(), "\n") # P...
65354917692311bfabe5822dd971be09c249c77d
3,610,722
def next_line_same_block(line, *args): """:type line: FrekiLine""" next_line = line.doc.get_line(line.lineno+1) return same_block(line, next_line)
1febf16717e1244d8cb293652645a7b7f238d782
3,610,723
def make_hash(hash_type="hashids") -> Hashids: """Factory function, can make different encoders in the future if needed""" def make_hashid() -> Hashids: """Build a Hashid instance based on Django's settings.py configuration""" try: config = settings.PROXYID["hashids"] sa...
7c58cc502c24bea3a7674b34f2baeeb0ec2e9846
3,610,725
def cast_op(x, dtype): """The operation takes input tensor `x` and casts it to the output with `dtype` Args: x (oneflow.Tensor): A Tensor dtype (flow.dtype): Data type of the output tensor Returns: oneflow.Tensor: A Tensor with specific dtype. For example: .. code-block::...
16f72392d88953a7a192591dbbb815688c756681
3,610,727
def decode(model_output: np.ndarray, labels: dict) -> str: """Decodes the integer encoded results from inference into a string. Args: model_output: Results from running inference. labels: Dictionary of labels keyed on the classification index. Returns: Decoded string. """ t...
009df297ab525ce02ec03e67e1ce30ca7e88b9cf
3,610,728
def CODE(string): """ Returns the numeric Unicode map value of the first character in the string provided. Same as `ord(string[0])`. >>> CODE("A") 65 >>> CODE("!") 33 >>> CODE("!A") 33 """ return ord(string[0])
0f680fe1e45156c00d0a5839e24f1619a456773f
3,610,729
def expected_weighted(da, weights, dim, skipna, operation): """ Generate expected result using ``*`` and ``sum``. This is checked against the result of da.weighted which uses ``dot`` """ weighted_sum = (da * weights).sum(dim=dim, skipna=skipna) if operation == "sum": return weighted_su...
5d3518de9bd52407cdcf140bd1c43dd5d78f9c37
3,610,731
def matching(strategies): """Returns the number of strategy1's result. Parameters ---------- strategies : list of str Names of used strategies. matching_number : int Number of matches. Returns ---------- count_win, count_lose, count_draw : int result of matches...
4a86867a7f477c24bbff357442ca997486224a08
3,610,732
def flask_apis(): """ List of Flask RESTful APIs """ apilist = ["Geolocate by IP Address", "Geolocate by Lat/Long", "Phone Number Location", "Street Address Validation", "Email Address Deliverablity", "IP Address to Consumer Profile"] return render_template( "flask.html", c...
f19909e38e42273c0a8e41161e2e32ef8f75f118
3,610,735
def train_model( X, y, df, model, num_epochs, skip_epochs, learning_rate, plot_frames_dir, predictions_plot_mesh_size): """ Train the model by iterating `num_epochs` number of times and updating the model weights through backpropagation. Parameters ---------- model: Pytorch model ...
88b1f27b68c645702fb4d40b3bba7249f2624fb0
3,610,736
def filter_get_project_samples_response(response, json_response): """Filter list project samples sensitive data from response.""" if "results" in json_response: for result in json_response["results"]: if "id" in result: result["id"] = MOCK_UUID if "client_id" in r...
e4102c9fe0b87d08c5906d3b9041e0d04d556758
3,610,737
def extract_dictionary(dataframe, column, key_list=None, prefix=None, separator='.'): """ Extract values of keys in ``key_list`` into separate columns. .. code-block:: python >>> df = DataFrame({ ... 'trial_num': [1, 2, 1, 2], ... 'subject': [1, 1, 2, 2], ...
b7e2c1db034b158e545fb6d81444c561a294bc23
3,610,738
def BetaPrime(alpha, beta, tag=None): """ A BetaPrime random variate Parameters ---------- alpha : scalar The first shape parameter beta : scalar The second shape parameter """ assert ( alpha > 0 and beta > 0 ), 'BetaPrime "alpha" and "beta" paramete...
d3fccb98cf03445fa85d8d2e8f2c201561b5a5fd
3,610,739
def get_sweep_parameters(parameters, env_config, index): """ Gets the parameters for the hyperparameter sweep defined by the index. Each hyperparameter setting has a specific index number, and this function will get the appropriate parameters for the argument index. In addition, this the indices wi...
4fe3ce005cc5a90694e6386737c6df2d18d41f49
3,610,740
import numpy def load_values(files): """ Loads the sasa values from the files in the files dictionary. Returns the maximum and minimum values. Values are loaded into the "files" structure. """ min_val = float("inf") max_val = 0.0 for filename in files: files[filename]["values"] = ...
a03ff0e928c192f57b911445b216f4baf0d88d7d
3,610,741
def reproject_helper(args, raster_tuple, procnum, return_dict, resolution): """ Helper function for reprojection """ (pre_post, src_crs, raster_file) = raster_tuple basename = raster_file.stem dest_file = args.staging_directory.joinpath('pre').joinpath(f'{basename}.tif') try: return_...
36f053946f4747ec8e4df95b948882c1eed18d5b
3,610,743
def create_board(user, **params): """Helper function to create a new board""" defaults = { 'title': 'Test Board', 'code': 'tb' } defaults.update(**params) return Board.objects.create( user=user, **defaults )
cdd3fd076480e44e4a5ff14a5e98fedf2d77461f
3,610,744
def transform(resp_type): """A decorator to take a RundeckResponse and pass it through one of the is_transform marked functions above """ def inner(func): @wraps(func) def wrapper(self, *args, **kwargs): results = func(self, *args, **kwargs) try: ...
60d94e3448aa1bd199fbb835f86e1005106daab0
3,610,745
def create_attributes_filter_rules_list(raw_attributes_filter_rules_list): """Validate and parse a list of attributes filter rules :param raw_attributes_filter_rules_list: A list of filter rules of type `attribute`, formatted as strings. :return The list of filter rules that matches the provided...
f5cf78bb6067b5cbb3616ea99048ef599298034c
3,610,746
def mount( storage=None, name="", storage_parameters=None, unsecure=None, extra_root=None ): """ Mount a new storage. .. versionadded:: 1.0.0 Args: storage (str): Storage name. name (str): File URL. If storage is not specified, it will be infered from this name. ...
fa446f40958b50828e1a9142cdb46f35d9ec0243
3,610,748
import numpy def labeled_comprehension(input, labels, index, func, out_dtype, default, pass_positions=False): """ Compute a function over an image at spec...
3475b331c7ba522bf71be264725e247687c7cf39
3,610,749
from typing import Optional def get_resub(db: Session, *, name: str) -> Optional[Resub]: """Get the resub with the given name.""" return db.query(Resub).filter(Resub.name == name).first()
15418f7f594f696cb04d33b9a5a332f447405265
3,610,750
def smooth_control_inputs_gaussian(log, sigma): """ Bind smoothed control inputs to the driving log using a Gaussian filter. This more closely preserves the mean than the exponential smoothing (but the outputs have so far been not that different). """ for control_column in CONTROL_COLUMNS: ...
a6baa03b5ad70537a68ba6581c56f005f0e3d0af
3,610,751
from typing import Optional from typing import Dict from re import A def get_scaled_sum_aggregations(field_to_sum: str, pagination: Optional[Pagination] = None) -> Dict[str, A]: """ Creates a sum and bucket_sort aggregation that can be used for many different aggregations. The sum aggregation scaled the v...
4210903774db8f746eabd48748f0d1016b3d59fe
3,610,753
def _get_versions(client, bucket, key): """ Returns all the version IDs for a key ordered by last modified timestamp. """ resp_iterator = client.get_paginator("list_object_versions").paginate( Bucket=bucket, Prefix=key ) try: versions = [version for page in resp_iterator for vers...
32ab35529997c97c3a83e54f9c3a59bbc82d1498
3,610,754
def associate_new_data(dataframe, df_studies_by_funder): """Merge two dataframes based on Case Study ID. Takes a dataframe with the case study information and merges it with another dataframe that contains case study IDs and some other data (e.g. funders, disciplines) :params: a dataframe with case st...
ae86739dae8699865d407e8fedfa97c26902578d
3,610,755
def infer_feature_schema(features, graph, session=None): """Given a dict of tensors, creates a `Schema`. Infers a schema, in the format of a tf.Transform `Schema`, for the given dictionary of tensors. If there is an override specified, we override the inferred schema for the given feature's tensor. An over...
dda42e6e76cf628fc7dac10afa0e169f677d35c5
3,610,756
def _parse_timestamp(exit_or_boot_timestamp): """ Parse boot_timestamp or exit_timestamp and return datetime object or None. """ timestamp = exit_or_boot_timestamp.strip(':') if timestamp: return datetime_parse(timestamp).replace(tzinfo=utc) else: return None
790e7fb94a93c3dcc0121f19dede7090563afd78
3,610,757
def authorization(auth, preserve_user=None, white_list=None): """ MW для авторизации. :param auth: сервис авторизации :param white_list: Список контроллеров без проверки :return: вызов следующей по списку MW """ bypass = set(white_list or []).__contains__ def wrapper(nxt, controller, a...
ec459ea7f1581449561cd1079bec3b5caab1d44b
3,610,758
def format_call(__fn, *args, **kw_args): """ Formats a function call, with arguments, as a string. >>> format_call(open, "data.csv", mode="r") "open('data.csv', mode='r')" @param __fn The function to call, or its name. @rtype `str` """ try: name = __fn.__name__...
0dce4bf0166f59f810063596f872b9f641f84234
3,610,759
import torch def rgb_to_yuv(image: Tensor) -> Tensor: """Convert an RGB image to YUV. Image data is assumed to be in the range of [0.0, 1.0]. Args: image (Tensor[B, 3, H, W]): RGB Image to be converted to YUV. Returns: yuv (Tensor[B, 3, H, W]): YUV version of...
a891ac3564f8bec2a40163b86e2bab0753749fc2
3,610,760
def method(obj, method, **kwargs): """ Call an object method. {% method object method **kwargs %} """ try: return getattr(obj, method)(**kwargs) except Exception as exception: raise TemplateSyntaxError( 'Error calling object method; {}'.format(exception) )
bdc034fcc1e865bd15ff4064a5b64d8f37c3d0a7
3,610,762
def make_layout() -> Layout: """Define the layout.""" layout = Layout(name="root") layout.split( Layout(name="header", size=3), Layout(name="main", ratio=1), Layout(name="footer", size=7), ) layout["main"].split_row( Layout(name="side"), Layout(name="body", r...
30839d6c5d4a3b2ea33e737d9967071437cce7fd
3,610,763
import math def _get_precursor_mz_splits(precursor_mzs: np.ndarray, precursor_tol_mass: float, precursor_tol_mode: str, batch_size: int) -> nb.typed.List: """ Find contiguous blocks of precursor m/z's, relative to the precu...
1b0f0cf9cdfadabac750a44e0ba599ee49f6fdc9
3,610,764
def generate_fieldnames(value, prefix=''): """ """ fieldnames = [] if isinstance(value, dict): prefix = prefix + '.' if prefix != '' else '' for key in sorted(value.keys()): subnames = generate_fieldnames(value[key], prefix='{}{}'.format(prefix, key)) fieldnames.e...
e5ba2a4bc8786aa37542535e6c2bf2dd11b76648
3,610,765
def treebank_to_short_name(treebank): """ Convert treebank name to short code. """ if treebank in treebank_special_cases: return treebank_special_cases.get(treebank) if treebank.startswith('UD_'): treebank = treebank[3:] splits = treebank.split('-') assert len(splits) == 2, "Unable ...
c6eca6d1a8e5b5c9fb73ac75716421cee630484b
3,610,766
def solve_chroma_sub(upper_rgb, lower_rgb, xyz_t, l, h, l_val, h_val, c): """ 与えられた条件下での Chroma の限界値を算出する。 """ upper_rgb = [ upper_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)] lower_rgb = [ lower_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)] xyz_t = [ ...
54905abf0639ab4067e251cf05337017c8d12dfd
3,610,767
def ProcrustesCompare(mat1,mat2): """ Compares similarity of two matrices according to weighted R^2 among their individual components. R^2 of inidividual components weighted by their magnitude to generate composite score. Matrcies aligned prior to comparison using orthogonal procrustes (rotation only). ...
d010b0156f0f9e2b0ae1c44205c75167700f91d4
3,610,769
def _get_value_pos(line, delim): """ Finds the first non-whitespace character after the delimiter Parameters: line: (string) Input string delim: (string) The data delimiter """ fields = line.split(delim, 1) if not len(fields) == 2: raise Exception(f"Expected a '{delim}' ...
8337c92045f2d3ccb91479502b30c7d191e53f34
3,610,770
def norm(data): """Normaliza una serie de datos""" return (data - data.min(axis=0))/(data.max(axis=0)-data.min(axis=0))
9e2a23d8d734a4e77ec99c0dcb0ae4d85f971ede
3,610,771
def area(ds, Nmax=None, label_name='labels', cell_dim_name='CellID', dims='STCZYX'): """ Compute the area of each labelled region in each frame. """ if isinstance(dims, str): S, T, C, Z, Y, X = list(dims) elif isinstance(dims, list): S, T, C, Z, Y, X = dims def padded_area(int...
24b342b1abc0248171da82925d49bbd89e4f59bf
3,610,772
from pathlib import Path def create_default_compiler_error_handler( experiment_handle: 'ExperimentHandle', project: Project, report_type: tp.Type[BaseReport], output_folder: tp.Optional[Path] = None, binary: tp.Optional[ProjectBinaryWrapper] = None ) -> PEErrorHandler: """ Create a default...
7a3948b7d8eb88c094cea8bdf7d711fe65cbc170
3,610,773
def format_size(size): """格式化大小 >>> format_size(10240) '10.00K' >>> format_size(1429365116108) '1.3T' >>> format_size(1429365116108000) '1.3P' """ if size < 1024: return '%sB' % size elif size < 1024 **2: return '%.2fK' % (float(size) / 1024) elif size < 1024...
66aa2301350def395e32bae87dabccc18a126786
3,610,774
from typing import Counter def vectorize(tokens_list, feature_fns, min_freq, vocab=None): """ Given the tokens for a set of documents, create a sparse feature matrix, where each row represents a document, and each column represents a feature. Params: tokens_list...a list of lists; each subl...
a6b5addc84c052a48d7bcca98919d4760d5afde7
3,610,776
def convert_category_to_continuous(df: pd.DataFrame): """Convert category to continuous value started from the trial. 5 sec and 9 sec is flushing time. See "makeDataFrame" in basicChara for reference code. Args: df: cleaned dataframe. Ex., pL.merged_structured_df. """ df = df.cop...
2c98594cf8dd44b74c1e07e76a764616dbe81694
3,610,777
def closest_contour_center(depth_image, contours): """ Takes a depth_image and list of contours. Finds the center of each contour, then finds which center is closest. Returns the coordinates for that center in y, x format. """ depth_image = cv.GaussianBlur(depth_image, (3, 3), 0) contour_centers = [] for con...
297c537e9e0664b2143f333c326ad798213e89ed
3,610,778
def get_download_url_for_platform(url_templates, platform_info_dict): """ Compare the dict returned by get_platform_info() with the values specified in the url_template element. Return true if and only if all defined attributes match the corresponding dict entries. If an entry is not defined in the url_...
a5eb81ff5aec82b24dc6128e908519dbee4e13e3
3,610,779
from typing import Union from typing import List from typing import Dict def determine_boundaries(df: pd.DataFrame, bucket_mapping: BucketMapping) -> Union[List, Dict]: """ Determine mapping boundaries. Given a dataframe with pre_bucket and bucket column, determine the boundaries that can be passed t...
c057decf7a0ff05a830aa29e47adcd44f3d120a6
3,610,780
def load(filepath): """ Load in metadata from filepath. Args: filepath (string/path): path to file. Returns: pd.DataFrame: dataframe containing metadata. """ tracks = pd.read_csv(filepath, index_col=0, header=[0]) # Format the data. # Remove "tabs" from strings etc. ...
58f111c95fa85b22b920931bd6af60a330d3fe5a
3,610,781
def compute( applied_voltages, resistances, r_i=None, r_i_word_line=None, r_i_bit_line=None, **kwargs): """Computes branch currents and node voltages of a crossbar. Parameters ---------- applied_voltages : array_like Applied voltages. Voltages must be supplied in an array of sha...
76f5c80bc1f0cf248d63bac4a3564d64c64facfb
3,610,782
def TypeNameToLogModel(type_name): """Return log model associated with type_name.""" if type_name == BitLockerVolume.ESCROW_TYPE_NAME: return BitLockerAccessLog elif type_name == DuplicityKeyPair.ESCROW_TYPE_NAME: return DuplicityAccessLog elif type_name == FileVaultVolume.ESCROW_TYPE_NAME: return F...
fcfc65a2c6a534bc73e2e9a59001d93ed8a3bb46
3,610,783
def grad_logdet(inv_metric: np.ndarray, jac_metric: np.ndarray, num_dims: int) -> np.ndarray: """Computes the gradient of the log-determinant of the Riemannian metric. Args: inv_metric: The inverse of the Riemannian metric. jac_metric: The Jacobian of the metric tensor. num_dims: The nu...
8d56cb3be084fa8c7030bf86c7e068167ea9263e
3,610,784
def get_code(): """ return code from codes.txt and """ codes = [] with open(codes_file, "r") as cf: for num, line in enumerate(cf.readlines()): if num == 1: if line.startswith("Need"): raise Exception(line) codes.append(line) code = cod...
1e3343e245e3c2ba627feb6364f3bf3dba487141
3,610,785
def get_unicode_category(prop): """ Retrieve the unicode category from the table """ p1, p2 = (prop[0], prop[1]) if len(prop) > 1 else (prop[0], None) return ''.join([x for x in _unicode_properties[p1].values()]) if p2 is None else _unicode_properties[p1][p2]
790a6bc54ea7e0839735d681e074b3de7a044123
3,610,786
def pink_noise(nstep_out, pow_spec=None, f=None, fmin=None, alpha=-1, **kwargs): """ Generate random pink noise Parameters ========== nstep_out : int Desired size of the output noise array. If smaller than `pow_spec` then it just truncates the results to the appropriate size. If...
e4261a5c78cdd68df04a0437c517fe97d1d54ff1
3,610,787
import getpass def get_username() -> str: """ Returns username lowercase >>> username = get_username() >>> assert len(username) > 1 """ _username = getpass.getuser().lower() return _username
aa7c5d2974502bd411cd1a77218ca74171d3dc71
3,610,788
def fetch_ALL_standings(): """ This returns the complete set of all the standings in the league, namely IGnobels and general/points. It is used by other functions """ dic_stand = { 'Caduti': 'infortunati', 'Cartellino Facile': 'cartellini', 'Porta Violata': 'goal_subit...
f586cbc0a917cc0c23a0ead083b669deba61b458
3,610,789
def extract_id(source): """ Attempts to extract an ID from the argument, first by looking for an attribute and then by using dictionary access. If both fail, the argument is returned. """ try: return source.id except AttributeError: pass try: return source["id"] ...
7ec169cfd6edf70c9d414ec61edc3bf514a80e02
3,610,790
import shutil def pytest_report_header(config): """Add header information for pytest execution.""" return [ "LAMMPS Executable: {}".format( shutil.which(config.getoption("lammps_exec") or "lammps") ), "LAMMPS Work Directory: {}".format( config.getoption("lammps_...
dc07ae457cc49a1fc1ac43643a193bb3b6a84399
3,610,791
def transform_score(data, score_card): """ 特征映射回分值 Args: data: 特征表 score_card: 评分卡 Returns: 返回转化后的得分 """ base_score = score_card[score_card['Bins'] == '-']['Score'].values[0] data['Score'] = base_score for i in range(len(data)): score_i = base_score ...
d3afafeca40f0bcf97e522cb32b4f139d1c0321e
3,610,792
def load_query(asset): """Helper to load test asset and parse as Query, returning.""" yaml_query1 = load_test_asset(asset) parser1 = mql.QueryParser() return parser1.parse_ystr_query(yaml_query1)
79cf824066dda4862bd59d8d6ddb94a465d62e3f
3,610,793