content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def extract_character_pairs(letter_case, reverse_letter_case): """ Extract character pairs. Check that two unicode value are also a mapping value of each other. :param letter_case: case mappings dictionary which contains the conversions. :param reverse_letter_case: Comparable case mapping table which c...
29e5415afc4e4a3bff5cd74c1fa14f78cf715384
3,653,364
def after_timestep(simulation, is_steady, force_steady=False): """ Move u -> up, up -> upp and prepare for the next time step """ # Stopping criteria for steady state simulations vel_diff = None if is_steady: vel_diff = 0 for d in range(simulation.ndim): u_new = simul...
7aa3436ba8bcc4ec395ba6f030b83e6fc3cb4bf3
3,653,365
def get_summary_indices(df, on='NOSC'): """ Get the summary stats for the indices: median, mean, std, weighted mean and weighted std """ samples = get_list_samples(df) samples.append(on) t = df[samples] t = t.melt(id_vars=[on], var_name='SampleID', value_name='NormIntensity') t = t[t['NormI...
1c430a9ad377e3d550e292b381af072d4adc78f0
3,653,366
def view_evidence(evidence_id: int): """View a single Evidence model.""" evidence = manager.get_evidence_by_id_or_404(evidence_id) return render_template( 'evidence/evidence.html', evidence=evidence, manager=manager, )
8a51a3c6279a1501c26fb2de09c4450660546bf3
3,653,367
def rigidBlades(blds, hub=None, r_O=[0,0,0]): """ return a rigid body for the three blades All bodies should be in a similar frame """ blades = blds[0].toRigidBody() for B in blds[1:]: B_rigid = B.toRigidBody() blades = blades.combine(B_rigid, r_O=r_O) blades.name='blades' re...
89b48ba43f748fa4b2db7ee768eabe9e79e9a453
3,653,369
def mea_slow(posterior_matrix, shortest_ref_per_event, return_all=False): """Computes the maximum expected accuracy alignment along a reference with given events and probabilities. Computes a very slow but thorough search through the matrix :param posterior_matrix: matrix of posterior probabilities with r...
4b7165a0145d2e1ad2d0550910e03de5a775733c
3,653,370
import trace def predict(cart_tree, feature_set, data_set): """Predict the quality.""" feature_dict = {} for index, feature in enumerate(feature_set): feature_dict[feature] = index results = [] for element in data_set: # Append a tuple. results.append((trace(cart_tree, feat...
c7f50557202c4320194ecc5264059c1701e0de73
3,653,371
def test_incorporate_getitem_through_switch(tag): """ test_incorporate_getitem_through_switch """ fns = FnDict() scalar_gt = Primitive('scalar_gt') @fns def before(x, y): def f1(x, y): return x, y def f2(x, y): return y, x return tuple_getitem( ...
df128faf55c48ba698340d06b3c232ebc0140511
3,653,372
def response_json(status, message, response): """ Helper method that converts the given data in json format :param success: status of the APIs either true or false :param data: data returned by the APIs :param message: user-friendly message :return: json response """ data = { "status": status, "message": me...
9c7e30e81c5412998bc8523b0e45a353c82b5a41
3,653,373
from . import conf def settings(request): """ """ conf = dict(vars(conf)) # conf.update(ThemeSite.objects.get_theme_conf(request=request, fail=False)) data = request.session.get('cms_bs3_theme_conf', {}) conf.update(data) return {'bs3_conf': conf}
1230171ce1263083aabbd0fb79928c9236af31a9
3,653,374
def NDVI(R, NIR): """ Compute the NDVI INPUT : R (np.array) -> the Red band images as a numpy array of float NIR (np.array) -> the Near Infrared images as a numpy array of float OUTPUT : NDVI (np.array) -> the NDVI """ NDVI = (NIR - R) / (NIR + R + 1e-12) return NDVI
aa1789c80720c09aa464b3ae67da7de821e2ba97
3,653,375
from typing import Union from typing import Optional from datetime import datetime def get_nearby_stations_by_number( latitude: float, longitude: float, num_stations_nearby: int, parameter: Union[Parameter, str], time_resolution: Union[TimeResolution, str], period_type: Union[PeriodType, str],...
e53896ea4644bcce6351671ec950fe8165a2cb12
3,653,376
import scipy def get_state(tau, i=None, h=None, delta=None, state_0=None, a_matrix=None): """ Compute the magnetization state. r(τ) = e^(Aτ)r(0) eq (11) at[1] """ if a_matrix is not None: # get state from a known A matrix # A matrix can be shared and it takes time to build ...
a4ae277d41b64c9caf49758d62767030db0b244b
3,653,377
import aacgmv2._aacgmv2 as c_aacgmv2 import logging def convert_latlon_arr(in_lat, in_lon, height, dtime, code="G2A"): """Converts between geomagnetic coordinates and AACGM coordinates. Parameters ------------ in_lat : (np.ndarray or list or float) Input latitude in degrees N (code specifies ...
d9efc4d58925ef9cd63e7c800258b99c91e14f7a
3,653,379
import re def getPredictedAnchor(title: str) -> str: """Return predicted anchor for given title, usually first letter.""" title = title.lower() if title.startswith('npj '): return 'npj series' title = re.sub(r'^(the|a|an|der|die|das|den|dem|le|la|les|el|il)\s+', '', title) ...
972eaa495078bc3929967a052f031c50d439fbdc
3,653,381
from typing import Optional from typing import Mapping def get_contact_flow(contact_flow_id: Optional[str] = None, instance_id: Optional[str] = None, name: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, type: Optional...
ed57d1b17c19f66c38e67613e49653b11c13f699
3,653,382
def jensen_alpha_beta(risk_returns ,benchmark_returns,Rebalancement_frequency): """ Compute the Beta and alpha of the investment under the CAPM Parameters ---------- risk_returns : np.ndarray benchmark_returns : np.ndarray Rebalancement_frequency : np.float64 ...
ac9d1cf638e2ce67219ed16dbbffc652ff47c541
3,653,383
def cycles_run() -> int: """Number of cycles run so far""" return lib.m68k_cycles_run()
145dc9a154a0ec4c2e46fecdeb7106134307cf10
3,653,384
def loop_and_return_fabric(lines): """ loops lines like: #1196 @ 349,741: 17x17 """ fabric = {} for line in lines: [x, y, x_length, y_length] = parse_line(line) i_x, i_y = 0, 0 while i_y < y_length: i_x = 0 while i_x < x_length: thi...
d5fd18c5b90c0e6576767a77c954b3546cbaef1a
3,653,385
def get_sample(id): """Returns sample possessing id.""" for sample in samples_global: if sample.id == id: return sample raise Exception(f'sample "{id}" could not be found')
524305fe77ef5cc03ba51af3eb61301b697b9c1f
3,653,386
def transcriptIterator(transcriptsBedStream, transcriptDetailsBedStream): """ Iterates over the transcripts detailed in the two streams, producing Transcript objects. Streams are any iterator that returns bedlines or empty strings. """ transcriptsAnnotations = {} for tokens in tokenizeBedStream(transcriptDe...
2be2bbca915667be89220d92c42b8a8dce905cc4
3,653,387
import re def convert_check_filter(tok): """Convert an input string into a filter function. The filter function accepts a qualified python identifier string and returns a bool. The input can be a regexp or a simple string. A simple string must match a component of the qualified name exactly. A r...
9d1aaa9a5007371e4f33ce3b4fbc86edd15875c6
3,653,388
def region_stats(x, r_start, r_end): """ Generate basic stats on each region. Return a dict for easy insertion into a DataFrame. """ stats = Munch() stats["start"] = r_start stats["end"] = r_end stats["l"] = r_end - r_start stats["min"] = np.min(x[r_start:r_end]) stats["max"] = np.ma...
cb52f6320952be13f9715cb2259b32996bdbb0da
3,653,389
def _sql_type(ptype): """Convert python type to SQL type""" if "Union" in ptype.__class__.__name__: assert len(ptype.__args__) == 2, "Cannot create sql column with more than one type." assert type(None) in ptype.__args__, "Cannot create sql column with more than one type." return f"{pty...
331734ce050ca261d2d78876ebd78540a088597b
3,653,392
def rescale_data(data: np.ndarray, option: str, args: t.Optional[t.Dict[str, t.Any]] = None) -> np.ndarray: """Rescale numeric fitted data accordingly to user select option. Args: data (:obj:`np.ndarray`): data to rescale. option (:obj:`str`): rescaling strate...
5f885233c262fb2d766417e64f783f807212355e
3,653,393
def extract_labels(text, spacy_model): """Extract entities using libratom. Returns: core.Label list """ try: document = spacy_model(text) except ValueError: logger.exception(f"spaCy error") raise labels = set() for entity in document.ents: label, _ = Label.o...
782fdcb4bdd817b55a38c5efe03db676f0e00eed
3,653,394
from typing import Callable import click def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for a DC/OS variant. """ function = click.option( '--variant', type=click.Choice(['auto', 'oss', 'enterprise']), default='auto', hel...
4c89dc15b46c9d147445ef458b721c7ce835cbe7
3,653,395
def GetSegByName(name): """ @return Address of the first byte in the Segment with the provided name, or BADADDR """ for Segment in ida.Segments(): if ida.SegName(Segment) == name: return Segment return ida.BADADDR
4b0353da187735095805b5a80bb0e23a2ce6491b
3,653,396
def sample_points_from_plateaus(all_plateaus, mode, stack_size=10, n_samples=1): """ Samples points from each plateau in each video :param all_plateaus: dictionary containing all plateaus, keys are plateaus's ids, values are the plateau objects :param mode: either `flow` or `rgb` :param stack_size:...
1dd12721acc9b126d244902016e939792b220d1e
3,653,397
def mobile_user_meeting_list(request): """ 返回用户会议列表 :param request: :return: """ dbs = request.dbsession user_id = request.POST.get('user_id', '') start_date = request.POST.get('start_date', '') end_date = request.POST.get('end_date', '') error_msg = '' if not user_id: ...
55e9a61a755ef957f4b6bf504b3efe721b13cfd7
3,653,398
import ctypes def get_current_thread_cpu_time(): """ <Purpose> Gets the total CPU time for the currently executing thread. <Exceptions> An AssertionError will be raised if the underlying system call fails. <Returns> A floating amount of time in seconds. """ # Get the current thread handle ...
6d83314e8ceee0336b6c0ed7f71fa49e89b24ca8
3,653,399
def get_data_upload_id(jwt: str) -> str: """Function to get a temporary upload ID from DAFNI data upload API Args: jwt (str): Users JWT Returns: str: Temporary Upload ID """ url = f"{DATA_UPLOAD_API_URL}/nid/upload/" data = {"cancelToken": {"promise": {}}} return dafn...
dcce05a8efda1c90e6a78a19757f57deffd0c247
3,653,400
def StationMagnitudeContribution_TypeInfo(): """StationMagnitudeContribution_TypeInfo() -> RTTI""" return _DataModel.StationMagnitudeContribution_TypeInfo()
d9af45a3bbe993de37c351b5791ba8b87aeeedc9
3,653,401
def _get_operations(rescale=0.003921, normalize_weight=0.48): """Get operations.""" operation_0 = { 'tensor_op_module': 'minddata.transforms.c_transforms', 'tensor_op_name': 'RandomCrop', 'weight': [32, 32, 4, 4, 4, 4], 'padding_mode': "constant", 'pad_if_needed': False, ...
a3bab4147f1a2020fb87853fc30bede277f0f4bd
3,653,402
def itm_command( ticker: str = None, ): """Options ITM""" # Check for argument if ticker is None: raise Exception("Stock ticker is required") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception("Stock ticker is invalid") current_price = yfinanc...
b2230ee5f8c520523f7ce844372a4f26d14fe53d
3,653,403
def create_nx_suite(seed=0, rng=None): """ returns a dict of graphs generated by networkx for testing, designed to be used in a pytest fixture """ if rng is None: rng = np.random.RandomState(seed) out_graphs = {} for N in [1, 2, 4, 8, 16, 32, 64, 128]: for dtype in [np...
eb64688850d48b755dc526ed3d64876d04ba3914
3,653,404
def _nearest_neighbor_features_per_object_in_chunks( reference_embeddings_flat, query_embeddings_flat, reference_labels_flat, ref_obj_ids, k_nearest_neighbors, n_chunks): """Calculates the nearest neighbor features per object in chunks to save mem. Uses chunking to bound the memory use. Args: refere...
e9b7af295ddfab56f70748e42fb7b06f6192a3ac
3,653,405
import heapq def heap_pop(heap): """ Wrapper around heapq's heappop method to support updating priorities of items in the queue. Main difference here is that we toss out any queue entries that have been updated since insertion. """ while len(heap) > 0: pri_board_tup = heapq.heappo...
c640fd178a399332fc10ccbb55085cb08d118865
3,653,406
def _variant_po_to_dict(tokens) -> CentralDogma: """Convert a PyParsing data dictionary to a central dogma abundance (i.e., Protein, RNA, miRNA, Gene). :type tokens: ParseResult """ dsl = FUNC_TO_DSL.get(tokens[FUNCTION]) if dsl is None: raise ValueError('invalid tokens: {}'.format(tokens))...
28e989087a91accf793eaaada2e65a71ee145c32
3,653,407
def project(name, param): """a tilemill project description, including a basic countries-of-the-world layer.""" return { "bounds": [-180, -85.05112877980659, 180, 85.05112877980659], "center": [0, 0, 2], "format": "png", "interactivity": False, "minzoom": 0, "maxz...
9609c523cccc99168bbc0e7dbf10fe8624d399c2
3,653,408
def get_deepest(): """Return tokens with largest liquidities. Returns: str: HTML-formatted message. """ url = config.URLS['deepest'] api_params = {'limit': 5, 'orderBy': 'usdLiquidity', 'direction': 'desc', 'key': POOLS_KEY ...
c944f20f65dd68716b4f436b02ec5e373c04848f
3,653,409
def _grompp_str(op_name, gro_name, checkpoint_file=None): """Helper function, returns grompp command string for operation.""" mdp_file = signac.get_project().fn('mdp_files/{op}.mdp'.format(op=op_name)) cmd = '{gmx} grompp -f {mdp_file} -c {gro_file} {checkpoint} -o {op}.tpr -p'.format( gmx=gmx_exec,...
9201bd49fd09ce9faa268d8ea4d33482cea5d7ad
3,653,410
def get_role_with_name(role_name: str) -> Role: """Get role with given name.""" role = Role.query.filter(Role.name == role_name).one() return role
e20858ef1bcbb54d2c1d09ba9d3a54bf15dfa658
3,653,412
def namespace_store_factory( request, cld_mgr, mcg_obj_session, cloud_uls_factory_session, pvc_factory_session ): """ Create a NamespaceStore factory. Calling this fixture lets the user create namespace stores. Args: request (object): Pytest built-in fixture cld_mgr (CloudManager): ...
cc2d090d8dc0f12d89331ada54e4054e117e544d
3,653,413
def get_user(request, username): """ Gets a user's information. return: { status: HTTP status, name: string, gender: string, marital_status: string, first_name: string } """ data = get_user_info(username) if data: ...
9820b441718629780ff72ab00776fc2d4c95a63f
3,653,414
def find_changes(d_before, d_after): """ Returns a dictionary of changes in the format: { <system id>: { <changed key>: <Change type>, ... }, ... } The changes should describe the differences between d_before and d_after. ...
02e5eea5ac1264c593d542a8f745a8d3571d5fac
3,653,415
def check_vector_inbetween(v1, v2, point): """ Checks if point lies inbetween two vectors v1, v2. Returns boolean. """ if (np.dot(np.cross(v1, point), np.cross(v1, v2))) >= 0 and (np.dot(np.cross(v2, point), np.cross(v2, v1))) >= 0: return True else: return False
6eeaa4a9e37ea345c3399c103dadbc45c306887c
3,653,416
def accuracy(y_preds, y_test): """ Function to calculate the accuracy of algorithm :param y_preds: predictions for test data :param y_test: actual labels for test data :return: accuracy in percentage """ return np.sum(np.where(y_preds == y_test, 1, 0)) * 100 / len(y_test)
f41522663ae9a35e976f4d848f14e42ef0993fd9
3,653,417
def get_all(factory='official', **kwargs): """Construct and return an list of Class `Event`. hookを呼び出す. Args: factory: `Event` の取得用マネージャ 今のところ,京大公式HP用のみ. EventFactoryMixin classを継承したクラスか 'official' に対応 date (:obj:`datetime`, optional): 欲しいイベントのdatetime. `month` , `y...
bc1fabe37fc8065ff5394259607caf32c6345b41
3,653,418
def nudupl(f): """Square(f) following Cohen, Alg. 5.4.8. """ L = int(((abs(f.discriminant))/4)**(1/4)) a, b, c = f[0], f[1], f[2] # Step 1 Euclidean step d1, u, v = extended_euclid_xgcd(b, a) A = a//d1 B = b//d1 C = (-c*u) % A C1 = A-C if C1 < C: C = -C1 # Step ...
7f5a16c0fc2611a5f9dc0ebde00e3587c188f944
3,653,420
def remove_schema(name): """Removes a configuration schema from the database""" schema = controller.ConfigurationSchema() schema.remove(name) return 0
e45b415ea6eb57402790b04bbf1fa63749242a77
3,653,421
def get_unassigned_independent_hyperparameters(outputs): """Going backward from the outputs provided, gets all the independent hyperparameters that are not set yet. Setting an hyperparameter may lead to the creation of additional hyperparameters, which will be most likely not set. Such behavior happens...
6f28f3fcbaf4a875c3a42cdb4fc9ad715c99a093
3,653,422
def get_theta_benchmark_matrix(theta_type, theta_value, benchmarks, morpher=None): """Calculates vector A such that dsigma(theta) = A * dsigma_benchmarks""" if theta_type == "benchmark": n_benchmarks = len(benchmarks) index = list(benchmarks).index(theta_value) theta_matrix = np.zeros(n...
aa84006b7a69faa8803ecea20ffd24e35f178185
3,653,423
def reorder_points(point_list): """ Reorder points of quadrangle. (top-left, top-right, bottom right, bottom left). :param point_list: List of point. Point is (x, y). :return: Reorder points. """ # Find the first point which x is minimum. ordered_point_list = sorted(point_list, key=lambd...
8ef3466616ecf003750cce7e1125d913d258cf15
3,653,425
import torch def ppg_acoustics_collate(batch): """Zero-pad the PPG and acoustic sequences in a mini-batch. Also creates the stop token mini-batch. Args: batch: An array with B elements, each is a tuple (PPG, acoustic). Consider this is the return value of [val for val in dataset], where ...
1357a8a9fa901a9be4f79ea13fd5ae7c3810bbeb
3,653,426
def problem004(): """ Find the largest palindrome made from the product of two 3-digit numbers. """ return largest_palindrome_from_product_of_two_n_digit_numbers(3)
516c98d75ac2b4e286e58ea940d49c1d2bcd2dc7
3,653,427
import torch def residual_l1_max(reconstruction: Tensor, original: Tensor) -> Tensor: """Construct l1 difference between original and reconstruction. Note: Only positive values in the residual are considered, i.e. values below zero are clamped. That means only cases where bright pixels which are brighter...
8649b1947845c0e3f9e57c0ec2e68d7bed94be5d
3,653,428
def build_url(path): """ Construct an absolute url by appending a path to a domain. """ return 'http://%s%s' % (DOMAIN, path)
fa9df465607082993571ca71c576d7b250f6cc76
3,653,429
def get_registration_url(request, event_id): """ Compute the absolute URL to create a booking on a given event @param request: An HttpRequest used to discover the FQDN and path @param event_id: the ID of the event to register to """ registration_url_rel = reverse(booking_create, kwargs={"event_i...
d8b344c6574a120d365a718934f5dc0e78173a6f
3,653,430
def create_no_args_decorator(decorator_function, function_for_metadata=None, ): """ Utility method to create a decorator that has no arguments at all and is implemented by `decorator_function`, in implementation-first mode or usage-first mode. T...
7067974d7bd15c238968f78aa0057086458940bf
3,653,431
import torch def compute_batch_jacobian(input, output, retain_graph=False): """ Compute the Jacobian matrix of a batch of outputs with respect to some input (normally, the activations of a hidden layer). Returned Jacobian has dimensions Batch x SizeOutput x SizeInput Args: input (list or t...
c18f596a3500f2f82e2b4716e6f9892a01fb31c7
3,653,433
def is_associative(value): """Checks if `value` is an associative object meaning that it can be accessed via an index or key Args: value (mixed): Value to check. Returns: bool: Whether `value` is associative. Example: >>> is_associative([]) True >>> is_ass...
5d2a9e0e69ad793a98657dc13b26f79900f29294
3,653,434
def join_audio(audio1, audio2): """ >>> join_audio(([1], [4]), ([2, 3], [5, 6])) ([1, 2, 3], [4, 5, 6]) """ (left1, right1) = audio1 (left2, right2) = audio2 left = left1 + left2 right = right1 + right2 audio = (left, right) return audio
23348b746469d362fd66371d61142b4227814ff3
3,653,435
def csi_from_sr_and_pod(success_ratio_array, pod_array): """Computes CSI (critical success index) from success ratio and POD. POD = probability of detection :param success_ratio_array: np array (any shape) of success ratios. :param pod_array: np array (same shape) of POD values. :return: csi_array: ...
84952fe6f7c8bd780c64c53183342ab0d8f3f90f
3,653,436
def compute_secondary_observables(data): """Computes secondary observables and extends matrix of observables. Argument -------- data -- structured array must contains following fields: length, width, fluo, area, time Returns ------- out -- structured array new fields are ad...
7141d16a579e4b629e25fee3a33c9a844a08e48f
3,653,438
def get_account_number(arn): """ Extract the account number from an arn. :param arn: IAM SSL arn :return: account number associated with ARN """ return arn.split(":")[4]
3d0fe552691ae98cf0dc70bc2055297f01a5d800
3,653,439
def get_hashtags(tweet): """return hashtags from a given tweet Args: tweet (object): an object representing a tweet Returns: list: list of hastags in a tweet """ entities = tweet.get('entities', {}) hashtags = entities.get('hashtags', []) return [get_text(tag) for tag in ha...
ef222d64294c62d27e86a4c8520bb197701ed1af
3,653,440
def get_appliance_ospf_neighbors_state( self, ne_id: str, ) -> dict: """Get appliance OSPF neighbors state .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - ospf - GET - /ospf/state/neighbors/{neId} :param n...
25a985ccf8b00ee3f27ea43d2a8371eef2443963
3,653,442
def info(obj): """Return info on shape and dtype of a numpy array or TensorFlow tensor.""" if obj is None: return 'None.' elif isinstance(obj, list): if obj: return 'List of %d... %s' % (len(obj), info(obj[0])) else: return 'Empty list.' elif isinstance(obj, tuple): if obj: ret...
64ffab112b0f0397541f8661a861a958c8ccf26e
3,653,444
def first_index_k_zeros_left(qstr, k, P): """ For a binary string qstr, return the first index of q with k (mod P) zeros to the left. Return: index in [0, qstr.length] """ num_zeros_left = 0 for j in range(qstr.length+1): if (num_zeros_left - k) % P == 0: return j if ...
62e505290fb32b43860deae3477dec718028e7af
3,653,445
def transform_points(points, transf_matrix): """ Transform (3,N) or (4,N) points using transformation matrix. """ if points.shape[0] not in [3, 4]: raise Exception("Points input should be (3,N) or (4,N) shape, received {}".format(points.shape)) return transf_matrix.dot(np.vstack((points[:3, ...
f478dfdfe41c694ada251deca33820336001d61e
3,653,446
def get_lat_long(zip): """ This function takes a zip code and looks up the latitude and longitude using the uszipcode package. Documentation: https://pypi.python.org/pypi/uszipcode """ search = ZipcodeSearchEngine() zip_data = search.by_zipcode(zip) lat = zip_data['Latitude'] long =...
4fa8dc583bba9a6068db58ab86c2cab5f310edc4
3,653,447
def propose_perturbation_requests(current_input, task_idx, perturbations): """Wraps requests for perturbations of one task in a EvaluationRequest PB. Generates one request for each perturbation, given by adding the perturbation to current_input. Args: current_input: the current policy weights task_idx...
279da36eb633005c8f8ee79e66b71b3bdf8783f3
3,653,448
import google def id_token_call_credentials(credentials): """Constructs `grpc.CallCredentials` using `google.auth.Credentials.id_token`. Args: credentials (google.auth.credentials.Credentials): The credentials to use. Returns: grpc.CallCredentials: The call credentials. """ reque...
433bb494d9f8de529a891f529a42f89af0b5ef77
3,653,449
import time def test_analyze(request,hash,db_name): """ Get features of a sequence, using the sequence's sha-1 hash as the identifier. """ db = blat.models.Feature_Database.objects.get(name=db_name) sequence = blat.models.Sequence.objects.get(db=db,hash=hash) ts = int(time.mktime(sequence....
173ebb356167558cb64a35265caa39e828a43bae
3,653,450
from typing import List def _collect_scaling_groups(owner: str) -> List: """Collect autoscaling groups that contain key `ES_role` and belong to the specified owner""" client = boto3.client("autoscaling") print("Collecting scaling groups") resp = client.describe_auto_scaling_groups() assert "NextT...
f1f75e6158450aaef834a910f8c36bb8812b1ede
3,653,451
def cross_entropy_loss(logits, labels, label_smoothing=0., dtype=jnp.float32): """Compute cross entropy for logits and labels w/ label smoothing Args: logits: [batch, length, num_classes] float array. labels: categorical labels [batch, length] int array. label_smoothing: label smoothing ...
7b6ce3145bc85433e54cef0ac85570eeb0fe7230
3,653,452
import torch def set_optimizer(name, model, learning_rate): """ Specify which optimizer to use during training. Initialize a torch.optim optimizer for the given model based on the specified name and learning rate. Parameters ---------- name : string or None, default = 'adam' The name...
5c1a5e836176b90506ca6344c01ce6828b43d917
3,653,453
import httplib import urllib def get_http_url(server_path, get_path): """ Вариант с использованием httplib напрямую; ничем не лучше urllib2 server_path = "example.com" get_path = "/some_path" """ # urllib - более высокого уровня библиотека, которая в случае http использует # httplib; ...
d759609b1c48af28e678fa75bd9ff102f7eaafae
3,653,454
def not_found_view(request): """Not Found view. """ model = request.context return render_main_template(model, request, contenttile='not_found')
0fe250d09f8fc007ffb07f848e59e779da9aefb0
3,653,455
import torch def top_filtering( logits, top_k=0, top_p=0.0, threshold=-float("Inf"), filter_value=-float("Inf") ): """ Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering Args: logits: logits distribution shape (vocabulary size) top_k: <=0: n...
7b230fc959e0078f1cfc5b2f2f991c79e0f4fd86
3,653,456
def get_physical_type(obj): """ Return the physical type that corresponds to a unit (or another physical type representation). Parameters ---------- obj : quantity-like or `~astropy.units.PhysicalType`-like An object that (implicitly or explicitly) has a corresponding physical t...
03d28bdb9a507939e52bc0021dae3c539b4954a5
3,653,457
def reverse(list): """Returns a new list or string with the elements or characters in reverse order""" if isinstance(list, str): return "".join(reversed(list)) return _list(reversed(list))
ba74d9e4e54782114f534fb4c888c681ab708b67
3,653,458
from typing import Dict def PubMedDiabetes( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/linqs", version: str = "latest", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance ...
ddac0cfb8a525c42fe5a8d6c1a70677ab57451e0
3,653,459
def find_neighbor_indices(atoms, probe, k): """ Returns list of indices of atoms within probe distance to atom k. """ neighbor_indices = [] atom_k = atoms[k] radius = atom_k.radius + probe + probe indices = list(range(k)) indices = indices + list(range(k+1, len(atoms))) for i in ind...
05c3218357d660d6b66c3d614bfcb0d78431d32e
3,653,460
def genDir(EAs): """ Generate the projection direction given the euler angles. Since the image is in the x-y plane, the projection direction is given by R(EA)*z where z = (0,0,1) """ dir_vec = np.array([rotmat3D_EA(*EA)[:, 2] for EA in EAs]) return dir_vec
0753fad9638ca8b0ac4e899ad103dc08266a208b
3,653,461
def plainica(x, reducedim=0.99, backend=None, random_state=None): """ Source decomposition with ICA. Apply ICA to the data x, with optional PCA dimensionality reduction. Parameters ---------- x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples) data set reduced...
7ffe9ebc78220898c84459fed61fc0f32fe05e69
3,653,462
def all_equal(values: list): """Check that all values in given list are equal""" return all(values[0] == v for v in values)
8ed08f63959367f3327554adc11b1286291963d8
3,653,464
def _tester(func, *args): """ Tests function ``func`` on arguments and returns first positive. >>> _tester(lambda x: x%3 == 0, 1, 2, 3, 4, 5, 6) 3 >>> _tester(lambda x: x%3 == 0, 1, 2) None :param func: function(arg)->boolean :param args: other arguments :return: something or none ...
035c8bf68b4ff7e4fbdb7ed1b2601f04110287d8
3,653,465
from datetime import datetime def new_revision(partno): """ Presents the form to add a new revision, and creates it upon POST submit """ _load_if_released(partno) # ensures the component exists and is released form = RevisionForm(request.form) if request.method == 'POST' and form.validate_on_...
722a3860e9daeb4bd5d9339f7dcaf5245c51b5de
3,653,466
def fresnel_parameter(rays, diffraction_points): """ returns the fresnel diffraction parameter (always as a positive) Parameters ---------- rays : [n] list of shapely LineString (3d) diffraction_points: [n] list of Points (3d) diffraction point which the ray is rounding Returns ---...
cd398797161f1e9e66805cd09162359ed6e89330
3,653,467
def validate(net, val_data, ctx, eval_metric): """Test on validation dataset.""" eval_metric.reset() # set nms threshold and topk constraint net.set_nms(nms_thresh=0.45, nms_topk=400) net.hybridize() for batch in val_data: data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_a...
79dcd9b0d1920952b5badd4aa9f3f234776f6e06
3,653,468
from re import S def add_unique_geom_id(point_gdf: gpd.GeoDataFrame, log: Logger=None) -> gpd.GeoDataFrame: """Adds an unique identifier (string) to GeoDataFrame of points based on point locations (x/y). """ point_gdf[S.xy_id] = [f'{str(round(geom.x, 1))}_{str(round(geom.y, 1))}' for geom in point_gdf[S....
0663e24b217c2911083d68146a5d8ff25c4fd8bd
3,653,469
def get_data_parallel_rank(): """Return my rank for the data parallel group.""" return _TOPOLOGY.get_data_parallel_rank()
a1da062793f6798e2e56809b3076c811f786a82b
3,653,470
import math def entropy(data): """ Compute the Shannon entropy, a measure of uncertainty. """ if len(data) == 0: return None n = sum(data) _op = lambda f: f * math.log(f) return - sum(_op(float(i) / n) for i in data)
ebfd9a84885a95ec6e4e7b2d88a0fb69fbbfaea1
3,653,471
import torch def alexnet(pretrained=False): """AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = AlexNet() if pretrained: model_path = './mod...
a42df7c926472b88501001eefd691959e6acb3ac
3,653,473
import torch def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor: """ Generates one random target in (num_classes - 1) possibilities for each label that is different from the original label. Parameters ---------- labels: Tensor Original labels. Generated targets wi...
c0740c5ddc7c1f866b4c3cb2986f45a672d22e49
3,653,474
def recall_k(sent_im_dist, im_labels, ks=(1, 5, 10)): """ Compute recall at given ks. """ im_labels = tf.cast(im_labels, tf.bool) def retrieval_recall(dist, labels, k): # Use negative distance to find the index of # the smallest k elements in each row. pred = tf.nn.top_k(-dist, k=k)[1] # ...
188f2cb4c3581f9c565253fbb17797a408ce3d74
3,653,475
def get_suggestion(project_slug, lang_slug, version_slug, pagename, user): """ | # | project | version | language | What to show | | 1 | 0 | 0 | 0 | Error message | | 2 | 0 | 0 | 1 | Error message (Can't happen) | | 3 | 0 | 1 | 0 | Error messa...
66ddf3e44f006fcd1339b0483c3219c429643353
3,653,476
def resample_data_or_seg(data, new_shape, is_seg, axis=None, order=3, do_separate_z=False, cval=0, order_z=0): """ separate_z=True will resample with order 0 along z :param data: :param new_shape: :param is_seg: :param axis: :param order: :param do_separate_z: :param cval: :param...
ab7aa7ab1db40ec605d7069ccf3b1bc8751c3855
3,653,477