content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def contenttype(filename, default='text/plain'): """ Returns the Content-Type string matching extension of the given filename. """ i = filename.rfind('.') if i >= 0: default = CONTENT_TYPE.get(filename[i:].lower(), default) j = filename.rfind('.', 0, i) if j >= 0: ...
7dd27aa87db1197887be4aaa20f489d1b19f7258
53,437
import pdb def _validate_mean_cols(df, fix=False): """ Validates contents of mean column in a given dataframe """ col = 'mean' if col in df.columns: # Check if columns are floats if not df[col].values.dtype == float: # Check whether values can be interpreted as floats...
4461a84ca46c38da24064fbbd1d69b88e0c6ba84
53,438
from datetime import datetime from typing import List from typing import Dict def search_async(start: datetime.datetime, end: datetime.datetime, programs: List[str] = None, platforms: List[str] = None, instrument_types: List[str] = None, ...
e261774eb3e31461d5ff5ce6c2f82bfe3cdc0859
53,439
def delete_aip(mets_file): """Delete the file""" mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first() db.session.delete(mets_instance) db.session.commit() return render_template('deletesuccess.html')
415696d5ba75934de02ea23e3a6c77c3a9a19e45
53,440
import json def bel_process_pybel_neighborhood(): """Process BEL Large Corpus neighborhood and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = bel.process_pyb...
2ca33f051d87c65cc8b4e493a555175d1adcda1b
53,442
def _induced_power_cwt(data, sfreq, frequencies, use_fft=True, n_cycles=7, decim=1, n_jobs=1, zero_mean=False): """Compute time induced power and inter-trial phase-locking factor The time frequency decomposition is done with Morlet wavelets Parameters ---------- data : array...
9c847ce3b329fa5710fcc97353ce65075a08b65c
53,443
def clean_tag_text(tag): """ Convert a tag to a string, with all extra whitespace removed. """ if tag is None: return None # Get tag text and remove soft hyphens added by Word text = tag.get_text().replace('\xad', '') return RE_CLEAN_TEXT.sub(' ', text).strip()
e025101484d03cdb29a39b80863f9f4c802160f7
53,444
def get_xfmr_pose(pose: str, dim: int, **kwargs) -> nn.Module: """ Return position encodings layer Args: pose (str): positional encoding type, {abs|rel|xl|conv1d} """ if pose not in PosEncodings: raise ValueError(f"Unsupported pose layer: {pose}") return PosEncodings[pose](dim, *...
adce1b7369322238d0cbd2fbcc0d4394c89dfbfa
53,445
def base64_middleware(): """Provide a middleware configured with the Base64Backend.""" return EPDBServe(backend=Base64Backend(), serve_options={"port": 9000})
02885892ae4409e743183f0b3a43824d8de53456
53,446
from numpy import log def log_mean(T_hi, T_lo, exact=False): """ compute the logarithmic mean """ if exact: return (T_hi-T_lo)/log(T_hi/T_lo) else: d = T_hi - T_lo return T_hi - d/2*(1 + d/6/T_hi*(1 + d/2/T_hi))
dcae1d753c416a117dc2f8502454d18f9413fc36
53,447
def getheader(header_text, default="ascii"): """Decode the specified header""" headers = decode_header(header_text) header_sections = [(text.encode(charset or default)).decode() if type(text) == str else text.decode(charset or default) for text, charset in headers] return ''....
44da35add8dd06899a6d73c104e6606d62ee2360
53,448
from pathlib import Path import json def load_json(fp_in): """Loads JSON and returns items :param fp_in: (str) filepath :returns: data from JSON """ if not Path(fp_in).exists(): log.error('file does not exist: {}'.format(fp_in)) return {} with open(str(fp_in), 'r') as fp: data = json.load(fp) ...
e6689b5f5650c34185adf9cb0d0de2e9a75aad71
53,449
def uniform_glorot(nin, nout, mean=0., gain=1., **kwargs): """ Uniform Glorot Initialization :param nin: :param nout: :param mean: :param gain: float or 'relu' :return: """ if gain == 'relu': gain = np.sqrt(2) logger.warn('Uniform Glorot weight with {} fan-in, {} fan-out,...
d3e625c81fae23478e526bdb3b093fc64660ce9a
53,450
def elevate(command, param="", wait=False): """ Execute a shell command with elevated rights when the current user can have the privilge. Deisgned to be used with Windows Vista, 7 and 8. It also works on Windows XP although it is not necessary on many occasions. It may pops User Access Con...
a3c5131862e7e6baff0e3937f5d004ef7b6515a5
53,451
import torch def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor: """ Computes pearson correlation coefficient. Args: preds: estimated scores target: ground truth scores Example: >>> from torchmetrics.functional import pearson_corrcoef >>> target = torch.ten...
8de3fea852585d14de6595f411ce15a14df83317
53,452
def get_local_env_method(method): # pylint:disable=too-many-return-statements """get a local environment method based on its name""" method = method.lower() if method.lower() == "crystalnn": # see eq. 15 and 16 in # https://pubs.acs.org/doi/full/10.1021/acs.inorgchem.0c02996 # for ...
778f98153c53380b25339f21d0cda123bd642590
53,453
def name_for(obj): """ Get a name for something. Allows overriding of default names using the `__alias__` attribute. """ if isinstance(obj, str): return obj cls = obj if isclass(obj) else obj.__class__ if hasattr(cls, "__alias__"): return underscore(cls.__alias__) els...
f875cf8233c3bd8443d28c61de9f413b4c82f524
53,454
def reduceSet(setList): """Step through a list of sets and combine sets that overlap. This will create a unique list of sets, where each set contains the headers of reads that optical duplicates.""" setList2 = [setList[0]] for item1 in setList[1:]: inSetList2 = False for item2 ...
4e7e763ae78d5cf97fa122f991b01529e12c86a5
53,455
def weird_compare(interval, start, end): """ This is a function that is used later on in data_upscale, to add a corrective integer (either 1 or 0), when that function checks whether the image it is working on has reached the border. This function is not expected to be used anywhere outside data_upscale....
f4b67c2b740a318ad659d1001bd14d402dad9e21
53,456
def make_word(letters, beginnings=[], endings=[]): """Return word dictionary""" return { 'word': ''.join(letters), 'letters': letters, 'beginnings': beginnings, 'endings': endings, }
0b53fd8e26d2ca80e8c54ffa08f9473fb7b9f902
53,457
def dependence_vector(iter_vars, iter_slices, source, sink, invariant=None): """ Uses ISL for dependence testing and returns the dependence vector. iter_vars: Iteration variables iter_slices: Iteration starts, stops and steps; stop is inclusive! source, sink: Subscript objects invariant: Loop i...
015b6959c0b77b0e5bdbc45f6d66df7033fb71e8
53,458
import importlib def get_role(classpath): """Get a role implementation by its path name.""" return importlib.get_class(classpath, __name__)
6c124221085f18d08719b74c41e73e17e84c1689
53,459
import torch def compute_batch_accuracy(output, target): """Computes the accuracy for a batch""" with torch.no_grad(): batch_size = target.size(0) _, pred = output.max(1) correct = pred.eq(target).sum() return correct * 100.0 / batch_size
b8ac6b891b2b1abc39cd9549c2d2a4a79c129577
53,460
import psutil def get_ram_memory(units="Mb"): """Get the RAM memory of the current machine. Args: units (str): Units [bytes, Kb, Mb, Gb] Returns: float: Memory size. Examples: >>> num = get_ram_memory("Gb") >>> num >= 4 True """ s_bytes =...
144a09c631f94d4971b4c329bcd065cff77d16c6
53,461
def gsl_blas_zswap(*args, **kwargs): """gsl_blas_zswap(gsl_vector_complex * X, gsl_vector_complex * Y) -> int""" return _gslwrap.gsl_blas_zswap(*args, **kwargs)
d069e57bf92b21ceb5d2e7d64b3f4d939599d9b8
53,462
import json def create_user(): """Endpoint to create a user data.""" data = json.loads(request.data) password = data['password'].encode('utf-8') hashed = bcrypt.hashpw(password, bcrypt.gensalt()) user = User(username=data['username'], password=hashed.decode('utf-8'), phone=data['phone'], ...
9edea341aa97107acf7e018761b89d4c0c91f953
53,463
def set_mon_sites(node: CephAdmin, tiebreaker_node) -> bool: """ Adds the mon daemons into the two sites with arbiter node at site 3 as a tie breaker Args: node: Cephadm node where the commands need to be executed tiebreaker_node: name of the monitor to be added as tie breaker( site 3 ) ...
b5f6cf9d06bbe8ac9664afc9e5b3d97a5a44aea4
53,465
def conv1d( ni: int, no: int, ks: int = 1, stride: int = 1, padding: int = 0, bias: bool = False ): """Create and initialize a `nn.Conv1d` layer with spectral normalization. Unmodified from https://github.com/fastai/fastai/blob/5c51f9eabf76853a89a9bc5741804d2ed4407e49/fastai/layers.py """ conv ...
b7f0584c0c6ffe7ef5bd24403125826f6e8225a2
53,467
def _GetPrincipalQuantumNumber(atNum): """ *Internal Use Only* Get the principal quantum number of atom with atomic number equal to atNum Parameters: atNum: int Returns: PrincipalQuantumNumber: int """ if atNum <= 2: return 1 elif atNum <= 10:...
3176377b74a8ff8dd41b710137c2b2e79b9a1d53
53,468
import functools def wrap_single_convertor(convert_single): """ Wraps a ``__ua_convert__`` defined for a single element to all elements. If any of them return ``NotImplemented``, the operation is assumed to be undefined. Accepts a signature of (value, type, coerce). """ @functools.wraps(...
9a937f5366b896d95c091db870952b923f5323fe
53,469
def rot(theta): """returns a 2D-rotation matrix with rotation angle theta""" R = np.array(((cos(theta), -sin(theta)), (sin(theta), cos(theta)))) return R
f67b88a7c29300f88884f5130f1d16c99a00bb1e
53,470
def integrate(params, t, gamma_max, nu_max, phiR, Kd=Kd): """ Integrates the system of differential equations, including the dilution factor and assumes that nutrient concentration is high enough such that nu ≈ nu_max. """ # Unpacking Mr, Mp, cAA = params gamma_max, nu_max, phiR = args...
d055c0a11c1dd3501f22ab4a060e4a3652746fbf
53,471
def build_streamflow_cube(nc_files, river_ids=None, consistent_id_order=True): """Reads streamflow from several NWM files into a single array. Reads streamflow from several files into a single array. Each file from the National Water Model represents a single time step. This function can be used to rea...
d08149ff7133026d4afc8992f998b11384aa233b
53,472
def mutate(mushroom, i): """ Randomly flips one bit in a mushroom bit string""" return mushroom ^ 1 << i
ffac7c56cfe455928fcbb833d363441ef9a2a8a7
53,473
def avoid_multiple_update(func): """Decorator to prevent handlers to update multiple times.""" def wrapper(self, attr, old, new): if self.in_update: return self.in_update = True func(self, attr, old, new) self.in_update = False return wrapper
d35e9add88ddb62d1368ff0fbf94e9637518c249
53,474
def zeros(shape, dtype=float): """ Array of zeros. Return an array of given shape and type, filled with zeros. Parameters ---------- shape : {sequence of ints, int} Shape of the array dtype : data-type, optional The desired data-type for the array, default is np.float64. ...
50cc1bafdc2b1f25f40d5215846ad5cf8b76ec00
53,475
def node_draw_color(node): """given a row of a nodes() dataframe, return the color it should be drawn""" if 'draw_color' in node.axes[0]: # if this value has already been calculated return node.draw_color color = '#d2d2e6' # (210, 210, 230) #default color if 'HoursFlooded' in node and...
42fc4c392d872f94a58c753c1c62569b1302fd0a
53,476
from typing import Callable def tabulated(dr: Array, spline: Callable[[Array], Array], **unused_kwargs) -> Array: """ Tabulated radial potential between particles given a spline function. Args: dr: An ndarray of pairwise distances between particles spline: A function computing the spline ...
0118cc34a8b8c0e80223aca572a13f10121479ea
53,477
import numpy as np def create_slice_mask(plane_dict, infile_dims): """Create a binary array defining a mask covering the area below a given plane in the 3D image. :type plane_dict: dict :param plane_dict: A dictionary matching z voxel coordinates to corresponding (x,y) coordina...
ca25e627dc93b3828b7ea49c139e1f9fc5950f6e
53,478
def postprocess_braces(value, **options): """Remove any braces from a string value.""" if bibpy.is_string(value): return "".join([e for e in bibpy.parser.parse_braced_expr(value) if e not in '{}']) return value
78db8d678a9d023394e7e9a59f2cd82d565c0cdf
53,479
def row2dict(row): """ Converts a row of SQLAlchemy into a dictionary :see: http://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict :param row: SQLAlchemy row :return: dictionary """ if row is None: return None d = {} if hasattr(row, '__table_...
f5ccfcc919e79340b668d1f99c52223fa48ea5f8
53,480
from typing import List import json def retrieve_by_index(index_dir_path: str, question: str, top_k: int=1) -> List[str]: """ Retrieves the most relevant passages to a question, using the indexed embedding of the passages. :param index_dir_path: path to the index and texts. :param question: :para...
45a72078bab65b8d1bb56997c839f4f350fcd247
53,481
def unsigned_to_signed(seq, width): """ Convert unsigned integer to signed. """ out = [] k = pow(2, width) for x in seq: if x >= k/2: x -= k out.append(x) return out
b7b90ff4de576bee2e91af27f6fc3b509608ef34
53,482
import signal def ssim(img1, img2, cs_map=False): """Return the Structural Similarity Map corresponding to input images img1 and img2 (images are assumed to be uint8) This function attempts to mimic precisely the functionality of ssim.m a MATLAB provided by the author's of SSIM https://ece....
dbd347bc4cf026cb0e0ffef17812f7783a3aa921
53,483
def _hash(host, username, password, hasher_params): """Performs a hash operation on the given host with the given hasher parameters (hasherWsParams) and returns a hasherWsResult record with these fields: - blockFileDataHandler (base64Binary) - blockFileName (string) - bytesHashed (long) - elapse...
d9c7330c1c2df54744c15f42d347fa4fd28254c1
53,484
def l2_distance(x, y): """Computes cosine similarity between all pairs of vectors in x and y.""" x_expanded, y_expanded = x[:, tf.newaxis], y[tf.newaxis, :] return tf.sqrt(tf.reduce_sum((x_expanded - y_expanded)**2, axis=-1))
a6fdf06c7facba2f63799786dfa8085602e8c070
53,485
def per_device_batch_size(batch_size, num_gpus): """For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. ...
5191fb313ba26026cb1bd61173a3f983ca42f5b6
53,486
def organisation_information_save(request,organisation_id): """ :param request: :param organisation_id: :return: """ # ADD IN PERMISSION CHECKING # Get the form data form = OrganisationForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) ...
e183b2b79064b86d3007b55ca63ce0012c9c63c7
53,487
from typing import Optional from typing import List from typing import Tuple def _monkey_patch_python_domain_to_resolve_params(): """Adds support to the Python domain for resolving parameter references.""" PythonDomain = sphinx.domains.python.PythonDomain # pylint: disable=invalid-name orig_resolve_xref = Pyt...
408e0fa3e3019b0ea3ebbcc1d0af03e13853fa0e
53,488
def containerhasprefix(obj, prefix): """ Returns whether obj's container starts with prefix. """ return obj.container.name.startswith(prefix)
dcf4b14cfa1ac15355e7db5110be55b623e35f20
53,489
def _variance(mean_variance, samples): """Perform final variance calculations. `mean_variance` and `samples` were pre-recorded with `options.record.reduction._variance`. This operation only calculates total running variance. This function is applied on per-recording basis (per layer to be exact)....
0bcc9705205304d8338843a3c09c8ae1f2314bb6
53,490
import tqdm def trange(*args, **kwargs): """ A shortcut for tqdm(xrange(*args), **kwargs). On Python3+ range is used instead of xrange. """ return tqdm(_range(*args), **kwargs)
991ff44ab461b9c78639b0d4d0621d959f0a0a2b
53,492
from pathlib import Path import json def load_event_schema(event_type, suffix=None): """Load an Avro schema for a Slack Events API event from the local app data. This function is memoized so that repeated calls are fast. Parameters ---------- event_type : `str` Name of an event type,...
7741549c1703ed300a25081274dd42dfc8e59eec
53,493
import six def choose_part_ranges(content_length, minimum_part_size): """ Returns a list of (offset, length) for the parts of a large file. :param content_length: content length value :type content_length: int :param minimum_part_size: a minimum file part size :type minimum_part_size: int ...
28acbe2df14d6f54a95ab74c18e410a076354187
53,494
def line_too_long(editor, item): """ Pylint line-too-long method """ line_no = item.line_no error_text = editor.lines[line_no] new_lines = line_split(error_text, 100) if not new_lines: LOGGER.info("Could not split: {0}".format(error_text)) result = (line_no, 0) else: asse...
cbd450bcac63e46482fec2248939548bd6931399
53,495
from operator import and_ def remove_actions_that_are_not_wildcard_arn_only(db_session, actions_list): """ Given a list of actions, remove the ones that CAN be restricted to ARNs, leaving only the ones that cannot. :param db_session: SQL Alchemy database session object :param actions_list: A list of ...
b8d74e56fb0fe305e24ebb1b865066b8fdc68daf
53,499
def file_import(**kwargs): """ Fast import of exported log files containing messages from a bus. Optional arguments: - folder (str): Custom folder to import log files from. - limit (int): The maximum number of lines/messages to read each time. Default value is '5000'. - idle_sleep (int): ...
d284dde2623e5f7ff982865e99eeaebbb5e7fedd
53,500
def main(useruid: str, old_passwd: str, new_passwd: str, email: str): """ 修改個資 """ user = User(useruid) session = get_empty_session() session.login( user.userid, old_passwd, session.courses.index(user.course) + 1) if session.active: session = get_session(useruid) i...
7a303323a6421c4fd850ede18c85af1cd9cd5f72
53,501
import requests def check_user_permission(access_token, job_requires): """ Check if user has permission to run the job or not Args: access_token(str): the access token job_requires(dict): requirements so that job can run { "arborist_url": "http://arborist-servi...
c1069364b8d59965f78367e64b88206062c60b2b
53,503
def FiskJohnsonDiscreteFuncExtrapolate(rho,F0,T): """Extrapolate samples of transform to sequence of target coordinates. Extrapolate sequence of (few) Fourier-Bessel transform samples to sequence of target coordinates following Eq. (9) of Ref. [1]. Args: rho (numpy array, ...
ae5c86d1e616dc77404165d9df9a0e8b063cec61
53,504
def media_entity(props): """ Helper to construct elements of the form <embed embedtype="custommedia" id="1"/> when converting from contentstate data """ return DOM.create_element('embed', { 'embedtype': 'wagtailmedia', 'id': props.get('id'), 'title': props.get('title'), ...
3cdaef6c88e88551a594a38f99c2c48344b27163
53,505
def ws_s_dt_wa_gauss(ws, wa, *params): """Models the function \\[ \\frac{a_2}{1 + e^{a_0 - a_1x}} - a_3x^2 + + a_4\\exp\\left(\\frac{-(y - a_5)^2}{2a_6}\\right) + a_7\\exp\\left(\\frac{-((360 - y) - a_8)^2}{2a_9}\\right) \\] """ wa = np.asarray(wa) return ( s_sha...
3c17ab5adb3ff71257f360d5caf3eb6a72e2b823
53,506
import io def get_version(relpath): """Read version info from a file without importing it""" for line in io.open(join(dirname(__file__), relpath), encoding="cp437"): if "__version__" in line: if '"' in line: return line.split('"')[1] elif "'" in line: return line.split("'")[1]
0e06b67f0aa44d84b9dfddfdb040e63534329fe8
53,508
def slice_array_d50(df,idNode): """ This function allows to slice the array resulting from the create_array function. The slicing is performed by a boolean mask in which the array is filtered according to the ID_Node specified by the user and then only the columns corresponding to time and mean diameter...
565c4ea76de08a493f028e32052fcef60e7f42dd
53,509
def to_upper(string): """The upper case version of a string""" return string.upper()
8d3bb60b7b4704479cb642b9ab910f7a1469fd44
53,510
def is_printable_as_block_string(value: str) -> bool: """Check whether the given string is printable as a block string. For internal use only. """ if not isinstance(value, str): value = str(value) # resolve lazy string proxy object if not value: return True # emtpy string is prin...
aab23c58fdbd3bd505392dff0224a9f342ca6afb
53,511
def inbox(request, search_type='', search_word='', page=0, box=''): """Inbox""" if int(page) < 1: page = 1 list_count = settings.INBOX_LIST_COUNT current_page = int(page) - 1 start_at = current_page * list_count end_at = start_at + list_count if box == 'inbox': sq = (~Q(use...
813ec39d77f0438d7fd5b54ef8f7847d108a3cbb
53,512
def _after_arg(arg_name): """Return a finder for argument after arg_name.""" def generate(transform): """Generate three args, OTHER, arg_name and ARGUMENT.""" return "ONE {0} {1}".format(arg_name, transform("ARGUMENT")) return generate
0a0306760e8e9a2ad356a4f2d9ae2c6b76d53d2e
53,513
import numpy def load_cifar(dataset="training", path="cifar"): """ The Cifar Loading Method. :param dataset: 'training' or 'testing', depending on the data to load :param path: path to the cifar files :return: X,y: data and labels """ if dataset == "training": X = numpy.ndarray([50...
92eb76ef9466bc6c04beed24d3c0b4587b24df2a
53,514
def get_data_files(split, dataset_config): """ Get the path to the dataset (images and labels). 1. If the user has explicitly specified the data_sources, we simply use those and don't do lookup in the datasets registered with VISSL from the dataset catalog. 2. If the user h...
392c618bfe602c66fcb2cbd56924f33d364c0a1e
53,515
def create_s3_bucket(session, bname, region): """ IAM Permission Required: - s3:CreateBucket """ try: s3 = session.client('s3') req = { "Bucket": bname, "ACL": "private" } if region != "us-east-1": tmpObj = { "L...
b7f1d07763db020a74968b93d4818efab1383abf
53,516
def compute_predictions(example, n_best_size=10, max_answer_length=30): """ Converts an example into an NQEval object for evaluation. :param example: EvalExample :return: ScoreSummary """ predictions = [] for unique_id, result in example.results.items(): if unique_id not in example....
ffdb662d0bfd2841caef18e64799685df79373e7
53,517
def validate_create_namespace(result, name): """ Validation function for integration testcases """ return name in get_system_namespace_list()
075590d42d357b5410cd7b3bf152842cae9f6d92
53,518
def log5(request): """log5 is a version of log3 without conclusion. It is meant for the version that has artificial words as terms in the syllogism.""" if request.method == "GET": bValid = True (usernumber_str, bValid) = getValue(request, u"uid", bValid) (timelapse_str, bValid) = get...
e103f8f29deb751669722738df66a8933d2b8eac
53,519
import torch def load_datasets(args): """load the dataset (ColonDataset) and split the dataset into train and validation set Args: args: arguments from the parser. Return: train_dataset: a dataset for training val_dataset: a dataset for validation """ dataset =...
ba8d0594a456f7878dffaa4dae4a7cec34179e82
53,520
def _get_unstarted_workflows(): """Get a list of all workflows that should have a cycle started. This function is used for fixing failed cycle starts. Returns: list of workflows that are missing any started cycles. """ return db.session.query(Workflow).filter( Workflow.next_cycle_start_date < date...
142853795f2b77fc61db01b2d85c85dedb996f10
53,522
def parse_list(elem): """Parse list of properties. >>> parse_list(ET.XML('<Property />')) [] >>> xml = '''<Property> ... <Property>Hello</Property> ... <Property>World</Property> ... </Property>''' >>> parse_list(ET.XML(xml)) ['Hello', 'World'] """...
a1fdb641fab345bc81ec1bd4891eb0d185ed4104
53,523
def deltaF(int_list, f_0_win=5): """ Function for colculation ΔF/F0 for data series. f_0_win - window for F0 calculation (mean of first 2 values by defoult). """ f_0 = np.mean(int_list[:f_0_win]) return np.asarray([(i - f_0)/f_0 for i in int_list])
6c43832c67811379ab125e34952afc5880a0cd11
53,526
def calculate_rcplvs(lv): """ Convert cartesian lattice vectors to the fractional lattice vectors Args: lv (:py:attr:`array_like`, optional): Lattice vectors Returns: rcplvs (:py:attr:`array_like`, optional): Reciprcocal lattice vectors lengths (:py:attr:`array_like`, optional)...
2be1e78289f209d87cff54177fcb24c9982f4939
53,527
import torch def get_src_xyz_from_plane_disparity(meshgrid_src_homo, mpi_disparity_src, K_src_inv): """ :param meshgrid_src_homo: 3xHxW :param mpi_disparity_src: BxS :param K_src_inv: Bx3x3 :return: """ B, S = mpi_d...
91492ba8782607e8500de5b886f9339b041a3513
53,528
import torch def reduce_loss_dict(loss_dict): """ Reduce the loss dict from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return loss_dict w...
ecbc363a9e7df4978a2bf81ffeb2e8f6d5636796
53,529
def geoserver_cascading_delete(self, *args, **kwargs): """ Runs cascading_delete. """ lock_id = f'{self.request.id}' with AcquireLock(lock_id) as lock: if lock.acquire() is True: return cascading_delete(*args, **kwargs)
5f944c619f3679fb0a63d4035191590bcdb943ac
53,530
def create_vat(*, session: Session = Depends(get_session), schema: VatPostingGroupCreate): """«VAT Posting Group» («НДС Учетная Группа»)""" return service.servicetype_s.create(db=session, schema=schema)
bfe38b86c18809ba58f0a17565e00d048f143bab
53,531
def local_test_pressure_unity(α_spt, p_lt=None, p_li=None, p_e=None, **kwargs): """Local test pressure unity check. Reference: DNVGL-ST-F101 (2017-12) sec:5.4.2.1 eq:5.6 p:93 (local_test_press_unity) """ if p_e is None: p_e = external_pressure(h_l, ρ_seawater, g) if p_lt ...
1336d9d3a6d38691f80c3d968725a6d412cce266
53,533
import ctypes def getProgramState(hc, nbuf, wait=SYNCHRONOUS): """Returns program state""" state = ctypes.c_int() acs.acsc_GetProgramState(hc, nbuf, byref(state), wait) return state.value
2563015cecea556a30f659b5f10b6002fb86af4d
53,534
def ip( source=None, source_hex=None, destination=None, destination_hex=None, version=None, ihl=None, tos=None, p=None, p_str=None, d=None, d_str=None, t=None, t_str=None, r=None, r_str=None, tl=None, id=None, flg=None, flg_str=None, frg=None, ttl=None, pro=None, sum=None, su...
5126d981ec9822c2c28dfa3918e59d2516b5e50d
53,536
from typing import DefaultDict def default_dict(_cls): """ Decorator that it create DefaultDict by attribute of class. Support attribute alias: @attrdict.default_dict class CustomDict: a=1 b=2 custom_dict = CustomDict() custom_dict.a # return: 1 ...
f9e3eadde4e7230acf64d544c9a4df146bb58e2e
53,537
def trimmed_split(s, seps=(";", ",")): """Given a string s, split is by one of one of the seps.""" for sep in seps: if sep not in s: continue data = [item.strip() for item in s.strip().split(sep)] return data return [s]
192c75f7e346860010031cf9e621d7bb5664dde4
53,538
import torch def mp2rage_old(pd, r1, r2s=None, transmit=None, receive=None, gfactor=None, tr=6.25, ti1=0.8, ti2=2.2, tx=None, te=None, fa=(4, 5), n=160, eff=0.96, sigma=None, device=None, return_combined=True): """Simulate data generated by a (simplified) MP2RAGE sequence. The d...
872be49a57514f4f4a85bcc94bfc3228b1ae8cf4
53,539
from typing import Dict from typing import Tuple def load_homonyms(synsets_file_name: str, senses_file_name: str, fasttext_model: FastText, udpipe_pipeline: Language) -> Dict[str, Tuple[np.ndarray, str]]: """ Create a special dictionary of RuWordNet homonyms and their distributional semantic rep...
c6d01b66c25f9f4f2218984817f5a30511517ed9
53,540
def descendant_selected(node): """Returns true if this node or a descendant of it is selected. Use as e.g.: {% if descendant_selected node %} """ if node.selected: return True for child in node.children: if descendant_selected(child): return True return Fals...
974b95b8d658ec173ccbbf9488f309529c1f0d86
53,541
import torch def create_mock_attention_data(number_of_nodes, edge_per_node, in_channels, periods): """ Creating a mock stacked feature matrix and edge index. """ graph = nx.watts_strogatz_graph(number_of_nodes, edge_per_node, 0.5) edge_index = torch.LongTensor(np.array([edge for edge in graph.edge...
b08185a92bb906da3bc89941f737b9aa5a162c46
53,542
def pretty_labels_map(atom_labels): """ transforms all of these crazy tuples into the notation used in williams and beer I_min PID """ rename_map = {} for label in atom_labels: new_label = str(label) # eliminate commas and spaces new_label = new_label.replace(',', '') ...
2e7841062a7a5688ecd79b9fd772022e99648ef2
53,543
def 取最小数(数值列表): """ 传入要对比的列表,如(1,2,3),返回里面最小的数字 :param 数值列表: (1,2,3) :return: 1 """ return min(数值列表)
27f031613c6e95e4daf3022a2c14b29ada905e30
53,544
import warnings def tile_iterator_1d(x,axis,n_tiles,block_size,n_block_overlap,guarantee='size'): """Tile iterator for one dimension of array x. Parameters ---------- x : numpy.ndarray Input array axis : int Axis which sould be tiled, all other axis not tiled n_tiles : int ...
09fa63a7b7d1d84e0db66b7cdfe2d2df5b47d88d
53,545
from typing import List import logging def _plot_categorical_feature_numerical_label( label_stats_data: pd.DataFrame, feature_stats_data: pd.DataFrame, feature_name: str, plot_style_params: _FeaturePlotStyles) -> List[axes.Axes]: """Plots the statistics of a categorical feature when label is numerical. ...
aae77e577016b2e4fd7d0f240fe24abda03ab12f
53,546
def get_all_property_groups(connection): """ Get the meta-information for all the property groups in the portal. :rtype: :class:`list` of :class:`PropertyGroup` instances :raises hubspot.connection.exc.HubspotException: End-point documentation: http://developers.hubspot.com/docs/methods/contac...
5d3a2745afe703ab2d6ece7cf4fdb5900b023d05
53,547
def get_infected(data: EoN.Simulation_Investigation, end_time: int): """Returns list of infected nodes.""" return get_type_of_nodes(data, end_time, 'I')
fffe3f52e47ebf534b8c48f2c8433baf0b68eb4d
53,548
def create_product_storage_record(record_info: dict): """ 创建一条库存变更记录 :param record_info:{ "shop_id": 1, "product_id": 1, "operator_type": 1, "user_id": 1, "type": 1, "change_storage": 1, "current_storage": 2, "order_num": 1xxxxx, } :ret...
8de739ea4b9d9fa4c98d76ba602c013e0049ffca
53,549
def _includes_custom_type(content_type: str) -> bool: """ Evaluate whether a content type is a custom type or has a custom type as a sub-type. :return: Boolean result """ if content_type.startswith("Optional"): sub_type = _get_sub_types_of_compositional_types(content_type)[0] result ...
3d795d7667c8ec07aec8fac8d831c76d7398ecae
53,550