content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def rivers_with_station(stations): """Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station""" river_set = set() for station in stations: river_set.add(station.river) river_set = sorted(river_set) return river_set
16161ababf034709e095406007db42e10b47c921
682,845
def selection(ls): """Create a function which sort list by selection.""" if type(ls) is not list: raise TypeError('Input must be a list type.') for i in range(0, len(ls)): if not isinstance(ls[i], (int, str)): raise TypeError('All elements must be either an \ integer...
4760940815e721864630111dc1c85cbf12c0ab20
682,846
def permute(lst, perm): """Permute the given list by the permutation. Args: lst: The given list. perm: The permutation. The integer values are the source indices, and the index of the integer is the destination index. Returns: A permutation copy of lst. """ return tuple([...
b12be0a40251d51e314e313996e1e11c60e4748c
682,849
import warnings def read_txt(file_name, two_dimensional=False): """ Reads control points from a text file and generates a 1-D list of control points. :param file_name: file name of the text file :type file_name: str :param two_dimensional: type of the text file :type two_dimensional: bool :re...
796eba6c72282084cb0444ec1be65793f3dacdfe
682,850
import socket def gethostbyaddr(ip): """ Resolve a single host name with gethostbyaddr. Returns a string on success. If resolution fails, returns None. """ host = None try: host = socket.gethostbyaddr(ip)[0] except OSError: pass return host
5e7c041171ea4fbaa75fa477f64121db5f05cd39
682,851
import argparse def parse_distance(): """ Parse arguments from the command line Parameters ---------- None Returns ------- dist_pc: float The distance in parsecs to be converted. OoM_value: float The order of magnitude of the distance. """ p = argparse.Ar...
aba94e877fb0e78ad401640cfe85f8ea3b9cc49a
682,852
from typing import Optional import requests def _get(uri: str, access_token: str, query_params: Optional[dict] = None) -> dict: """Send a GET request to the Spotify API.""" url = f"https://api.spotify.com/v1{uri}" response = requests.get( url, params=query_params, headers={"Authorization": f"Beare...
5a7a24a9315d80da28b02d1cc3b79ddf9f96a90e
682,853
import torch import math def gain_change(dstrfs, batch_size=8): """ Measure standard deviation of dSTRF gains. Arguments: dstrfs: tensor of dSTRFs with shape [time * channel * lag * frequency] Returns: gain_change: shape change parameter, tensor of shape [channel] """ ...
a64840f2d7d46869c226614da0977b21bc0140b9
682,854
def multiply(*fields, n): """ Multiply ``n`` to the given fields in the document. """ def transform(doc): for field in fields: doc = doc[field] doc *= n return transform
7697b0c21ecb6e77aedbaa60035c73f1fcee8239
682,855
def numpy_data(data): """Dictionary to numpy.""" values = [] functions = [] for func, ir2vec in data.items(): if func == 'program': continue functions.append(func) values.append(ir2vec) functions.append('program') values.append(data['program']) return fu...
bb0eafd7c4363525fb730bb630da7ed072663b92
682,856
def line_filter_report(reports, diff): """ Filter the reports so that it only contains the reports for lines in the diff that have been added. """ files_in_report = [i[0] for i in reports] filtered_report = [] lookup = {} for file in diff: if file.target_file[2:] in files_in_report:...
34c12fd586aac2322fe34cc0ad86c9d3d59a76a3
682,857
def to_matrix_vector(transform): """Split an homogeneous transform into its matrix and vector components. The transformation must be represented in homogeneous coordinates. It is split into its linear transformation matrix and translation vector components. This function does not normalize the matri...
ff64c6e93bfe8794e0a342bdc449bb42a05dc577
682,858
def or_(xs): """``or_ :: [Bool] -> Bool`` Returns the disjunction of a Boolean list. For the result to be False, the list must be finite; True, however, results from a True value at a finite index of a finite or infinite list. """ return True in xs
b61720cec4ff23dda5f0c0d9315d4d829e2c3512
682,859
def prompt_int(prompt): """ Prompt until the user provides an integer. """ while True: try: return int(input(prompt)) except ValueError as e: print('Provide an integer')
9352b78cd01466654d65ed86482f7163000ec1c4
682,860
from pathlib import Path def get_helper_path(): """ Get the Chapisha helper path. Used, usually, when needing template resources in the helpers folder. """ return Path(__file__).resolve().parent
31b57cee22483b05bd0f051eeb6346c0db09034f
682,862
def check_overlap(stem1, stem2): """ Checks if 2 stems use any of the same nucleotides. Args: stem1 (tuple): 4-tuple containing stem information. stem2 (tuple): 4-tuple containing stem information. Returns: bool: Boolean indicating if the two stems overlap....
3d1381eb5e8cedf7cfe37a8263bbba670240d575
682,863
import os def get_img_identifier(Ullman_or_ImageNet, path, target_list): """Create and return an image identifier with its correct class. It is used as a key in dictionaries and as part of filenames for figures. Args: path: absolute path to directory Returns: img_identifier: st...
b4bbccb9b87a59da5efb55a0c763a8d3db6f6067
682,864
import struct def _unpack_cstring(data, maxstrlen): """"Read a null-terminated string from the head of the data. Return the string and the rest of the data. >>> _unpack_cstring("abc%cfoobar" % 0, 6) ('abc', 'foobar') """ databuf = data[:maxstrlen] databuflen = min(len(databuf), maxstrlen...
52c76b247bd8f355052919683cf590b256f47458
682,865
import ast def str_to_list(string: str) -> list: """ convert list-like str to list :param string: "[(0, 100), (105, 10) ...]" :return: list of tuples """ return ast.literal_eval(string)
152e247a08d7ee50a85bfe5044ea6d3a9ce05169
682,866
import requests def fetch_page(url): """ Fetch the page from the given URL, and return the HTML as a string. """ try: page = requests.request('GET', url, timeout=2000, allow_redirects=True) except: return None if page.status_code is 200: return page.content
8adafcc8fa25072b89a0479661d38c9b042864a5
682,867
import json def json_load(path, verbose=False): """Load python dictionary stored in JSON file at ``path``. Args: path (str): Path to the file verbose (bool): Verbosity flag Returns: (dict): Loaded JSON contents """ with open(path, 'r') as f: if verbose: ...
ac099f33666c6502a253e91c6c03db434fa361cc
682,870
def center_crop(img_mat, size = (224, 224)): """ Center Crops an image with certain size, image must be bigger than crop size (add check for that) params: img_mat: (3D-matrix) image matrix of shape (width, height, channels) size: (tuple) the size of crops (width, height) returns: ...
5a65f44f3bc6e5fb7b768769580a3a0706e60673
682,871
def valid_history_object(request) -> bool: """ Checks if history object is provided :param request: :return: """ session_history = request.session.get('session_history') if session_history is None: return False request.validated['session_history'] = session_history return Tr...
f9418564479c110c02ad8eb12db1d55e36c83fd9
682,872
import os import glob def find_files(root_paths, file_pattern): """ Returns the paths to all files that match a given pattern. :returns: Paths ([str]) to files matching the given pattern. """ if isinstance(root_paths, str): root_paths = [root_paths] paths = [] for root_path in root_pa...
ee3562d7d073bd66fa89c2de9fd9aff481573f76
682,873
def reorder_columns(frame, front_columns): """ Re-order the columns of frame placing front_columns first. Good for looking specifically at certain columns for specific file in pipeline. """ # reorder columns into appropriate order new_cols = list(frame.columns) for d in front_columns: ...
7f0bfabe04ee1551c9ad1384a53478f5e0ad656a
682,874
def lookup_extension(extension_name, extensions): """ Lookup an extension for OpenStack Neutron """ if extensions is None: return None extension_list = extensions.get('extensions', None) if extension_list is None: return None for extension in extension_list: alias =...
ca9f6fa162ee15e3904202213895960e8c85e8ef
682,875
import numpy def svg_path_from_list(vh_list:numpy.ndarray) -> numpy.ndarray: """ Generate SVG-path-suitable list of directions from v/h list Parameters ---------- vh_list : ndarray Two-column list with v/h +/- relative movements Returns ------- path_str : bytes (ready for...
2adf133b31133c4a7a4bddd6eb430f2f3d49b2ff
682,876
def plot_line(m, line, colour='b', lw=1, alpha=1): """ Plots a line given a line with lon,lat coordinates. Note: This means you probably have to call shapely `transform` on your line before passing it to this function. There is a helper partial function in utils called `utm2lola` w...
4cf04142b7205116ff52c93ab32825a4874a28db
682,877
def create_starting_numbers(path): """ Reads a file containing a sudoku grid and converts its content to a list of tuples. @param path: The path of the file to read @return A list of tuples containing the starting numbers """ starting_numbers = [] with open(path, "r") as file: ...
7ce39ffcd04d1512cac2004fbe3e95606ea0fc99
682,878
def _get_orientation(exif): """Get Orientation from EXIF. Args: exif (dict): Returns: int or None: Orientation """ if not exif: return None orientation = exif.get(0x0112) # EXIF: Orientation return orientation
d05b8e7f2029a303d40d049e8d3e1cb9da02fcef
682,879
import torch def index_ordering(inputs, lengths, indices, pad_value=0): """ :param inputs: [B, T, ~] :param lengths: [B] :param indices: [B, T] :return: """ batch_size = inputs.size(0) ordered_out_list = [] for i in range(int(batch_size)): b_input = inputs[i] b_l = ...
597b25ea6e05c47eb54b9441e378c11c4a0b656f
682,880
def protect_eval_dict(evaldict, func_name, params_names): """ remove all symbols that could be harmful in evaldict :param evaldict: :param func_name: :param params_names: :return: """ try: del evaldict[func_name] except KeyError: pass for n in params_names: ...
df3020e56875252022e382ecbc0753e81f19a780
682,881
from unittest.mock import call def check(args=None): """ Checks for pep8 and other code styling conventions. """ return call('flake8 --max-line-length=150 --statistics openslides tests')
5d022bfbb5bc4324f51efe9c3aa72dba0dbc2b82
682,882
import re def extract_chinese(text): """ 只提取出中文、字母和数字 :param text: str, input of sentence :return: """ chinese_exttract = "".join(re.findall(u"([\u4e00-\u9fa5A-Za-z0-9@. ])", text)) return chinese_exttract
0ef6569769d01d5e8e4c122ed5662e31fcfeadb6
682,883
from typing import Union import re import string def _replace_variables(var: Union[dict, list, str, int, bool], params: dict): """Replace all the variables with the given parameters.""" if isinstance(var, dict): return {key: _replace_variables(value, params) for key, value in var.items()} if isins...
75e46904c5c38ecfb3c1018220bab767b765d079
682,884
import random def generate_layers(layer_limit: int, size_limit: int, matching: bool): """ Helper function for generating a random layer set NOTE: Randomized! :param layer_limit: The maximum amount of layers to generate :param size_limit: The maximum size of each layer :param matching: Specif...
27807566aee5d00f290821323e6aadce3733a8c7
682,885
def read(filepath: str): """ Easy way to get data of the file given """ with open(filepath, "r") as f: data = f.read() return data
a9fff47bd2de96d4ba416684903971f8d67e4ccb
682,886
def read_fixturestats(data): """In key "stats" followed by teamID followed by key "M" """ try: stats_all = [] for d in data: stats_temp = {} stats_home = {} stats_away = {} if not 'stats' in d: try: stats_te...
b73b771956bd18708d979445109d08c2966e88a8
682,887
def SPUR(N, A): """ SPUR trac or spur of the diagonal elements of a matrix n x n p. 49 """ SP = 0.0 for I in range(N): SP += A[I, I] return SP
da34273c1fe11c1852502287a3f27fdcb675b7fe
682,888
def get_case_index(acc_index): """ Returns the unique for a year case index from a given accident index. Looks at all digits and letters but the year that is in the beginning. """ case_index = 0 num = 0 letters = [] numbers = [] for char in acc_index[4:]: char_value = ord(cha...
e4ac779fdf1d83e85989b7637f33f665770fc1f4
682,889
def get_state_slug(self, state_type=None): """Get state of type, or default if not specified, returning the slug of the state or None. This frees the caller of having to check against None before accessing the slug for a comparison.""" s = self.get_state(state_type) if s: return s.slug ...
5c9ed30eade39e9ec37f22eeac571eda8d7ca08e
682,890
def obj_make_list(context, list_obj, item_cls, db_list, **extra_args): """Construct an object list from a list of primitives. This calls item_cls._from_db_object() on each item of db_list, and adds the resulting object to list_obj. :param:context: Request context :param:list_obj: An ObjectListBase...
d4ea7bcef4f3307ad2665979e4f9352d06416d0b
682,891
def expand_resources(resources): """ Construct the submit_job arguments from the resource dict. In general, a k,v from the dict turns into an argument '--k v'. If the value is a boolean, then the argument turns into a flag. If the value is a list/tuple, then multiple '--k v' are presented, ...
5e7edff0ceaf9b24a1d69cb9dcb3e9473e1d7b66
682,892
def gen_workspace_tfvars_files(environment, region): """Generate possible Terraform workspace tfvars filenames.""" return [ # Give preference to explicit environment-region files "%s-%s.tfvars" % (environment, region), # Fallback to environment name only "%s.tfvars" % environment...
a1e822451b9652b846eaf21c6323943678e75d84
682,893
import logging import sys def set_logger(level): """ Simple logging setup Arguments --------- level: logging.level Logging level of type logging.level Returns ------- logger: obj logging object use for log output """ log = logging.getLogger(__name__) log.s...
d0ef0f0aca34daae3b9b6ae26afe9233e243d41d
682,894
def comma_sep(values, limit=20, stringify=repr): """ Print up to ``limit`` values, comma separated. Args: values (list): the values to print limit (optional, int): the maximum number of values to print (None for no limit) stringify (callable): a function to use to convert values to ...
748f1956ed8383fc715d891204056e77db30eb4b
682,895
def solution(dividend, divisor): # O(N) """ Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. >>> solution(10, 3) 3 >>> solution(7, -3) -2 >>> solution(2, 3) 0 >>> solution(1, ...
42c9e77a25c87cea739d394305c75b589dcca70a
682,896
def myround (val, r=2): """ Converts a string of float to rounded string @param {String} val, "42.551" @param {int} r, the decimal to round @return {string} "42.55" if r is 2 """ return "{:.{}f}".format(float(val), r)
50e11ccae07764a3773e0a8adf45f010925f41b5
682,897
def normaliseports(ports): """Normalise port list Parameters ---------- ports : str Comma separated list of ports Returns ------- str | List If None - set to all Otherwise make sorted list """ if ports is None: return 'all' if ports in ('all', ...
125b73f0889cd99d5c0128a968b47ae4867cba7e
682,898
def review_pks(database): """ Check that all tables have a PK. It's not necessarily wrong, but gives a warning that they don't exist. :param database: The database to review. Only the name is needed. :type database: Database :return: A list of recommendations. :rtype: list of str """ p...
830c0a988ac6ccc593b979d113a0a9d88a0cca0c
682,899
def maxCtxContextualRule(maxCtx, st, chain): """Calculate usMaxContext based on a contextual feature rule.""" if not chain: return max(maxCtx, st.GlyphCount) elif chain == 'Reverse': return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount) return max(maxCtx, st.InputGlyphCount + st.Lo...
1e17f35864ed4702c80dfc88740d678753236a72
682,900
import re def read_sta_file(sta_file): """ Read information from the station file with free format: net,sta,lon,lat,ele,label. The label is designed with the purpose to distinguish stations into types. """ cont = [] with open(sta_file,'r') as f: for line in f: line = line.r...
4dad0b3227dadf4cf098f7df552cfac285862910
682,901
from pathlib import Path def get_home(): """ Return the user's home directory. If the user's home directory cannot be found, return None. """ try: return str(Path.home()) except Exception: return None
e7991273e5ece7cccf8b947ab0c9ebd900a59919
682,902
import glob import os def find_files_by_extension(directory, extensions): """Walks through files in a directory and searches for files by extension ignoring case Args: directory: The root directory to start the search from extensions: A list of extensions to filter files by Returns: ...
05d0b87db954343d9444a3bf6ebfbbf1edef3981
682,903
def count_common_prefix(str_seq, prefix): """ Take any sequence of strings, str_seq, and return the count of element strings that start with the given prefix. >>> count_common_prefix(('ab', 'ac', 'ad'), 'a') 3 >>> count_common_prefix(['able', 'baker', 'adam', 'ability'], 'ab...
124506fff457e39508cb4d6c2f243e337c60b1c4
682,904
def read_file(file_name): """Returns the content of file file_name.""" with open(file_name) as f: return f.read()
560b6ec2eeb507d694b9c10a82220dc8a4f6ca52
682,905
def load_requirements(requirements_path): """function that loads the requirements.txt file and returns a list of packages to be installed""" with open(requirements_path, 'r') as stream: requirements = stream.read().splitlines() return requirements
455da4b5b42ac100f26d02854141300bd2058e21
682,906
def t_add(t, v): """ Add value v to each element of the tuple t. """ return tuple(i + v for i in t)
da2e58a7b2ff7c1cc9f38907aaec9e7c2d27e1d0
682,908
import os def which(program: str): """ Locates the true path to the executable in the environment Borrowed from https://stackoverflow.com/a/377028 :param program: The program to determine a path to :return: The fully qualified path to the executable or None if not found """ def is_exe(fpat...
42e3e93572e14666849268a848504382cfa13505
682,909
def _create_file_link(file_data, shock): """ This corresponds to the LinkedFile type in the KIDL spec """ return { 'handle': shock['handle']['hid'], 'description': file_data.get('description'), 'name': file_data.get('name', ''), 'label': file_data.get('label', ''), 'URL':...
1bcf71deacbbc56c777ab5266d247860295a5481
682,910
def first_not_repeat(s: str) -> str: """ Parameters ----------- Returns --------- Notes ------ """ if not s: return "" dct = {} for c in s: if c in dct: dct[c] += 1 else: dct[c] = 1 for c in s: if dct[c] ==...
06fd0961cfe26be102f9d8636582b116b60394f4
682,911
import itertools def count_non_0_clusters_2(arr): """groupby() partitions into groups as: [[True , [list of non-0]], [False, [list of 0s]], [True , [list of non-0]], [False, [list of 0s]], ... [True , [list of non-0]]] (Old) Next, the list compren...
78033f4e3b52216f85452e10f3394fec4eee06f4
682,912
def integrate(i,dx): """Takes the y values from interval then uses the trapazoidal rule to approximate the area beneath the curve""" total = 0 for e in range(len(i)): total = total + 2*i[e] total = total- (i[0]+i[-1]) return (dx*total/2)
7cd6755518c77bc7df84b63083a367e8eb5934df
682,915
def active_llr_level(i, n): """ Find the first 1 in the binary expansion of i. """ mask = 2**(n-1) count = 1 for k in range(n): if (mask & i) == 0: count += 1 mask >>= 1 else: break return min(count, n)
75693cdedea712ba3d0e9591f4780c2d0f3a24d2
682,916
def fix_nonload_cmds(nl_cmds): """ Convert non-load commands commands dict format from Chandra.cmd_states to the values/structure needed here. A typical value is shown below: {'cmd': u'SIMTRANS', # Needs to be 'type' 'date': u'2017:066:00:24:22.025', 'id': 371228, ...
59bcce8af2c1779062d7a10d7186b170434bb244
682,917
import copy def _update_inner_xml_ele(ele, list_): """Copies an XML element, populates sub-elements from `list_` Returns a copy of the element with the subelements given via list_ :param ele: XML element to be copied, modified :type ele: :class:`xml.ElementTree.Element` :param list list_: List of...
772218e66aebb99e8d4f0901979969eeda128b99
682,918
def construct_fixture_middleware(fixtures): """ Constructs a middleware which returns a static response for any method which is found in the provided fixtures. """ def fixture_middleware(make_request, web3): def middleware(method, params): if method in fixtures: r...
46720c2a6e158dc931bb2c474dee9d6ffc6ef264
682,919
def selected(): """ Returns the list of elements currently selected :return: list(element, element, element, ...) """ return list()
ac9425bf3628b846835aa6056043df90e0753e90
682,920
import string def find_indent_level(source): """How indented is the def of the fn?""" ws = set(string.whitespace) for i, c in enumerate(source): if c in ws: continue return i return len(source)
7219b905bef7af0187b5a116f5bfcd7a1ecb88cf
682,921
def can_leftarc(stack, graph): """ Checks that the top of the has no head :param stack: :param graph: :return: """ if not stack: return False if stack[0]['id'] in graph['heads']: return False else: return True
352fdebf1612f79a32569403cc4fd1caf51a456d
682,922
def remove_single_children(tree, simplify_root=True): """ Remove all nodes from the tree that have exactly one child Branch lengths are added together when node is removed. """ # find single children removed = [node for node in tree if len(node.children) == 1 and ...
ce376b5cbee23dd476ec74c813fa48725633ba2c
682,923
def main_heading(): """An example fixture containing some html fragment.""" return '<h1>wemake-django-template</h1>'
e3ab6ed32bbfa605a3901dddacc99150f5357d8a
682,924
import math def read_precomp_mem(precomp_file): """Read precomputed memory if exists.""" ret = {} if precomp_file is None: return ret f = open(precomp_file, "r") for line in f: if line == "\n": continue line_data = line.rstrip().split("\t") gene = line_d...
dd950508066b13e294ebfcdcf739accf540f06eb
682,925
import numpy def eval_g(x, user_data= None): """ constraint function """ assert len(x) == 4 return numpy.array([ x[0] * x[1] * x[2] * x[3], x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3] ])
608f8cb654a1bb067fb8cc9fc407f8ea08e762a9
682,926
import networkx as nx def atoms_that_are_n_bonds_apart_dict( topology, n=4, exclude_hydrogen=True): """ Find all atom pairs that are less then `n` bonds apart. Returns result as a dict where each key is an atom index and the corresponding value is the list of atom indices that are l...
3d86018d2ca3c820cbbb0267d80573cacf5cc2af
682,927
import os def get_model_from_directory(folder, method): """ :param folder: :param method: :return: """ has_model = False model = None print('Will Match with each methods/files and get the right model! If model dosent exist the we will create one') print("Directory is : ", folder,'...
ef8cc0f43822b9dcd5d21b765516bfd386d75d48
682,929
def get_table_4(): """表 4 未処理暖房負荷を未処理暖房負荷の設計一次エネルギー消費量相当値に換算するための係数 Args: Returns: list: 表 4 未処理暖房負荷を未処理暖房負荷の設計一次エネルギー消費量相当値に換算するための係数 """ table_4 = [ (1.59, 1.21, 1.59, 1.22), (1.66, 1.22, 1.66, 1.24), (1.63, 1.22, 1.63, 1.23), (1.60, 1.21, 1.60, 1.23), ...
d7056de9a4331a0a43dda3bf86729c5b43ca7b8f
682,930
def titleize(phrase): """Return phrase in title case (each word capitalized). >>> titleize('this is awesome') 'This Is Awesome' >>> titleize('oNLy cAPITALIZe fIRSt') 'Only Capitalize First' """ return phrase.title()
ae530105eeb00917e36534b1a51b4ca9571ad8e4
682,931
def count_parameters(model): """The number of trainable parameters. It will exclude the rotation matrix in bottleneck layer. If those parameters are not trainiable. """ return sum(p.numel() for p in model.parameters())
b435bec5a595906b28f82872ca97c34df83f744b
682,932
def add_gaussian_noise(xs, std): """Add Gaussian noise to encourage discreteness.""" noise = xs.new_zeros(xs.size()).normal_(std=std) return xs + noise
c8dd93ba06075903faeb2c4b537f0210d213f9fd
682,933
def concatenate_dictionaries(d1: dict, d2: dict, *d): """ Concatenate two or multiple dictionaries. Can be used with multiple `find_package_data` return values. """ base = d1 base.update(d2) for x in d: base.update(x) return base
d35391843b299545d6d7908e091ac9b9af274979
682,934
import torch def invert_permutation(perm: torch.Tensor) -> torch.Tensor: """ Params: perm: (..., n) Return: inverse_perm: (..., n) """ # This is simpler but has complexity O(n log n) # return torch.argsort(perm, dim=-1) # This is more complicated but has complexity O(n) ...
e559a8e091689bc6c3cffd3bb0590354f28935d8
682,935
def nulls(x): """ Convert values of -1 into None. Parameters ---------- x : float or int Value to convert Returns ------- val : [x, None] """ if x == -1: return None else: return x
d87c6db9755121ec8f2ec283fb6686050d31b009
682,936
from typing import List def compute_skew(sequence: str) -> List[float]: """Find the skew of the given sequence Arguments: sequence {str} -- DNA string Returns: List[float] -- skew list """ running_skew = [] skew = 0 for base in sequence.upper(): if base =...
678510360d2c8ab39c5f91351e90d08ddad3f9bb
682,937
import base64 import hashlib def generate_hash(url): """ Generates the hash value to be stored as key in the redis database """ hashval = base64.urlsafe_b64encode(hashlib.md5(url).digest()) hashval=hashval[0:6] return hashval
51add11d40c5a9538d5794de8d5724705436c0ea
682,938
def is_connected(node1,node2,G): """returns True if node1 and node2 are connected in G. Otherwise returns False Prec:G is a dictionary. node1 and node2 are keys in G""" to_visit=G[node1] visit=[node1] while(to_visit!=[]): cur_node=to_visit[0] visit.append(cur_node) to_visit=t...
b92eac52efd8941ea4ec786393c8f3c0b09499fb
682,939
import numpy def spatial_displacement(pos1, pos2): """ :param pos1: :param pos2: :return: """ return (numpy.array(pos1) - numpy.array(pos2)).flatten()
8eb746313c9335f6e735b00fad68619f52e784a9
682,940
def Fplan(A, Phi, Fstar, Rp, d, AU=False): """ Planetary flux function Parameters ---------- A : float or array-like Planetary geometric albedo Phi : float Planetary phase function Fstar : float or array-like Stellar flux [W/m**2/um] Rp : float Planetary ...
5f7b92e31ba22bd44f2e710acb4048fd9860409b
682,941
import torch import time def time_synchronized(): """pytorch-accurate time :return: time """ if torch.cuda.is_available(): torch.cuda.synchronize() return time.time()
a390828bdd3f023625cc848d61c161f77157c2e0
682,943
def stats(func): """Stats printing and exception handling decorator""" def inner(*args): try: decoded = func(*args) except ValueError as err: print(err) else: return decoded return inner
d166b7ac31de49f03acbdef9564c11ba49fabfe8
682,944
def create_inventory(items): """ Create an inventory dictionary from a list of items. The string value of the item becomes the dictionary key. The number of times the string appears in items becomes the value, an integer representation of how many times. :param items: list - list of items to c...
9fb15b9c742d03f197c0e0fc402caa94d47f65b4
682,945
import os import re def get_special_paths(dirname): """Given a dirname, returns a list of all its special files.""" result=[] paths=os.listdir(dirname) for fname in paths: match=re.search(r'__(\w+)__',fname) if(match): result.append(os.path.abspath(os.path.join(dirname,fname))) return re...
30c0cf4fb5b4a6b1f2fa9588d04890a3cfdaa95e
682,946
def get_component_type(schema): """Due to quirks in the pyasn1 library, for some schema types the componentType is not properly set, so we use this convinience method to access the underlying data if required""" return schema.componentType if (len(schema.componentType) > 0) else schema._componentType
a86f2b520912c242e42a443a5a6efe0b7421f8c6
682,947
import six def get_paramfile(path, cases): """Load parameter based on a resource URI. It is possible to pass parameters to operations by referring to files or URI's. If such a reference is detected, this function attempts to retrieve the data from the file or URI and returns it. If there are an...
e9a55bf9459f609f9a39678cd97541318a0ba48f
682,949
def get_default_app_name(site, user): """get the default app for the currrent user""" if user.is_authenticated: default_app = site.config.get('apps', 'home', 'home') else: default_app = site.config.get('apps', 'index', 'content') return default_app
e5d70e7aa625f6f3cced73f4f7f96b382c77d5ce
682,951
def adds_comment_sign(data: str, comment_sign: str) -> str: """Adds comment signs to the string.""" return "\n".join(list(f"{comment_sign} {line}".strip() for line in data.split("\n")[:-1]))
a78d21fd1ae5325911e9b3e5bec3bf81f86757d1
682,952
import six import numpy def numpy_to_python(val): """Convert numpy types to their corresponding python types.""" if isinstance(val, (int, float)): return val if isinstance(val, six.string_types): return val if (isinstance(val, numpy.number) or isinstance(val, numpy.ndarray) and...
4d556fa1b42980faff5bd8ba55ce81afd576eca1
682,953
def framecycler_stereo_available(): """This function used to detect if we were running on Mac OS Tiger; we no longer support Tiger, so this function always returns true now.""" return True
867667455f732562b3467e64bd75addb6ded8dae
682,955
def positive_coin_types_to_string(coin_dict): """ Converts only the coin elements that are greater than 0 into a string. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ plat = "" gold = "" silver = "...
e4ad715e008fd836992b8023772a71cba16818bf
682,956
def iprs_from_docs(aliases,**kwargs): """Returns a list of IPRs related to doc aliases""" iprdocrels = [] for alias in aliases: for document in alias.docs.all(): if document.ipr(**kwargs): iprdocrels += document.ipr(**kwargs) return list(set([i.disclosure for i in ipr...
14d10b38720dccb662ef5e389058abde4cbfada0
682,957