content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def create_logger(name='', logging_config=logging_config): """Create a Logger object Args: name (str, optional): The name of the module.function logging_config (TYPE, optional): Logging config Returns: TYPE: Description """ dictConfig(logging_config) l...
f71bd7d96b50f2263c7b0175a89229d8c58abc92
46,524
def mark_all(request): """ Mark all notification as read or unread. """ action = request.data.get('action', None) success = True if action == 'read': request.user.notifications.read_all() msg = _("Marked all notifications as read") elif action == 'unread': request.us...
495a39c5f1229477704826ebaa4bdf86d8d67afe
46,525
def _split_mime_type(mime_type): """Split MIME type into main type and subtype. Args: mime_type: The full MIME type string. Returns: (main, sub): main: Main part of MIME type (e.g., application, image, text, etc). sub: Subtype part of MIME type (e.g., pdf, png, html, etc). Raises: _In...
ce88fd75624060403aed44ddab9f044a577cfbd1
46,527
def handler_get_user_connections_from_id_from_event_id(userID, eventID): """Get the connections of the user with the given IDs (user and event). .. :quickref: Users; Get the connections of the user with the given IDs (user and event). :param int userID: The ID of the user to retrieve the collection fr...
506904c23a23fd94f5894d2ede08ed37a8ae5ff5
46,528
import requests def run(studata,cook): """获取处理后的数据 :param studatae:学生信息 :param cook:传入的cookie :return :打卡结果 """ # 读取个人提交信息 info = getinfo.data(studata, cook) if info == 0: print("今日打卡已完成,自动打卡取消\n") return "已完成" # 提交今日打卡 url = 'https://yq.weishao.com.cn/api/quest...
f7767bc6e0dfbf3d0c663eaed5ed1e9d7924ad34
46,529
def filter_label_2( context, label ): """Test Filter Label 2""" return False
a31337f18cbec6d5b8e556b21603635732d17ffd
46,530
def raise_404_if_no_object(fn): """ get_object_or_404 doesn't work with mongoengine, so this is needed for similar purpose """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: if not e.__class__.__name__ == "DoesNotExist": ...
b50a204a8cc0ab2cb2c05eabbe62f9d9ea6c751d
46,531
from typing import Tuple async def generate_keys() -> Tuple[bytes, str]: """A helper function to generate the private and public keys. backend - The value specified is default_backend(). This is because the cryptography library used to support different backends, but now only uses the default_backend...
13654fa051eeddaad6682ee0525199500dee67fd
46,532
import six def _is_named_tuple(instance): """Returns True iff `instance` is a `namedtuple`. Args: instance: An instance of a Python object. Returns: True if `instance` is a `namedtuple`. """ if not isinstance(instance, tuple): return False return (hasattr(instance, "_fields") and i...
8ee641d4fb64926b807d74eaf40115e8608af301
46,533
def department_list_current(): """Returns a list of all Departments as of today's date. """ resp = _call_organisations_service("GetDepartmentListCurrent") return _parse_list_response(resp, "OrganisationsList", "Organisation")
dba40b7de228fdb196e46869499ed21db12fc569
46,536
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, aggregate_size=None): """ Find the unique elements of a tensor. Returns the sorted unique elements of a tensor. There are three optional outputs in addition to the unique elements: * the indices of ...
fb97f22416a5558cb334396d07546aa2c98d89b2
46,537
def post_to_dto(post: Post, href: str = None, links: list = None) -> PostDto: """ Converts post resource into data transfer object. :param post: Post resource to convert. :type post: Post :param href: Post resource href link. :type href: str :param links: Post resource links. :type link...
106d8b3dde351e52ed3df6b83eed3dd770e8f797
46,540
import logging def get_dual_coding_stop_stop_location( fs_coord, fs_type, strand, chr_seq, gencode): """Extend the starting coordinate (fs_coord) downstream until the stop-codon in the main frame, shift the frame (fs_type) at this stop-codon and then go upstream in the alternative until the second st...
cd5db26363585f93e234c36e158b0cd8046484ed
46,541
def delete_restaurant(restaurant_id): """V 0.0.0 POST Delete a restaurant: GET render Delete a restaurant form""" restaurant_to_delete = SESSION.query( Restaurant).filter_by(id=restaurant_id).one() if request.method == 'POST': SESSION.delete(restaurant_to_delete) SESSION.commit() ...
1380fa2159a90c536c94967a226453efedeaeafc
46,542
def get_clusters_from_file(path, ref_cluster_names=[]): """Get cluster names, labels, and cells from cluster file or metadata file """ clusters = {} with open(path) as f: lines = f.readlines() headers = [line.strip().split('\t') for line in lines[:2]] names = headers[0] types = hea...
cabf14c72b0467b0f2b15e3c0b8c8bd1846e92b5
46,543
import gzip def split_deltas(deltas_url): """Opens and decompress a gzipped text file and splits each line into two deltas""" left, right = [], [] with gzip.open(BytesIO(read_url(deltas_url))) as deltas: for line in deltas: line = line.decode().rsplit(" ", 1) left.app...
ff43daced54f1c18f837a525424e79dcd23d91d2
46,544
def transform(image, parameter_maps, verbose=False): """Transform an image according to some vector of parameter maps :param image: Image to be transformed :param parameter_maps: Vector of 3 parameter maps used to dictate the image transformation :type image: SimpleITK.Image ...
d2ac4b61f79f2a8275aa0f63feb49c87f12294ba
46,545
def put_lines(ax, cwaves, fluxes, ypos2, ypos3, labels, bars=None, bscale=None, edges=None, barskwargs=dict(), adjustkwargs=dict(), linekwargs=dict(), textkwargs=dict()): """ Automatic layout of labels for spectral lines in a plot. Parameters ---------- ax : Matplotlib A...
b8cf1918eeb77871e42e4bc9691ccaf227373ca8
46,546
def _tracking(fcn): """ Decorator to indicate the list has changed """ def new_fcn(self, *args): self.changed = True return fcn(self, *args) return new_fcn
3f6454190056f112134f01507b2bb353a8043790
46,548
def test(doorcount: int, switch: bool, trials: int) -> bool: """Returns a win rate for the Monty Hall problem with repeated trials.""" wins = sum(int(play(doorcount, switch) == CAR) for _ in range(trials)) return wins/trials
0e02834f54570867412eb2c25892377a388c9287
46,549
def getLastStepMeanSpeed(detID): """getLastStepMeanSpeed(string) -> double Returns the mean speed in m/s of vehicles that have been within the named multi-entry/multi-exit detector within the last simulation step. """ return _getUniversal(tc.LAST_STEP_MEAN_SPEED, detID)
dd0e79e0639ee6141ba2abb8f66398bc4cbe4341
46,550
def get_random_experiment_histories_from_file(experiment_path_prefix, net_number): """ Read history-arrays from the specified npz-file and return them as ExperimentHistories object. """ histories_file_path = generate_random_experiment_histories_file_path(experiment_path_prefix, net_number) with np.load(hist...
ec65f7bb1580f166218554a28fbe40b629d3bd11
46,551
def qr_householder(A): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square...
ce2e64c55e4476be1048c88b66bb89ce0c6697f5
46,553
def login(): """ Página de entrada de la app """ if 'email' in session: # Obtenemos el ID del user _id = elastic.getIDByMail(session['email']) return render_template('index_sup.html', random_num = WebScraper.getRandomNumber(), msg = session['user'] + ' is already online!',...
ea534c69727332958fe4fe7a32e0979f5a674d87
46,554
def load_data(database_filepath): """ Load data from database Arguments: database_filepath -> Path to SQLite destination database Output: X -> a dataframe containing features Y -> a dataframe containing labels category_names -> List of categories name """ # l...
142eed54d527225a7208a35b2631333ef842c934
46,555
def cholesteric_droplet_data(shape, radius, pitch, hand = "left", no = 1.5, ne = 1.6, nhost = 1.5): """Returns cholesteric droplet optical block. This function returns a thickness, material_eps, angles, info tuple of a cholesteric droplet, suitable for light propagation calculation tests. Pa...
3c478afad445066ade233461500b072bd756836f
46,556
def getInterpolatedFzeroPzero( f, g, p ): """ look at the points of f, g and p surrounding where g crosses zero and interpolate f and p at 0 """ ndx = getIndexZeroDbCrossover( g ) f_zero_db = None g_zero_db = None p_zero_db = None if ndx != None: f_zero_db = f[ndx] g_z...
7dbf5b0372e0c81c771c077b6badbe42d2c4eb55
46,557
from typing import Mapping def create_tag(entity: Entity, source_name: str, color: str) -> Mapping[str, str]: """Create a tag.""" value = entity.value if value is None: value = f"NO_VALUE_{entity.id}" return {"tag_type": source_name, "value": value, "color": color}
f510ddc698f9d6c491fda63e33a16fe2cfda1021
46,558
import re def javacode_to_tokens(code:str): """ Starting on method level, without javadocs returns a touple of ([code-tokens],code-string) """ code_tokens = re.findall(r"\w+(?:'\w+)*|[^\w\s]", code) #print("Javacode to tokens to be done!",code,code_tokens) return (code_tokens,code)
85c0dccb06936326929493edc5192ccf01bf59ea
46,559
def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, \ song_id=None, description=None, results=15, max_tempo=None, min_tempo=None, max_duration=None, \ min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None...
95961b0d4c865e86a636682bbb0f335a43e57a27
46,560
def floor_to(value: float, target: float) -> float: """ Similar to math.floor function, but to target float number. """ value: Decimal = Decimal(str(value)) target: Decimal = Decimal(str(target)) result: float = float(int(floor(value / target)) * target) return result
c58341913e294b68d38328fe42441e6942e94b8d
46,561
def registration(): """Processes registration when user provides email and password, or displays the form.""" if request.method == 'POST': email = request.form.get("email") password = request.form.get("password") # Create a possible user object to query if the user's email is in t...
e52fab05c05ad945b39d2f1e9d9f102efc5f395e
46,562
from typing import Dict def generate_meta(favicon: Dict[str, str]) -> str: """Generate metatag based on favicon data. Default behavior: - If favicon data contains no ``rel`` attribute, sets ``rel="icon"`` - If no ``size`` attribute is provided, ``size`` will be omitted - If no favicon MIME type i...
940e7f7ab7b2fb7207cba287f6f6ec7424749f98
46,563
import re def select_disk(prompt='Which disk?'): """Select a disk from the attached disks""" disks = get_attached_disk_info() # Build menu disk_options = [] for disk in disks: display_name = '{Size}\t[{Table}] ({Type}) {Name}'.format(**disk) if len(disk['Partitions']) > 0: ...
f5fd59ab6c45b1af303bfa453ecdde8c7df326a3
46,564
def imageToVTK( path, origin=(0.0, 0.0, 0.0), spacing=(1.0, 1.0, 1.0), cellData=None, pointData=None, fieldData=None, ): """ Export data values as a rectangular image. Parameters ---------- path : str name of the file without extension where data should be saved. ...
f263f1a7613e331fd46c336446be50d84e7110c6
46,565
def compute_capacities(n, demands_across_cuts): """ Computes the capacities as given in the paper. Takes O(n^2) time. :param n: ring size :param demands_across_cuts: SymmetricMatrix containing all demands across cuts. :return: np.array containing capacities """ c = np.zeros((n,), dtype=np.fl...
7a8936e057577473919302274b6c72c44d5b47fc
46,566
def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data Parameters ---------- subdir : None or str Subdirectory we need in nibabel-data directory. If None, only require nibabel-data directory itself. Returns ------- skip_dec : decorator De...
2d45fe47fae9ac6e574d33e97c556c7dabac9215
46,567
def __create_pyramid_features(C3, C4, C5, feature_size=256): """ Creates the FPN layers on top of the backbone features. Args C3 : Feature stage C3 from the backbone. C4 : Feature stage C4 from the backbone. C5 : Feature stage C5 from the backbone. ...
754acc903e767179096c5e84ec43e6df54970c3e
46,569
import copy def parse_compare(*tests, justeq=False): """Decorate a function to run it against pure python. This will run and compare the function using all available backends. """ def decorate(fn): def test(backend_opt, args): if not isinstance(args, tuple): args =...
3e503ab27bdb5fedc62a82ddace9f12a4e9da3c2
46,570
def check_brand_parameters(request): """ Function to check if the parameters of a given brand are valid :param request: request object containing all the parameters :return: Error if exists, if not, None """ if not check_parameter(request.json, NAME, 2, 15) \ or not check_parameter(r...
c59b94c044d81fa29d338d51ff19a44beca0da6b
46,571
def command_exists(cmd): """ does the command exists in current system? """ path = which(cmd) if path is None: return False return True
d84a843cb478c7ae63f1ec3abba0621a794dabd5
46,572
from typing import Optional from typing import List def _convert_names( names, max_levels: Optional[int] = None, err_msg: Optional[str] = None ) -> List[str]: """Helper function that converts arguments of index, columns, values to list. Also performs check on number of levels. If it exceeds `max_levels`,...
d67fb93b039306e7dac973abffe1e08089993c0d
46,573
from backend.caffe.path_loader import PathLoader def extractNetFromSolver(solverstring): """Read a protoxt string(!) of a solver and return the network protoxt string(!). This works only, if the solver specifies a network using the "net_param" parameter. A reference to a file using the "net" parameter ca...
a78e35798a48ef19272993183e73f314e5f7fd14
46,575
from datetime import datetime def expand_date_param(param, lower_upper): """ Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower...
1a2c34a0abace3b521be093de361ddcae0006ea7
46,576
def appliedMediumData(modelFunction,cellSpace,initialPercentageInfected,states,n_iterations,n_simulations,theSystemHasAges = False, systemAges = None): """Aplica el modelo epidemiológico en n_simulations modelFunction => Función basica del modelo epidemiológico initialPercentageInfected => Porcentaje de inf...
2237c93fdd318db6dc3bcd77ed7b396041938f18
46,577
def make_id(ref: extmodule.Ref) -> Text: """Convert a ref to a string iddentifier.""" return "{}/{}".format(ref.type, ref.ident)
b3dd53a68dc98230576839f9ced28c220e044e80
46,579
import math def get_torch_datagens(data_dir, feature_len=300, num_video_per_person=1e4, num_audio_per_video=1e4, split_by='audio', split_size=0.2, txt_dirs=None, ratios=[1.0, 1.0]): """ Returns datagens for torch Params: data_dir: Parent directory for the pickle files. Assumed that each person has...
59fc414365d44551b32c262f6268161e7d462529
46,580
def create_grouped_df_adv(group_param, df, ticker_name='symbol', agg_func=np.count_nonzero, show_value_counts=False): """ Receive the `group_param`, `df`, `ticker_name`, `agg_func` and return grouped by group_param DataFrame with values aggregated by agg_func and Dict with ...
22fc6d243cb64df906c143bee1b3d4ff8f4cb376
46,581
def query_history_to_json(query_history: QueryHistory): """ The function converts an object of QueryHistory to a json string. :param query_history: A QueryHistory object. :type query_history: ibmpairs.query.QueryHistory :rtype: str """ return QueryHi...
766d0918a7cea0868cdab6c672d14c7c5504dbd1
46,583
def is_MC(parcels): """ Dummy for Maricopa County. """ return (parcels.county == 'MC').astype(int)
6e8af2675f1ba40d642ada0d07e133aeb9dd0d70
46,584
import re def getMatchingCompetence(dictionary, lastmessage): """ Searches for a competence in a string """ allCompetences = getAllCompetences(dictionary) searchedCompetence = [] for word in re.split('[ .!?]', lastmessage): if stemmer.stem(word.strip().lower()) in [ ste...
2b6fbd95597db71a60a914443d2998ad093acb33
46,585
def objScale(obj,factor): """ Object scaling function, gets obj and scale factor, returns an array of the scaled size """ oldSize = obj.get_size() newSize = [] for i in oldSize: newSize.append(int(i/float(factor))) return newSize
3104fc4e126299400a5a119fff0d8bc9d3ea32f7
46,586
def tiny_shakespeare(c: NLPAutoRegressionConfigs): """ ### Tiny Shakespeare dataset It will download from the url if not present """ return TextFileDataset( lab.get_data_path() / 'tiny_shakespeare.txt', c.tokenizer, url='https://raw.githubusercontent.com/karpathy/char-rnn/ma...
7a22a359c5306e73e94701ce91645c31cf87c380
46,587
def preprocess_encoder_input(arr): """ Simple method to handle the complex MFCC coefs that are produced during preprocessing. This means: 1. (For now), discarding one of the channels of the MFCC coefs 2. Collapsing any empty dimensions :param arr: the array of MFCC coefficients. """ return a...
ccd754783377e9fe257e423f9099d6dbef21d11b
46,588
def findTreeRoute(observations, tree, startNodeID, startLayer, stopLayer, alternateLeafActivation = False): """Classifies the observations according to the tree.""" col = 0 treeRoute = [] for i in range(startLayer,stopLayer+2): if i == startLayer: currentNode = tree[startNodeID] ...
e206902c6edec2eff100f2ff77bb8a57d2a6c99f
46,589
def determineWinCardIndex(pile): """ @param list pile: pile of cards in center @return int: index of winning card - highest index of leading suit, or if there are spades, highest spades index """ bestCard = (pile[0], 0) for i in range(1, len(pile)): bestCardSuit = bestCard[0].ind...
c105ade59b79482de0f2d3e6b4d25c4353bb1dcf
46,590
import time def sagemaker_timestamp(): """Return a timestamp with millisecond precision.""" moment = time.time() moment_ms = repr(moment).split('.')[1][:3] return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment))
a0c09ed9f419ef519ca22b219e1bc0922f7f7f7c
46,591
def EmitEval(deque_graph, # type: collections.deque ctx, # type: Context ): """ Emit evaluation code(eval layers) """ ret = ''' bool NetworkForwardExecute(Buffer *buffer) { ''' for layer_name in deque_graph: node = ctx.graph[layer_name] if node["op"] == "N...
d2215da9db38d53e7a5fd1f6b3da01ef310cf357
46,592
from ._tornadoserver import TornadoServer # noqa - circular dependency from ._flaskserver import FlaskServer def create_server(host=None, port=None, loop=None, backend='tornado', **server_kwargs): """ Create a new server object. This is automatically called; users generally don't need t...
e4806cd389287c6aeab2e9ad824317fc34ec13e5
46,593
def build_dataset_info(cfg): """Build information struct about the dataset from a configuration. This performs type conversion to the expected types. Paths contained in cfg are expected to be alread expanded. That is, it should not contain global variables or other system dependent abbreviations. ...
576e71057bcaf38c1720d5b70f21557c608700e0
46,594
def hdr2srgb(im): """[Tonemap a linear image with quasi srgb (clip and gamma 1/2.2)] Args: im ([[hxwx3 ndarray]): [linear image] Returns: [hxwx3 ndarray]: [srgb image] """ return (np.clip(im,0,1) ** (1/2.2) * 255).astype(np.uint8)
ab932f0ea5061f549bbb5d85ab8e1cdbeabb4466
46,596
def greyList(n): """ 生成格雷编码序列 参考:https://www.jb51.net/article/133575.htm :param n: 长度 :return: 范围 2 ** n的格雷序列 """ def get_grace(list_grace, n): if n == 1: return list_grace list_before, list_after = [], [] for i in range(len(list_grace)): list...
eab1f00ec2cdd62fbbffbb78a2c69c6fe9177e66
46,597
from typing import Union def get_feature(feature: Union[str, Feature]) -> Feature: """Get feature from name. Args: name (str): Name of feature. Returns: Feature """ if isinstance(feature, str): feature = get_feature_class(feature)() elif not isinstance(feature, Featur...
92a0938ff426f66bc61e10e9f7b3f6cdc64ede33
46,598
def get_predictions(theta): """Produce predictions for all molecules in the freesolv set""" return np.array([predict_solvation_free_energy_jax(theta, distance_matrices[i], charges[i], type_slices[i]) for i in range(len(distance_matrices))])
6a19e6ab34e4d47d7285bf9f59779fe85ff5684b
46,600
def train(corpus): """ Computes the chunk distribution by pos The result is stored in a dictionary :param corpus: :return: """ pos_cnt = count_pos(corpus) maxPos = {} for pos in pos_cnt: testChunkCnt = count_chunks(corpus, pos) maxPos[pos] = maxDict(testChunkCnt) ...
51cf7fc919cb3f04d3e0691716f3e2b0e3ec9f88
46,601
def get_suggestions(): """ Get chatroom suggestions based on user-entered tag :param tag: string, the tag a user would like to match to :return: a JSON Response object, containing the matched results as a list of dicts with keys room_id, name, members """ incoming = request.get_json() ...
d3b2a2c9abc80841a722d3e6ea0e0794215af007
46,602
def subset_by_value(samples, feature, value): """ Subset samples based on value Parameters: samples - Pandas DataFrame; last column is taken as the class labels feature - Name of feature; should correspond to column in samples value - Value to check for subset membership; can be literal value o...
34f8f25ea312986599eb99a215db660fd5a2be83
46,603
def build_model(input_shape, conv_window_size, num_filters, reg, dropout, word2vec = True, max_token = None, sequence_len= 190): """ If random init max_token is the vocabulary size sequence_len is the number of words in the largenst sentence """ model = Sequential() #model.add(E...
6ace0c563555d33ade9468384193fe2546cafde7
46,604
def validate(validation, dictionary): """ Validate that a dictionary passes a set of key-based validators. If all of the keys in the dictionary are within the parameters specified by the validation mapping, then the validation passes. :param validation: a mapping of keys to validators :...
3c128992e9552ef973e5a94056891e50befa6043
46,606
def load_TD(file_path): """Returns the TD file given by file_path. Can be either .val files generated by the windows GUI, or .bin files generated by the linux C++ framework. """ if(file_path.endswith('.val')): print 'Reading event file: ' + file_path TD = eventvision.read_aer(fi...
1fba382ee72eaf07b6541270d3f6da67e168db22
46,607
import socket def test_get_ipv6_address(monkeypatch): """Test get own ipv6 address.""" class Socket(MockSocket): def getsockname(self, *args, **kwargs): return ("::1234",) monkeypatch.setattr(socket, "socket", Socket) assert get_internal_ipv6_address() == IPv6Address("::1234")
4cf586745ff2412ed3b07f4ca75e4aa3c51c60e6
46,608
def hbb_to_kaa(hessian): """ Unit conversions on input Hessian matrix from (Hartrees/Bohr/Bohr) (kcal/mol/Angstrom/Angstrom). """ hessian = (hessian * 627.509474) / (0.529177**2) return hessian
e5daec25cba9104f8ecf1bcf30a0b4020969c704
46,609
def get_formatted_contents( raw_contents, use_color, color_config, squeeze, subs ): """ Apply formatting to raw_contents and return the result. Formatting is applied in the order: color, squeeze, subs. """ result = raw_contents if use_color: result = get_colorized_co...
5f7594c859f6ffd3a31f608faf679e55b0a3fece
46,610
import warnings def compute_bin_assignment(position, x_edges, y_edges=None, include_edge=True): """Compute spatial bin assignment. Parameters ---------- position : 1d or 2d array Position information across a 1D or 2D space. x_edges : 1d array Edge definitions for the spatial binn...
5b5d2b5a60ea925c75a883923c5df07321e8e0ff
46,614
from typing import List from typing import Union import torch from typing import Optional from typing import Tuple def padded_tensor( items: List[Union[List[int], torch.LongTensor]], pad_idx: int = 0, left_padded: bool = False, max_len: Optional[int] = None, ) -> Tuple[torch.LongTensor, List[int]]: ...
a43b09fd15d8d2e31db692a782d20ab2013a10e3
46,615
def coloring(color, text): """Print a text in a specified color""" color_sequences = { 'default': '\033[0m', 'black': '\033[30m', 'red': '\033[31m', 'green': '\033[32m', 'yellow': '\033[33m', 'blue': '\033[34m', 'purple': '\033[35m', 'lightblue': '...
3953d72329a01453f52fd099bb20624c7661aa87
46,616
def truediv(a, b): """Same as a / b.""" return a / b
44b93737128efa6672eaaf33eff11ac9a0c56cac
46,617
def calcDihedrals(prevCO, currN, currCA, currCO, nextN): """ Calculates phi and psi angles for an individual residue. Requires coord tuple of each atom. """ prevCO = np.array(prevCO) currN = np.array(currN) currCA = np.array(currCA) currCO = np.array(currCO) nextN = np.array(nextN) ...
034364f625229fba3e19d5cf345716e91a4c4c45
46,618
from typing import Any def reset_password( token: str = Body(...), new_password: str = Body(...), node: Node = Depends(deps.get_db), ) -> Any: """ Reset password """ db = node.db email = verify_password_reset_token(token) if not email: raise HTTPException(status_code=400, d...
362917982d493d1ea2f59291bcffbc18eeb121ed
46,619
import importlib def WorkerAgentGenerator(agent_class): """ Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent. """ # Support special case where class is given as type-string (AgentsDictionary) or class-name-string. if isinstance(agent_c...
dac55eda91ac6743ef530dd2ecd52a8331465e57
46,620
def series_mean_with_conf(xx): """ Compute series mean. Also provide confidence of mean, as estimated from its correlation-corrected variance. """ mu = mean(xx) N = len(xx) if np.allclose(xx,mu): return val_with_conf(mu, 0) if (not np.isfinite(mu)) or N<=5: return val_with_conf(mu, n...
d007bd6f80fd494b65d47db5aafd056c0a2bf754
46,621
import token import requests def get_webhook(): """ Getting installed webhooks :return: installed webhooks """ header = {'Content-Type': 'application/json;charset=utf-8'} request_address = 'https://api.ok.ru/graph/me/subscriptions?access_token={token}'.format(token=token) response = reques...
345a331514d276b336803d2fed182d7591eb8cc6
46,622
import math def haversine(rad): """ Returns the haversine function of an angle in radians. """ return (1 - math.cos(rad)) / 2
294c901795aa499c42f3d67e6d6a3d5efecd46a8
46,623
def countingOp(i, m, Npair): """ Calculates the application of the counting operator to a basis state m. Returns 0 or 1, according to the occupation of the energy level. """ m1 = flipBit(m, Npair-i-1) if m1 < m: return 1 else: return 0
ee5e3fb1bcb1e5a3dfad25dffcaa3ee37671e9c5
46,624
def safestring_to_string(s): """Return the original string encoded by string_to_safestring""" return _base64.b64decode(s.encode("utf-8")).decode("utf-8")
4191bf8dedcdb56ffed09d329c572786f95dfe39
46,625
def apparent_spectrum_fit_function(wn, Z_ref, p, b, c, g): """ Function used to fit the apparent spectrum :param wn: wavenumbers :param Z_ref: reference spectrum :param p: principal components of the extinction matrix :param b: Reference's linear factor :param c: Offset :param g: Extinct...
21de604e34a894f08b6fa7d39e67c052a58e534d
46,626
def active_matrix_from_intrinsic_euler_xyz(e): """Compute active rotation matrix from intrinsic xyz Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) ...
71bc22736c61449423a4c09fa0512987ef029068
46,627
def test_post_handlers(): # language=rst """ Post handlers ------------- In the simplest cases, like in a create form, you only have one post handler. You can do this yourself in the classic Django way: """ # @test request = req('post', foo='foo', **{'-submit': True}) form = F...
7cbc22b0edb3d7b0d1bcc3137f247d6522bd0a33
46,628
import attr def parse(raw): """ Parses the given dict into a Entry object. This assumes the data is formatted according to version 1.0 (or equivalent) of the RNAcentral JSON schema. """ def key(raw): return gene(raw) or "" context = Context( database=raw["metaData"]["data...
d0c44f515c9d00795b9ed6b72c155506c2802628
46,629
import inspect def wrapper(f): """Internal wrapper, takes a function f, adds type checking and return handling. """ signature = inspect.signature(f) @wraps(f) def new_func(*args, **kwargs): payload = request.json new_args = [] new_kwargs = {} try: fo...
e1a787bb3742bc97f7dcc8613789db2c24b76274
46,630
import collections def callbacks() -> dict: """ Return a dictionary of callbacks with asynchrony support. :return: a collections.defaultdict that returns callbacks by name. """ return collections.defaultdict(MockCallable)
b3abf2ec0678e1c6633143224cfed07ccaed5524
46,631
import torch def run_kmeans(x, args): """ Args: x: data to be clustered """ results = {'im2cluster':[],'centroids':[],'density':[]} for seed, num_cluster in enumerate(args.num_cluster): print('performing kmeans clustering on ...',num_cluster) # intialize fais...
2fd3946a95a00fe640d1814dd50ff265b79ebe73
46,632
def gensym(name: str) -> str: """Generates a globally unique name, using the given one as a base""" global GENSYM_COUNTER uniq = f"{name}__{GENSYM_COUNTER}" GENSYM_COUNTER += 1 return uniq
c886e0b7148c9a57c9aee5d670e325043652312d
46,633
def normal_empirical_cdf( target_cdf: float = 0.5, mean: float = 0.0, sigma: float = 1.0, samples: int = 1000000, bins: int = 1000): """ computes the value x for target_cdf """ # --- argument checking if target_cdf <= 0.0001 or target_cdf >= 0.9999: ra...
3356ddbd83f490b5fd4fdb4f26782d4719b567dc
46,637
import requests from datetime import datetime def get_openweather_data(): """Gathers weather data and returns the required list.""" response = requests.get(API_URL).json() weather_data = response['list'] # Add date info for entry in weather_data: entry['date'] = datetime.fromtimestamp(ent...
08f6c0644d06bbff1d74e990547683261a5acd03
46,638
def find_break_edges(ptree): """ Find edges which to remove from the graph for the original tree behind this ptree. ==> edges between adjac """ ret = set() if len(ptree.insert_descendants) > 0: lca = ptree.insert_descendants[0] for lca_child in lca: ret.add((lca.nodei...
db9ff3ae36dba799d6f479f83e775b41d7bce3df
46,639
def _getMASTidentifier(ID, lkwargs): """ return KIC/TIC/EPIC for given ID. If input ID is not a KIC/TIC/EPIC identifier then the target is looked up on MAST and the identifier is retried. If a mission is not specified the set of observations with the most quarters/sectors etc. will be used. ...
130e29fce25b06eebc0c1c99200fdf778a3ba64f
46,640
def generate_ui_list_data(item_type="parts", pack=None): """Generate a list of Blender UI friendly data of categories and parts. When we retrieve presets we just want an item name. For parts I am doing a trick where I am grouping sets of 3 parts in order to make a grid in each UIList entry. A...
141502b94c51569437b1f771718ac299123e130a
46,641
def pad_image(image): """ Parameters ---------- image : ndarray DESCRIPTION. Returns ------- TYPE padded image and its information """ padded_image = image pad_x1, pad_x2, pad_y1, pad_y2, pad_z1, pad_z2 = 0, 0, 0, 0, 0, 0 # Padding on X axes if image.sh...
c82c02473fdd1ce8363a4448004d509ed2a080e9
46,642
def parse_calibration(filename): """ read calibration file with given filename Returns ------- dict Calibration matrices as 4x4 numpy arrays. """ calib = {} calib_file = open(filename) for line in calib_file: key, content = line.strip().split(":") values = [float(v) for v...
046cd945b0c2d78e0609a96379afb63e2910eceb
46,643