content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy def mat33_by_mat44(mat): """ Extract a 3x3 matrix from a 4x4 matrix. :param mat: :return: """ m = numpy.eye(3, 3) for i in range(3): for j in range(3): m[i][j] = mat[i][j] return m
984b6fee91eb793d305f6d26de19ca9edc55aaef
641,975
import torch def bboxes2tblr(priors, gts, normalizer=4.0, normalize_by_wh=False): """Encode ground truth boxes to tblr coordinate. It first convert the gt coordinate to tblr format, (top, bottom, left, right), relative to prior box centers. The tblr coordinate may be normalized by the side length of...
942ddf4baafb76141607485e388117816d69f908
641,977
def run(dfs: dict, settings: dict) -> dict: """df.drop_duplicates(subset={})""" subset = settings['subset'] if 'subset' in settings else None keep = settings['keep'] if 'keep' in settings else 'first' dfs[settings['df']] = dfs[settings['df']].drop_duplicates( subset=subset, keep=keep, ...
53cdd62341bab6159cdd8175734f108177c589c2
641,978
def interpolate_linear(a, b): """ ((b-a)*alpha) + a """ def _interpolate_linear(alpha): # See exponential #(b-a)*alpha + a return a * (1.0 - alpha) + b * alpha return _interpolate_linear
22e1335f79fdaa41e23865cdc82058ae46458017
641,979
def order_from_ordered(ordered, data): """ build a ordered list from a desordered list with elems in ordered ordered = [5, 3, 1, 6, 2] this elems are ordered acordenly to importance data = [3, 2, 5] result is [5, 3, 2] """ index = {} for i, elem in enumerate(ordered): ind...
1a4bf9d25a0f5f05ec311912a707af33ff639a6b
641,980
def true_boolean(value): """Convert the string value from a SettingBoolean to a true bool""" value = str(value) sound_settings_values = [b"0", b"1"] if value in sound_settings_values: return bool(sound_settings_values.index(value)) else: return False
547d85a4d796ed8256efe71d9a9a492e9e540555
641,981
from typing import Any def cls_is_annotated(cls: Any) -> bool: """ Inspect if a class has annotations Args: cls (Any): Class to inspect Returns: bool: True if cls is annotated else False """ return ( hasattr(cls, "__dict__") and "__annotations__" in cls.__dict...
6d26d77310248917a8568516637cb3dcc27c21db
641,982
def calc_relative_density_boulanger_et_al_2014_cpt_values(q_c1n, c_dq=0.9): """ Table 4.1 in PM4Sand v3.1 manual Parameters ---------- q_c1n: array_like Normalised cone penetration resistance c_dq: float, default=0.9 (from :cite:`Idriss:2008ua`) Correlation factor, (range 0.64-1...
56042ae414e415843ed9a911383e2d0506c6b7b4
641,983
import inspect def get_name_from_pyusb_backend(backend): """internal: return backend name from loaded backend""" module = inspect.getmodule(backend) if not module: return None return module.__name__.split(".")[-1]
b6a4c6352c0bbc512d44566ae6817552820bba27
641,984
def design_data(self): """ """ # output = [] output.append("\n") output.append("{:}\n".format(88*"_")) output.append("\n") output.append(" PIPING DESIGN DATA\n") output.append("\n") output.append("Pipe ID Pi [N/mm2] Po [N/mm2] T1 [degC]...
6e5087197075393817d414090f30d54f2e013aa1
641,985
import os def env_get_yaml_path(project_path, name): """ Get YAML environment path. :param project_path: Project path (str) :param name: Environment name (str) :rtype: Absolute path to environment file (str) """ return os.path.join(project_path, "envs", "".join((name, ".env....
950c5942974c56fc4ad714af7081dad9dbf46358
641,986
def get_row_col_matrix(row_index_set, col_index_set): """ Returns the resulting matrix when using a row and column of indices (list of tuples) row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16. col_index_set: the index set that would be...
f074fedfb681d40d8fafb3c2de8aa99d2601b907
641,987
def _UsingGtestJson(options): """Returns True if we're using GTest JSON summary.""" return (options.annotate == 'gtest' and not options.run_python_script and not options.run_shell_script)
400d454fb00639395f44e1c5f99be1a0a53e6b4c
641,988
def get_invalid_reposlug(reposlugs): """ Checks invalid reposlug """ for x in reposlugs: if len(x.split('/', 1)) != 2 or '' in x.split('/'): return x return None
9a7f4f4809904f63cc540be43e151ccc45f01b3f
641,989
def hhmmsstime(strt): """ This converts a string format of the time into seconds """ try: h, m, s = strt.split(":") return int(h) * 3600 + int(m) * 60 + int(s) except: return 0
25f3bd14987bfaff9b3f1f638fe245f380ea1411
641,990
import numpy def _find_fend_from_coord(hic, chrint, coord): """Find the next fend after the coordinate on chromosome 'chrint'.""" if hic.binned is not None: first_fend = hic.fends['bin_indices'][chrint] last_fend = hic.fends['bin_indices'][chrint + 1] return numpy.searchsorted(hic.fend...
03f4ac9d0b8a15efd683cedae17d74859cd10201
641,991
def CSourceForArrayData(values, formatter, margin=4, width=80): """Turn an array of values into a C source array data definition. Args: values: Array of input values. formatter: Formatting function, applied to each input value to get a C-source description of the value. margin: Left-side margin /...
602c0cc6fab36647db2b6cddd5e51af920672f2f
641,992
def handle_year_stradling(date_time): """ Deals with the scenario of the water year starting in 10/1/N and ending in 10/1/N+1, assumes that the water year is asssociated to the bulk of time at the year which is N+1 Depending on the time, will return the appropiate year for the starting point ...
012ba16e53e4ce7652c0a9dd72b5491c8c886d45
641,993
def get_binary_mask_from_raw_address(raw_address: str) -> str: """ Return binary mask from raw address. >>> get_binary_mask_from_raw_address("192.168.1.15/24") '11111111.11111111.11111111.00000000' >>> get_binary_mask_from_raw_address("91.124.230.205/30") '11111111.11111111.11111111.11111100' ...
a29567d0cebf2b4442f1f242f547c766726cd9f2
641,994
def cyclic(graph): """ Return True if the directed graph has a cycle. The graph must be represented as a dictionary mapping vertices to iterables of neighbouring vertices. For example: >>> cyclic({1: (2,), 2: (3,), 3: (1,)}) True >>> cyclic({1: (2,), 2: (3,), 3: (4,)}) False """ ...
de8a768af9705b5c8a7b8a8c3f2d9a651e089ba4
641,995
def read_mpconfig(): """ Open 'circuitpy_mpconfig.mk' and return the contents. """ configs = [] with open("py/circuitpy_mpconfig.mk") as mpconfig: configs = mpconfig.read() return configs
55335df06bca16ab12483960d49573e83b07e5d3
641,996
def _search_topk_similar_through_categories(tool, text, categories, k): """ 從 Categorise 中找最相近的 k 筆 Category return hash_word:{Similarity,word} """ _MaxSimilarity = -99 close_word = 'none' hash_word = {} # hash map for recording (Key:sim, Value:close_word) maxk = [] ...
04f067a01babe9464adbb3c0796209e9d7a16d01
641,997
def get_alignment_overhangs(alignment): """Remove gap overhangs from the alignments. There are cases where no template sequence is availible for a big chunk of the protein. Return the number of amino acids that should be removed from the start and end of the query sequence in order to match the templat...
9da29e9c395f01968bf05ce8c68f93e0f5357af1
641,998
def _creation_options_for_cog(creation_options, source_profile, blocksize): """ it uses the profile of the source raster, override anything using the creation_options and guarantees we will have tiled raster and blocksize """ if not(creation_options): creation_options = {} creation_opti...
e722098390a136b86758d4e799f4d22e8d00629c
641,999
def high_income_amount(responses, derived): """ Return the guidelines table amount for a high income earner """ try: under = float(responses.get('child_support_amount_under_high_income', 0)) except ValueError: under = 0 try: over = float(responses.get('amount_income_over_high_i...
588ce06fd276be6695b0cab852ab6020a404338f
642,000
def get_col(df, key): """ Return a DataFrame column by either name or numeric index. :param df: A pandas.DataFrame :param key: A string or int :return: The indicated column from the dataframe, either by name or order. """ try: if isinstance(key, int) and (key not in df.columns): ...
f91155c9200a1e3f2132d4c5601f771a4f06d2c2
642,002
def player_odds(player): """Print this.""" total = 0.0 if "B" in player: total += 1 if "D" in player or "Q" in player: total += 2 if "J" in player or "N" in player: total += 3 if "A" in player or "O" in player: total += 4 if "C" in player or "P" in player: ...
aa2780f628fbb45424ff75a4d0f31fa1cbd0d9bd
642,004
import torch def generate_noise(max_norm, parameter, noise_multiplier, noise_type, device): """ A noise generation function that can utilize different distributions for noise generation. @param max_norm The maximum norm of the per-sample gradients. Any gradient with norm higher than this ...
fdd2689baf1b21e76aaf0655d887c1d4976237dc
642,005
import pathlib def get_testdata_file_path(rel_path: str) -> pathlib.Path: """Gets the full path to a file in the testdata directory. Arguments: rel_path -- path relative to testdata/ Returns: pathlib.Path -- the full path to the file. """ return pathlib.Path(__file__).parent / "t...
48431abacceb289a8349bd10b911001525caf954
642,006
import re def regex_replace(in_str, regex_pattern, regex_replacement): """ On a given text input, replace it with a regular expression """ regex = re.compile(regex_pattern) return regex.sub(regex_replacement, in_str)
627f9dfb83629915b3e4bbf21c9f3273e4bf61f4
642,007
def usage_hint(command, shell): """ Returns the usage hint and comment, for the given shell. """ if shell == "fish": return ("eval ({command})".format(command=command), "#") elif shell == "powershell": return ( "{command} | ForEach-Object {{If (-Not[string]::IsNullOrEmpty...
e82469240fbf8f37daa0cebf7b40a500e27298ae
642,008
import random import string def latin(minimum=3, maximum=8, separator=' '): """ Simple function to generate fake (two parts) Latin species names. :param minimum: int, minimum number of letters in each part of the Latin name. :param maximum: int, maximum number of letters in each part of the Latin...
ed5f0c7625af90e783015cd6304a2e2dd77d1762
642,010
import math def _perplexity(self): """ Pythonification of the formal definition of perplexity. input: a sequence of chances (any iterable will do) output: perplexity value. from https://github.com/zeffii/NLP_class_notes """ def _perplex(chances): chances = [i for i in chances if...
082477b3ed8c7f9b0662f2b00e01128ccd267516
642,011
import os def FileModifiedTime(file_name): """Enables mocking in the unit test.""" return os.stat(file_name).st_mtime
ab6276a92e85e97687a4f90e5cab9b5152e471ab
642,013
def report(sufficient_items, insufficient_items, condition, output = ".", prefix = None, **kwargs): """ Report the symbols which did not pass the condition. Parameters: sufficient_items: List of (name, object)-tuples that passed the condition insufficient_items: List of (n...
359ba53b7ad68747a311606bc311306c8d1c1a07
642,014
def adjust_header(header): """Adjust a FITS header for use with aplpy.""" for i, k in enumerate(header): if not k or k == 'COMMENT': header.pop(k) return header
28dc3b6904c76db0bf66f40b6fcf3ccac3866451
642,015
def squeeze_batch_dim(tt): """Converts batch size 1 TensorTrainBatch into TensorTrain. Args: tt: TensorTrain or TensorTrainBatch. Returns: TensorTrain if the input is a TensorTrainBatch with batch_size == 1 (known at compilation stage) or a TensorTrain. TensorTrainBatch otherwise. """ tr...
eea54ca8b6c4582751b3bc76a519f911c6ecddf7
642,016
import torch def efficient_causal_attention_seq(x, y, z): """ efficient causal attention operation Args: x (Tensor): Tensor with shape `(batch, n, d1)` y (Tensor): Tensor with shape `(batch, n, d1)` z (Tensor): Tensor with shape '(batch, n, d2)` return: """ n = x.size(...
2577d0d74bf86d83f402b293f6e844accd86d32d
642,017
import platform def get_hostname(): """Returns hostname.""" return platform.node()
b5ee938f142b840c4756ec65614797f821f33b95
642,018
def open_shift(self): """ Открыть смену. """ return self.protocol.command( 0xE0, self.password )
8129c24251fb062b1b3a30da374d98301a1027ba
642,019
import math def get_hot_value(gtread_value, tweets_value): """Calculate key-words hot value in google trend and tweets. Parameters ---------- gtread : float google trend index tweets_value : float twitter trend index Returns ------- float hot value """ ...
2e9ae4ddb27a9c5a66b5127fb4e71cd246b34d10
642,020
def _how(how): """Helper function to return the correct resampler Args: how: """ if how.lower() == "average": return "mean" elif how.lower() == "linear": return "interpolate" elif how.lower() == "no": return "max" else: return "max"
4fe9038d37cfedf61a62865aba24de8023e0f888
642,022
def test(test_cases, function): """Given a dictionary of test_cases containing inputs and their expected results after a function has been run on them, returns True if all passed, returns False if any fail with a print statement on each failure.""" successful = True for test_case in test_cases: ...
41407be59ea0933f122cfe0f1dd7aadee0433e58
642,023
from pathlib import Path import logging def get_most_recent_run_id(run_recovery_file: Path) -> str: """ Gets the string name of the most recently executed AzureML run. This is picked up from the `most_recent_run.txt` file. :param run_recovery_file: The path of the run recovery file :return: The r...
e36041ccebfd146997142bd03d610b246888f46f
642,024
import subprocess def task_test(): """Run all tests""" def run(args): args = args or [] subprocess.run( ['python', '-m', 'pytest', '-s', '-p', 'no:cacheprovider', *args], cwd='test', check=True) return {'actions': [run], 'pos_arg': 'args'}
c1a67a506b02c6c84fed5cc48bf43c3571eed8c0
642,025
def setup_sigcopy(args): """Determine if an extra copy of the atmospheric signal is needed. When we simulate multichroic focal planes, the frequency-independent part of the atmospheric noise is simulated first and then the frequency scaling is applied to a copy of the atmospheric noise. """ if ...
fb22c91d42881fe51b4682ddbcc119d344552261
642,026
import pandas def transform(data, transformation_df): """Transform coordinates in `data` using `transformation_df` data : 2d DataFrame with 2 columns, ending in 'x' and 'y' transformation_df : must have columns shift_x, shift_y, c00, c01, c10, c11 Returns: DataFrame shaped like `data` ...
5650031c883f965cbcd101e216ac4dead73a3c03
642,027
import re def parse_name(spec): """ Function that writes short names of the species to name the nodes. It counts how many times a monomer_pattern is present in the complex pattern an its states then it takes only the monomer name and its state to write a shorter name to name the nodes. Parameters...
7c62585b6bcd1ae932cd31609cc4b1d4fe0c8c4e
642,028
import sys def _os_decode(b, enc=sys.getfilesystemencoding()): """Turns a `bytes` into `unicode` via decoding.""" return b.decode(enc, 'strict')
432ca307ead5c4eef7f1b39a8dd24a13b9f5005d
642,029
def substr(qualified_name): """ 去掉字符串前的节点类型 :param qualified_name: 'result_table_591_durant1115' :return:'591_durant1115' """ type_list = ["result_table_", "data_processing_", "raw_data_"] for each_type in type_list: if each_type in qualified_name: qualified_name = qualif...
c105a3b8b4d35fa2fbfb43238a14345419bd366d
642,030
def nested_get(dic, path, delimiter='.'): """Get from dictionary by path :dic dict Source dictionaly. :path string Path withing dictionary :delimiter string Path delimiter :return: Value at path :rtype: unknown """ try: keys = path.split(delimiter) for key in keys[:-1]: ...
7ce38dfff407c286d38634d11b00b384ea1d69de
642,031
def str2num (text:str)->float: """ Convert string to number. Keyword arguments: text -- number in string format Output: number -- number converted """ assert text.isnumeric(),"Error: The string can not be converted to a number" number = float(text) retu...
22db18949633092f12e1cafc7470f07e821fd4a4
642,032
def get_intersection(x1, y1, x2, y2, x3, y3, x4, y4): """Return intersection between segment 1 (p1-p2) and segment 2 (p3-p4).""" p1x = min(x1, x2) p2x = max(x1, x2) p3x = min(x3, x4) p4x = max(x3, x4) if p1x == x1: p1y = y1 p2y = y2 else: p1y = y2 p2y = y1 ...
7daba3206ef59a2f2c160ef9bfe41684f4b480ff
642,033
def _load_output_format_file(_output_format_file): """ Loads DCASE output format csv file and returns it in dictionary format :param _output_format_file: DCASE output format CSV :return: _output_dict: dictionary """ _output_dict = {} _fid = open(_output_format_file, 'r') for _line in _f...
f37759ce9b55f712fdfc0f3ae74b6f9fbf4a4a5d
642,034
def get_digits(num: int) -> str: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(list(str(num ** 3))))
d924d9a0156b13725a01ccbb1bebe038bf4644bd
642,037
def validate_nag_function_name(name): """ Check wether a NAG function name is valid """ if ( name is not None and isinstance(name, str) and len(name) > 1 and name[1:].isdigit() and ( name[0:1] in ['i','n','o'] or ...
d89c407137152c9bb75be472be397563fb6635de
642,038
def fixMDA(d): """usage: d=fixMDA(d), where d is a list returned by readMDA()""" dimensions = [] for i in range(1,len(d)): npts = d[i].curr_pt d[i].npts = npts dimensions.append(npts) for j in range(d[i].np): if (len(d[i].p[j].data) > npts): d[i].p[j].data = d[i].p[j].data[0:npts] for j in range(d[i...
d43b1aa07cd9b45a7de45b6ea887a8bc2f68534a
642,039
def create_auth(auth_spec): """Creates auth body of message""" if auth_spec.type == 'none': return b'' if auth_spec.type == 'direct': return auth_spec.app_name.encode('utf-8') return b''
d0347b3a10a4937d8c34ebd638129f45101a1401
642,040
def apply_func_to_ast_helper(ast, func, acc): """Recursive helper function for "apply_func_to_ast". Args: ast: The AST instance. func: The function applied to the AST elements. acc: A list of values accumulated during application. Returns: The adapted AST. """ if is...
3a3a55540186b4b19876942423f165a2be4aa54c
642,041
def read_file(fp): """ Returns file content """ with open(fp, 'r') as f: content = f.read() return content
2d1adfd76e20a528a0261abf7b2bb820e3b5326d
642,042
def upper_section_score(die_value, final_dice, scorepad, ): """Evaluate dice from a roll for a given value and multiply the count by that value. E.g. for a die value of 3 and a count of two dice with that value the total score is 6 (die...
488d64cb1dcaf2810ae2a5cb0c8e535c1da375a1
642,043
import os def fetch_TCGA_BAM(acc, token, outdir=".", filter_bed=None): """Get BAM file from TCGA repository based on UUID. Will return statement and path/filename of downloaded file. A bed file may be provided to filter to remove contigs not present in the reference genome""" statement = [] ...
3e4b32cf258b056f781bb7799485b9c2e6bf361a
642,044
def bam_indexing(samtools, variable_name): """Will take a file variable name and a samtools path and will print bash code that will create a bam index using samtools """ return ('# Indexing\n' + samtools + ' index $' + variable_name + ' >> $logFile 2>&1')
60f5b3d123570fd4ba7faf8b3f49d46c77f1d45d
642,045
from typing import Dict async def raceplan_mock() -> Dict: """Create a raceplan object.""" return { "id": "raceplan_1", "event_id": "event_1", "no_of_contestants": 8, "raceplan_id": "raceplan_1", "races": [ "race_1", "race_2", "race_3...
4808d80d08294ba81ecad7a854f5b3be5eb6a48f
642,046
def find_weakness(data, wrong_value): """ Finds the weakness according to star2 day09 puzzle """ index_of_wrong_value = data.index(wrong_value) weakness = [(min(data[start:end]) + max(data[start:end])) for start in range(0, index_of_wrong_value) for end in range(st...
77fd445c809b7ee9e1331029b736c70f8cb211a5
642,047
def program_code_store_cwd_json(path: str) -> str: """ Creates program code that stores its working directory as JSON into the specified `path`. """ return f""" import os with open("{path}", "w") as f: f.write(os.getcwd()) """
4b529a0fe6dd26d06564dab4f4a691529cec9c41
642,048
def letterize(bytes_): """ Canonicalize a byte sequence. Removes non-alphabetic characters and converts to lower case. """ return bytes(b for b in bytes_ if chr(b).isalpha()).lower()
4eedae64acc020781af0c3005b7c0aea949da47c
642,049
def calculate_ia_penalty(ia): """ This function receives ia array and calculates the sum ia values based on timing slot. :param ia: :return: """ sum_ia = 0 for i in range(len(ia)): if ia[i] > 0: sum_ia += (i+1)*ia[i] return sum_ia
3845c93489ada3716a6b38055ea780346fc9032f
642,050
import torch def kl_divergence(p, q, clip=False): """Generalized KL divergence [1] for unnormalized distributions. Args: p: tf.Tensor. q: tf.Tensor. clip: bool. Returns: tf.Tensor of the Kullback-Leibler divergences per example. ## References [1] Lee, Daniel D., and H. ...
c2a8fd36510ec17e438afd09f618b2d9cfe89a90
642,051
def evalt(t): """ Evaluate tuple if unevaluated >>> from logpy.util import evalt >>> add = lambda x, y: x + y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 """ if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return t
6214f6c3e35be0556e04d5994d6f2e730756917a
642,052
def reverse_transcript_rna_char(base_char: str) -> str: """ A function that reverse transcripts mRNA char into DNA char returns '' when base char is not one of RNA bases :param base_char: :return rna_char: """ dict_of_rna_to_dna_base = {'A': 'T', 'U': 'A', ...
c4d4debdf21cf25f2045ddb64642a034b4fda2a5
642,053
import os import fnmatch def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): ...
8c8fd3b74539676ae52e8c564c6de5c7f1574740
642,054
from pathlib import Path def infile_gsd(): """The path to a gsd file which can be used for input. This is to test all the analysis which uses the gsd files as input. """ return Path(__file__).parent / "data/trajectory-Trimer-P13.50-T3.00.gsd"
f7ebaa6f5e7df9f6310c92d894628436a23dacb2
642,055
def intinlist(lst): """test if int in list""" for item in lst: try: item = int(item) return True except ValueError: pass return False
e10fd2371c86cdd4ef1b9af1049d64d635a6acb5
642,056
from typing import Tuple def rotation_plane(xyz: Tuple[int, int, int]) -> Tuple[int, int, int]: """ Rotation des Punktes xyz um 90° im Uhrzeigersinn um eine z-parallele Achse durch den Punkt (2,2.0). :param xyz: Diesen Punkt rotieren. :return: Die Koordinaten nach der Rotation. """ return ...
1eae0cd066cff54d2f7c25d5aa41d046e2f363c4
642,057
def bond_or_stake(bond_price, ohm_price, reward_rate, n_rebase_to_fully_vested=15, claim_interval=1): """ Assumptions ----------- * Constant APY over vesting period: reward_rate == reward_yield, i.e. the amount of staked OHM doesn't change over the vesting period. * No trans...
4187ad7574a132d9cf0114e965200fd547ae5e2b
642,061
from typing import Counter def to_quest_counter(ques_index): """ 將問題集的索引先合併到一個集合,然後使用 Counter進行group by 加總 :param ques_index: :return: group by dictionary [3,5,7,9,3,5,5] => {3:2,5:3,7:1,9:1} """ all_ques_index = [] for i in ques_index.values(): all_ques_index += i return...
1b8f04200a37397b196c165f97385bb1aa301df1
642,062
def change_ext(input_fn, new_ext, no_dot=False, remove_player=False): """ Return the input path `input_fn` with `new_ext` as extension and the part after the last '-' removed. If `no_dot` is True, it will not add a dot before of the extension, otherwise it will add it if not present. `remove_pla...
6f0563dbb72def59034f37feeffa6574b3e7b428
642,063
import sys import traceback def exception_message(): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, ...
e820308cdee313118e273842abf950d308b71927
642,064
def get_atoms_for_flow(flow, persistence_backend): """ Gets all atoms for a flow :param obj flow: A TaskFlow flow :param obj persistence_backend: A connection to the persistence backend :return iter[obj, ..] all_atoms: An iterable of atom objects """ return persistence_backend.get_atoms_for_...
f42fb5d71b7bcb061cb1cf1559781e3140622188
642,065
import typing def calcNthTerm(a_1: typing.Union[float, int], r: typing.Union[float, int], n: typing.Union[float, int]) -> typing.Union[float, int]: """ Calculates the nth term of a geometric progression (an = a1 * r^(n-1)). :param a_1: First term. :param r: Common ratio. :param n: Number of desire...
e6dce78e4aad43333819a0db07c265fc00b237d3
642,066
import torch def eye(m, dtype=None, device=None): """Returns a sparse matrix with ones on the diagonal and zeros elsewhere. Args: m (int): The first dimension of corresponding dense matrix. dtype (`torch.dtype`, optional): The desired data type of returned value vector. (default i...
21d4f5a2460b07d75f4e7ffed9a8ee89c2e220d7
642,067
import tempfile import os def temp_file(ext='tmp'): """Get a temporary filename with the given extension. This function will actually attempt to create the file.""" tf, fn = tempfile.mkstemp(suffix='.%s'%ext) os.close(tf) return fn
77c68a151e11c48a3f52a033d28250f4f9c698b3
642,068
def get_tag(record, name, default=None): """ Loks in the XML tag 'record' for other tags named 'name', and returns the value of the first one. If none is found, it returns 'default'. """ tag = record.getElementsByTagName(name) if len(tag) and len(tag[0].childNodes): return tag[0].chi...
77631e4788e1d8cc0deba0e27e41be0b3a56fd56
642,070
def BuildIdToBuildStatus(db, build_id): """Fetch a BuildStatus (with stages) from cidb from a build_id. Args: db: cidb.CIDBConnection object. build_id: build id as an integer. Returns: build status dictionary from CIDB with 'stages' field populated. """ build_status = db.GetBuildStatus(build_id)...
3d38d040d834e4d41afc99edfb9226f234347724
642,071
from io import StringIO def to_XML_string(Coalesce_object, indent_level = 1, pretty_print = True): """ Assigns the XML representation of a Coalesce object to a string. :param Coalesce_object: a Coalesce object with an "export" method :param level: multiply by 4 to determine the number of spaces for...
e981dd7efb18b2254b6b12af8bd32a748c6774fd
642,072
def compute_gravitational_force(cphi, sphi, ctheta, stheta, mass, g): """ Gravitational force expressed in body frame """ fx = -mass * g * stheta fy = mass * g * ctheta * sphi fz = mass * g * ctheta * cphi return fx, fy, fz
4b753b88a743cee451dd5c38cdd5c8727ec97441
642,073
def diff_column_tags(src_data_columns, atlas_columns): """ :param src_data_columns: Source data with all columns. :param atlas_columns: Atlas columns retrieved with Sync.columns_from_atlas() :return: Dict of columns where value is (tags only in src, tags only in atlas) """ result = {} for co...
23b1dfb4a8d6ff3b079d7f1fff217b84eee62283
642,075
def create_data_model(full_matrix, full_product_name_list, list_name): """Stores the data for the problem.""" list_index = [] for name in list_name: index = 0 found_product = False for i, prod in enumerate(full_product_name_list): if full_product_name_list[i] == name: ...
78755bd7a60d0f8185af6f5e6360e93d952ec36a
642,076
def has_permission(user, item): """ :param user: {'id': str, 'creation_date': float, 'groups': [str], 'email': str, ..+} :param item: {'id': str, 'creation_date': float, 'partition': str, 'owner': str, 'read_groups': [str], 'write_groups': [str], ..+} :return: bool, determines if user has permission to ...
38d53dc0ce726cf869769eb576a038eb057e3ce2
642,077
def average_of_factors(n): """ n (int): number Returns the average of the positive divisors of n """ # Initialize the sum total = 0 # Initialize the number of factors count = 0 for i in range(1, n+1): # Check if i is a divisor of n if n % i == 0: total += ...
622f5793685c03ec0b367c23313327264a79b9b2
642,078
def is_valid_read(read): """Check if a read is properly mapped.""" if (read.mapping_quality >= 20 and read.reference_end and read.reference_start): return True return False
1ad54406c86a5375b880d6cc00afad3a173fda58
642,079
import re def convert_coordinates(x): """Return right coordinate format """ long = x.replace('.',',') rep = re.sub('(,[^,]*),', r'\1', long) rep = rep.replace(',','.') return rep
c63501137d474cfa9ac6fb16166a4e0737570d13
642,080
def calc_time_axis(df): """Returns the number of minutes between midnight of the earliest date and midnight of the day after the latest date in the dataset""" time_min = df.Timestamp.min() time_max = df.Timestamp.max() diff_in_days =(time_max.date() - time_min.date()) diff_in_minutes = (dif...
d7d5ef397381815405e38e018a01a8618db9c348
642,081
def create_probs_from_genotypes(genotype): """Creates probabilities from an additive genotype.""" if genotype == 0: return (1, 0, 0) if genotype == 1: return (0, 1, 0) if genotype == 2: return (0, 0, 1) if genotype == -1: # Lower than normal probabilities r...
6ca39091fb70beeebe207eb927b9ba04ea477fee
642,082
def filter_cds_utr_ncrna(df_in): """Filter regions CDS, UTR5, UTR3 and ncRNA by size and trim.""" utr5 = df_in.region == "UTR5" cds = df_in.region == "CDS" utr3 = df_in.region == "UTR3" ncrna = df_in.region == "ncRNA" size = df_in.end - df_in.start >= 100 df_out = df_in[(utr5 & size) | (cds ...
41ff9d99d6ac318c88aa19262b06798172a75e69
642,084
def url_joiner(url, path, trailing=None): """Join to sections for a URL and add proper forward slashes""" url_link = "/".join(s.strip("/") for s in [url, path]) if trailing: url_link += "/" return url_link
888abf4917fbcb476f39a6cda7cc46880bd9aa4e
642,085
def get_attractions_by_distance(city_data, distance): """Return a attractions list based on distance.""" # type: (Dict, str) -> List return [a for a in city_data["attractions"] if int(a["distance"]) <= int(distance)]
278e2e90a196d5b7306ab8d4c428de3134bd1d27
642,086
def server_read(conn): """Read incoming client message and create echo message to client.""" buffer_length = 16 message_complete = False message = [] while not message_complete: part = conn.recv(buffer_length) message.append(part) if len(part) < buffer_length: br...
8592a3887c378f9d9ad620c02b2a989d1d962783
642,087
import os def get_stack_element_in_config(config, stack): """ The path_spec of a config element if it is named like stack and has a root level file named stack.xml """ for entry in config.get_config_elements(): if entry.get_local_name() == stack: if os.path.isfile(os.path.join(...
5bcb2c3bfdc0c0feabd6090bf3882c3714f86df1
642,088