content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import random def randint(start: int, end: int) -> int: """Returns a random integer""" return random.randint(start, end)
0f0f7a8fda9287c6260ad5e201de1bd16065bbb1
667,497
def helper_properties_def(properties): """ Convert properties from a Fiona datasource to a definition that is usable by `dict_reader_as_geojson` and utilizes the helper functions for better value handling. Sample input: { 'float_field': 'float:14', 'int_field': 'in...
07e368026842eae5bb59b3fc4fe3860672c0daf9
667,500
from pathlib import Path import shutil def copy_to_tmp(origin: Path, dest: Path) -> Path: """ Copy `origin` to temp `dest` """ shutil.copy(origin.as_posix(), dest.as_posix()) return dest / origin.name
82929c88109889a9af8802ff154b70237b3ce1cc
667,503
import random def init_neurons(count): """ Initialize the weights of the neurons :param count: number of neurons to initialize :return: list of neurons as weight vectors (x,y) """ return [[random.uniform(0.0, 1.0), random.uniform(0.0, 1.0)] for i in range(count)]
98be8fc1f621e2c768af3c93d1a0254ac42a4ffc
667,504
def custom_name_func(testcase_func, param_num, param): """Generates friendly names such as `test_syntax_while`.""" return "%s_%s" % (testcase_func.__name__, param.args[0])
a2800267987bdafb82636e4391f95db2e4872edb
667,505
def iodineIndex (Na2S2O3_molarity, Na2S2O3_fc, Na2S2O3_volume_spent, blank_volume, sample_weight): """ Function to calculate the iodine index in grams of iodine per 100g """ V_Na2S2O3 = blank_volume - Na2S2O3_volume_spent iodine_mols = (Na2S2O3_molarity * Na2S2O3_fc * V_Na2S2O3) / 2 iodine_mg = ...
9af3c55d90228f43c16885b6e2f828ffae195296
667,508
def time_to_seconds(time): """Convert timestamp string of the form 'hh:mm:ss' to seconds.""" return int(sum(abs(int(x)) * 60 ** i for i, x in enumerate(reversed(time.replace(',', '').split(':')))) * (-1 if time[0] == '-' else 1))
55dbf2f8a57f3a57c593afda908c984910bcb659
667,509
def value2Tuple4(v): """Answers a tuple of 4 values. Can be used for colors and rectangles. >>> value2Tuple4(123) (123, 123, 123, 123) >>> value2Tuple4((2,3)) (2, 3, 2, 3) >>> value2Tuple4((2,3,4,5)) (2, 3, 4, 5) """ if not isinstance(v, (list, tuple)): v = [v] if len(v)...
ed8a7c49e0198d2867f4d00fb52a3206b5850b9b
667,513
import math def glow(radius=40): """Overlay a Gaussian blur with given radius (default 40)""" stdDev = math.floor(radius/2) return lambda g: f""" <filter id="glow"> <feGaussianBlur stdDeviation="{stdDev}" /> <feMerge> <feMergeNode /> <feMergeNode in="SourceGraphic" /> </feM...
2b70b0485276049aacae30fb8f06d9bda7d16173
667,521
def parked_vehicles(psvList): """ Get number of successfully parked vehicles. Args: psvList (list): List of parking search vehicle objects Returns: int: Number of parked vehicles """ return sum(1 for psv in psvList if psv.is_parked())
8bfeeb3ceacb8697df76021bc1206d2e4d1a26f5
667,522
def false_discovery_rate(cm): """ false discovery rate (FDR) FDR = FP / (FP + TP) = 1 - PPV """ return cm[0][1] / float(cm[0][1] + cm[1][1])
90316c7648ee9993764eb88f0de12b7fcd1914c7
667,524
def _get_iterator_device(job_name, task_id): """ Returns the iterator device to use """ if job_name != 'learner': return None return '/job:%s/task:%d' % (job_name, task_id)
336b06f0fa15c662765e867afc43b87fdd400ed3
667,526
def unicode_to_c_ustring(string): """Converts a Python unicode string to a C++ u16-string literal. >>> unicode_to_c_ustring(u'b\u00fccher.de') 'u"b\\\\u00fccher.de"' """ result = ['u"'] for c in string: if (ord(c) > 0xffff): escaped = '\\U%08x' % ord(c) elif (ord(c) > 0x7f): escap...
2498487aa424ebf7da1825284be054d2699a5e6e
667,527
import torch def masked_mean(x, m=None, dim=-1): """ mean pooling when there're paddings input: tensor: batch x time x h mask: batch x time output: tensor: batch x h """ if m is None: return torch.mean(x, dim=dim) mask_sum = torch.sum(m, dim=-1) # ba...
0e222b49aac03e12befd4da7bafefe12c9c80980
667,529
def gFont(fontname="Times", fontsize=12, fontface='normal'): """ Returns a font specification to use with the draw text routines fontname must be a string, fontsize and integer fontface is also a string normal, bold or italic; for bold and italic, make fontface "bold italic" """ ret...
96e27bea0838acda94ec64a1bb691e0641632bc5
667,531
def Get_FigWidth_Inches(FigSizeFormat="default"): """ This function gets the figure width in inches for different formats Args: FigSizeFormat: the figure size format according to journal for which the figure is intended values are geomorphology,ESURF, ESPL, EPSL, JGR, big de...
2d07f39256ce628f7e8922421c8d6ec69e9d78f3
667,532
def acrostic(items): """ Take the acrostic of a list of words -- the first letter of each word. """ return ''.join([item[0] for item in items])
c42fd9645d3129f2792d9c3347a6a908126dfa83
667,534
def mean_soft_prediction(y_true, y_score): """Compute the mean predicted probability.""" return y_score.mean()
8bf5af4b8ab9562a015e5a58af3929f0e24167bb
667,535
def _get_file_name_from_uri(uri): """Gets filename from URI Args: uri (str): URI """ return uri.split("/")[-1]
c7b99ef3646c1df4a651c1ad78c08802847ffb31
667,538
def copy_state_dict(state_dict_1, state_dict_2): """Manual copy of state dict. Why ? Because when copying a state dict to another with load_state_dict, the values of weight are copied only when keys are the same in both state_dict, even if strict=False. """ state1_keys = list(state_dict_1.keys()) ...
2c66e3de9c13fc1b668c121dc307d8320679de36
667,540
def get_status_code(status,short = False): """Converts status code phrase to a simplified code if it isn't already simplified. Examples: 'Registered' => 'R' or 'Web Drop' => 'DROP' """ if short: status_codes = {'Registered': 'R','Web Registered': 'R','(Add(ed) to Waitlist)': 'WL', 'Web Drop'...
3b9345e9739afd1a9b08150e60a58ebaf24ebddb
667,541
def is_repo_image(image): """ Checks whether the given image has a name, i.e. is a repository image. This does not imply that it is assigned to an external repository. :param image: Image structure from the Docker Remote API. :type image: dict :return: ``False`` if the only image name and tag i...
75aa72fac2d1a99870b72b59b1f9e8861c82fd79
667,547
def summary_example(field): """Returns an example of a value in the summary of the field """ distribution_keys = ["categories", "counts", "bins", "tag_cloud", "items"] for key in distribution_keys: if key in field["summary"]: return repr(field["summary"][key][0][0])
a18fa2d3dc763a4429ed41d628dc84fce1476acd
667,551
def hp_state_english(raw_table, base_index): """ Convert HP state to English """ value = raw_table[base_index] if value == 0: return "Stop" if value == 1: return "Heating mode" if value == 2: return "Heating mode+comp" if value == 4: return "Cooling mode" if ...
7c589c58912b45e0743b80a8353e0606cf2b623f
667,556
def disjoint(L1, L2): """returns non-zero if L1 and L2 have no common elements""" used = dict([(k, None) for k in L1]) for k in L2: if k in used: return 0 return 1
9d3232769c7224a8acb88045eda15c5855fb5cf2
667,558
def exclude(ex1, ex2): """Return the number on the interval [1,3] that is neither ex1 nor ex2 Parameters ---------- ex1 : int The first number to exclude (1, 2 or 3) ex2 : int The second number to exclude (1, 2 or 3) Returns ------- int The number (1, 2 or 3) no...
136ca08fc0283757e922c27f132c1a59e6de5e1b
667,559
def build_texts_from_keens(keens): """ Collects available text from keens in a list and returns it :param keens: dict of iid: keen_iid :return: texts: dict of iid: list of strings with text collected from each keen. The title of the keen is always in the first position of the list """ texts ...
df446bb50bd98d224316fa90087be87a3db96e08
667,563
def calculate_hounsfield_unit_parameterless(mu): """ Given linear attenuation coefficients the function calculates the corresponding Hounsfield units. :param mu: Attenuation coefficient to determine corresponding Hounsfield unit. :return: Hounsfield unit corresponding to mu """ HU = mu * 65536-...
3785d9b73910e84c5265bc190272adcb4b257327
667,564
def dot(v1, v2): """Returns dot product of v1 and v2 """ assert len(v1) == len(v2), 'Vector dimensions should be equal' return sum(p * q for p, q in zip(v1, v2))
a1339a70bf9007f24bc8bbfbe445f05fa964dd6d
667,565
def set_cell(sudoku, y, x, value): """ Sets the current cell to the input value """ sudoku[y][x] = value return sudoku
1b93384f3cdf38789a190d85b346b0cfb56faed4
667,566
def ema(s, n): """ returns an n period exponential moving average for the time series s s is a list ordered from oldest (index 0) to most recent (index -1) n is an integer returns a numeric array of the exponential moving average """ ema = [] j = 1 #get n sma first and...
84e6981f5b80c487e99b8881bb08761fc76d7504
667,568
def categorize_transcript_recovery(info): """ full --- means that every exon in the tID was covered! fused --- full, but assembled exon match start > 0, meaning likely fusion of overlapped transcripts 5missX --- means that the assembled one is missing beginning X exons 3missY --- means...
535f535886baa8a6e36c1951e8f7a9cceb9f70fa
667,570
def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in order """ _list = [] for item in list_in: if item not in _list: _list.appen...
04308c3a2e8852af0d37dc697cd240bda76c9cc9
667,572
import yaml def read_yaml_file(filepath): """Return contents of a yaml file. Parameters ---------- filepath : string The full path to the yaml file. Returns ------- list of dictionaries The contents of the yaml file where each dictionary corresponds to a line in t...
27111c678ea3640172bcaccff6688f60650a960d
667,573
def _surf70(phi1, phi2, phi3, phi4): """Compute area of a south fire trapeze Parameters ---------- phi1 : float Level-set at south west point phi2 : float Level-set at south east point phi3 : float Level-set at north east point phi4 : float Level-set at north...
c4f166bccd0a290b37469f3f616bd568f90f1259
667,575
def hparams_frames_per_second(hparams): """Compute frames per second as a function of HParams.""" return hparams.sample_rate / hparams.spec_hop_length
a46feb8438363d425ac6f7dcb9d80f11d27a5816
667,578
import json def translate_classes(classes, json_file): """ Convert torch model outputs to human-readable categories Parameters ---------- classes : array-like Numerical class output of the neural network json_file : str Path to json file with category/class mapping Return...
3c6cdcf59802bb5aaba0827aad65643d66f2d53a
667,582
def recall_score(true_entities, pred_entities): """Compute the recall.""" nb_correct = len(true_entities & pred_entities) nb_true = len(true_entities) score = nb_correct / nb_true if nb_true > 0 else 0 return score
7851d329efc0f6e69fb7d7082e9941c2b47c52b1
667,583
from typing import List from typing import Tuple from typing import Optional def has_winner(field: List[List[int]]) -> Tuple[bool, Optional[Tuple[int, int]], Optional[Tuple[int, int]]]: """ Checks game for winning (or tie) positions :param field: playing field matrix :return: Overall answer & position...
442935063a143981fb91056a14adda52c016f066
667,584
def likely_inchi_match(inchi_1, inchi_2, min_agreement=3): """Try to match defective inchi to non-defective ones. Compares inchi parts seperately. Match is found if at least the first 'min_agreement' parts are a good enough match. The main 'defects' this method accounts for are missing '-' in the inchi....
504a92bee20f4c6418434c8475ed9675751eea35
667,586
def masked_status_eq(masked_status): """ Returns a function that matches to the masked status. """ return lambda m: m.get_masked_status() == masked_status
f3df74c6a8c867a0532e1514bb2b7bdbb0e451eb
667,587
def translate_matrix(m, v): """Translates a matrix by (x, y).""" (a, b, c, d, e, f) = m (x, y) = v return (a, b, c, d, x * a + y * c + e, x * b + y * d + f)
761139800c561e4ede3ef1c7d9dc9e495e5d3671
667,593
def credential_exist(cls,site_name): """ method that checks if a credential account exists from the credential list Args: site_name: Site_name to search if it exists Returns: Boolean: True or false depending if the credential exists """ for credential in cls.credentials_list: if ...
4348bec6f9e4ed0fccb68395c73de393c6036f9f
667,594
import math def _compute_output_resolution(input_spatial_resolution, kernel_size, stride, total_padding): """Computes output resolution, given input resolution and layer parameters. Note that this computation is done only over one dimension (eg, x or y). If any of the inputs is N...
2b23132a2933d73317b3d3fe9162f6c1b63ec231
667,595
import re def check_password(passw): """Checks if password is strong (at least 8 characters, both upper and lowercase letters, at least one digit) using regex.""" lowre = re.compile(r'[a-z]+') upre = re.compile(r'[A-Z]+') digre = re.compile(r'\d+') if lowre.search(passw) and upre.search(passw) and digre.searc...
031256586d063fb99c6cf245204da98abbc5a216
667,597
def tag_data(df, tag, var='auto_tag'): """Return data with specified tag.""" return df[df[var].eq(tag)]
36774aa62ff095520576b4babccad963f6cb20d0
667,598
import torch def bool_to_strings(bool_data): """Convert a vector of [True, False, False, True, ...] to '1001...' .""" def conversion(entry): if isinstance(bool_data, torch.Tensor): entry = entry.item() return str(int(entry)) mapping = map(conversion, bool_data) return ''.j...
c31a14c46cab11aae01a73571cde27838cd2caff
667,599
def file_to_list(filename,skip='#'): """ Read the filename and append all the lines that do not start with the skip string, to a list. Args: filename (str): name of the file skip (str): first elements of the skipped lines """ lines = [] with open(filename) as f: for ...
25a63d90eafad59597475b3f0827522f3ea655bf
667,601
def Substarction(matrix_1, matrix_2): # вычитание """ Функция, которая вычитает две матрицы :params matrix_1: матрица, уменьшаемое :params matrix_2: матрица, вычитаемое :return matrix_out: матрица, разность """ matrix_out = [] for i in range(len(matrix_1)): if (len(...
22d2f19026f887b2af547783f0ae4a4d2a8b39c1
667,604
from typing import OrderedDict import json def json_to_ordered_dict(file): """ Reads a timeline.json file output by Tensorflow/libcupti and returns and OrderedDict object :param file: .json file. :return: OrderedDict """ with open(file, mode='r') as f: def _as_ordered_dict(val): ...
5feaaf9c2bbc33bb3826ed599aa3200b4bac07ed
667,606
import torch def invert_pose(T01): """Invert homogeneous matrix as a rigid transformation T^-1 = [R^T | -R^T * t] Parameters ---------- T01: torch.FloatTensor (B44) Input batch of transformation tensors. Returns ---------- T10: torch.FloatTensor (B44) Inverted batc...
d933fb5e9b1b218f42816ed1c686a6fac8f4047b
667,608
def data(reader, chunk=100): """Creates a pandas DataFrame that is a subset of the entire file based on chunk Parameters ---------- reader : pd.DataFrame A pandas.DataFrame, use grab_files.reader chunk : int The number of rows to grab in the first chunk. Future versions ...
1ea39b2ca767e389c7c6bde83b3e9a6324f3d187
667,609
def split_path(path): """Split a path into a list of path components.""" return path.split('/')
d629db063c19d7a4f50eb84755fc71f3114b1e7d
667,610
def join(seq, separator=","): """ Description ---------- Concatenate all values in a sequence into a string separated by the separator value. Parameters ---------- seq : (list or tuple) - sequence of values to concatenate\n separator : any, optional - value to separate the values in the...
fc011f84210d198a650ac10233741508e03f3b77
667,611
def removeNonAsciiChars(str_in): """Remove all non-ascii characters in the string""" if str_in is None: return "" return str_in.encode("ascii", "ignore").decode()
aaacb023d855a35845b4e0ebe443e9d1d9d8e396
667,613
def splitStringIntoChunks( string, length=25 ): """ Split string into chunks of defined size """ if len(string) <= length: return [ string ] else: return [ string[ 0+i : length+i ] \ for i in range( 0, len( string ), length ) ]
ff91557d06927727868fd8b157272286b72f1d5f
667,615
def setify(diff_list): """Take a list of lists and make it a set of tuples.""" s = set() for diff in diff_list: s.add(tuple(diff)) return s
64f0e94c7c6b726b5bb7bae0b269a3c9e8053775
667,616
import codecs def read_only_relations_into_set(inpath): """ Only read the relation of a given relation dataset into a set. Args: inpath (str): Path to relation dataset. Returns: set: Set of dataset relation types. """ relations = set() with codecs.open(inpath, 'rb', 'utf-8') as infile: line = infile.r...
b9ecb376130673ca05d82ee30f1b5cc23e843d30
667,617
def get_uuid(connection): """Retreive UUID from OVN DB connection JSON.""" return connection["_uuid"][1]
30e6c5eb3346d8d6e2eedffdc7115abf205a0ddb
667,621
def parse_fs_statsfile(statsfile): """opens a fs generated stats file and returns a dict of roi keys with [mean, std, nvox], for each roi """ roidict = {} for line in open(statsfile): if line[0] == '#': continue tmp = line.split() roi = tmp[4] mean = e...
f9185fbd00e945171edc45bce18c3ae7034e23dc
667,624
def _prod(op1, op2): """Product of two operators, allowing for one of them to be None.""" if op1 is None or op2 is None: return None else: return op1 * op2
2a1048b995b680b43d67d8f3c237fc42f5d16bc6
667,627
def _format_83(f): """Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError""" if -999.999 < f <...
1b3956b31f417319b403db83ebd152df0fb5c732
667,629
def is_subset(list1, list2): """Returns true if list 1 is a subset of list 2 (assumes neither list has any repeats) """ for item in list1: if not item in list2: return False return True
a1ec2576d04cbf0a79d341e9ff1d802915730757
667,638
import inspect def get_args(frame): """Gets dictionary of arguments and their values for a function Frame should be assigned as follows in the function itself: frame = inspect.currentframe() """ args, _, _, values = inspect.getargvalues(frame) return dict((key, value) for key, value in values.ite...
87bb968522657c762962e58a9c90023e97bc118e
667,640
import re def get_valid_filename(s: str) -> str: """Returns a valid filename given an input. Removes any characters unable to be in a filename""" s = str(s).strip() return re.sub(r'(?u)[^-\w.\[\]()\' ]', '', s)
56d8d70a2d4e5514ad101d820698402c021c65ce
667,642
def single(value, dice): """ Score the dice based on a single value (1-6). """ points = 0 for die in dice: if die == value: points += value return points
03fd02f7f0f642c7aff9ea274630e9880bcd2caa
667,644
def get_descendant_by_address(tree_node, relative_address): """ Get the descendant node with given address relative to the given tree node. A relative address with respect to a tree node is a list of successive children to traverse to reach the desired descendant. For example: [0] is the address o...
7bea0634b015b742a0ef9b2c5e802f81494c6b75
667,645
def getDateTimeByName(entity, name): """Returns the DateTime property with the given name. Args: entity: Instance of a timeline model. name: The name of a specific property in the given timeline model. Returns: The requested DateTime property, or None if there is no such property set. """ if h...
9ec2c8e2868fce85a0ddacecadc35090ba6e185f
667,651
def max_divide(a: int, b: int) -> int: """ Returns a after dividing it with the greatest possible power of b. >>> max_divide(729,3) 1 >>> max_divide(7543,2) 7543 >>> max_divide(486,3) 2 """ while a % b == 0: a //= b return a
0081ae0cd245fc00287af7bc55c27202365f9d10
667,656
def is_magic(name: str) -> bool: """Check magic name.""" name = name.rsplit('.', maxsplit=1)[-1] return name[:2] == name[-2:] == '__'
9328d182b31a5028bb76c4d41b0e5ddc9cf0e5ab
667,658
import re def trim_xml_html_tags(data_str): """ Trim all HTML/XML tags and replace the special "panel" tag with a new line :param data_str: input data string to trim :return: Trimmed string >>> trim_xml_html_tags('') '' >>> trim_xml_html_tags(u'') '' >>> trim_xml_html_tags(u'hello...
a085bc2e94a9fbf112df8e256ab101ee958e1a12
667,667
from pathlib import Path def _transport_data(t): """Return data from "transport = data". Transport 'file' returns a transfer directory (defaulting to '$HOME/.CONSTELLATION/REST'. Transport 'sftp' returns a hostname, directory tuple; the directory defaults to '.CONSTELLATION/REST'.""" ix = t....
324ec3006eade25b75807f9592c71d44fa11d3f7
667,669
def nextf(f, offset=1): """Next token has feature f""" def feature(s, i): i += offset return i < len(s) and f(s, i) return feature
64d1b9ff14df65497681ece4eda17dceefbf5123
667,670
def sint16_to_int(bytes): """ Convert a signed 16-bit integer to integer :param bytes: :return: """ return int.from_bytes(bytes, byteorder='little', signed=True)
4ff2ddb42c7a7f9e8955bf79574cc1979650ef69
667,671
def is_valid_tour(nodes, num_nodes): """Sanity check: tour visits all nodes given. """ return sorted(nodes) == [i for i in range(num_nodes)]
7deb581c09e2d22f67c6abbb611b4a57ad6346d9
667,673
def sorted_by_key(x, i, reverse=False): """For a list of lists/tuples, return list sorted by the ith component of the list/tuple, E.g. Sort on first entry of tuple: > sorted_by_key([(1, 2), (5, 1]), 0) >>> [(1, 2), (5, 1)] Sort on second entry of tuple: > sorted_by_key([(1, 2), (5,...
b0b76316d620edae4451b8521ea2090b1ede9eb7
667,674
import re def exact_match_regex(name): """ Convert string to a regex representing an exact match """ return '^%s$' % re.escape(name or '')
f4cdfe67b19710a970b49f1921a33d219b12ac0f
667,677
def create_attribute_filter(attribute_name: str, values: list) -> dict: """ Create a categorical attribute filter to be used in a trace filter sequence. Args: attribute_name: A string denoting the name of the attribute. values: A list of values to be filtered. R...
a450f3cbc04d45d9f32b2c1b88967c1ff88dbb6a
667,679
def sort_key(attrs, node): """ Sort key for sorting lists of nodes. """ acc = 0 for i in range(len(attrs)): if attrs[i] in node.attrs: acc += 10**i return acc
b431773cf18f4b99a0cc1b747681244172a78c43
667,680
def get_test_response(client, method, params): """ Test the integration connection state :param client: instance of client to communicate with server :param method: Requests method to be used :param params: Parameters for requests :return: Test Response Success or Failure """ ret_val = '...
352f8a4f007049cf9b6e215f695670c53dc69eae
667,684
import re def escape_string(string): """ Escape URL-acceptable regex special-characters. """ return re.sub('([.+*?=^!:${}()[\\]|])', r'\\\1', string)
eccce5505716711bf22cfeee715ebf86b02eb6ff
667,687
import time def utc_mktime(utc_tuple): """Returns number of seconds elapsed since epoch Note that no timezone are taken into consideration. utc tuple must be: (year, month, day, hour, minute, second) """ if len(utc_tuple) == 6: utc_tuple += (0, 0, 0) return time.mktime(utc_tuple) - tim...
c626999ce011720c95e18e6bf785bd701359b259
667,688
def instance_group(group_type, instance_type, instance_count, name=None): """ Construct instance group :param group_type: instance group type :type group_type: ENUM {'Master', 'Core', 'Task'} :param instance_type :type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlar...
b8f42f49a7cc5455cf57ce5c14d523fb85189b8f
667,691
def hasextension(fname): """Check if a filename has an extension""" return fname.find('.')!=-1
1eb832a48e62c690c24265788ce7286ab73a5255
667,694
def get_file_text(file_path): """ Get the text stored in a file in a unique string (without parsing) :param file_path: str :return: str """ try: with open(file_path, 'r') as open_file: lines = open_file.read() except Exception: return list() return lines
f1f769cd3f5fb475baf54c838e057a2bfa71bccb
667,695
def _get_task_file_name(task): """Returns the file name of the compile task. Eg: ${issue}-${patchset}.json""" return '%s-%s-%s.json' % (task['lunch_target'], task['issue'], task['patchset'])
a7df31c6312da0fec18e76099af1020fdbcbe325
667,697
import torch def load_checkpoint(checkpoint_path: str): """ Loads a model checkpoint with the model on CPU and in eval mode. :param checkpoint_path: Path to model checkpoint to load. :return: Returns a tuple with the model, optimizer, epoch number, iteration number, and auc@0.05 of the loaded model. ...
ac275a6a6becf5b2622757fd6aa0a7eb9368ca29
667,699
def getPdbOccupancy(a): """ return pdb atom occupancy""" try: return float(a[60:67]) except: return 0.0
5cceca79bdcd83a83a6e2eb48f13c50b9b020deb
667,700
import codecs def read_voca_file(file_path): """ Read vocabulary file :param file_path: The path of vocabulary file :return: vocabulary list """ vocas = list() with codecs.open(file_path, "r", "utf-8") as voca_file: for each_line in voca_file: vocas.append(each_line.st...
73e5e182093bcd7002feac1c3a7727d2813bc10d
667,702
def MichaelisMenten(S, E0, k, K): """Definition for Michaelis Menten reaction with inputs E0 [mM], k [1/s] and K [mM]""" return (-k*E0*S[0]/(K+S[0]), )
ff1815244f94535581c456b5ea4dcb8e9139ba6d
667,703
def memoprop(f): """ Memoized property. When the property is accessed for the first time, the return value is stored and that value is given on subsequent calls. The memoized value can be cleared by calling 'del prop', where prop is the name of the property. """ fname = f.__name__ ...
31249af7040cb1a05cf8f644d74ea3153b1ca1d6
667,704
from typing import Union def _convert_params_to_array(params: dict) -> Union[dict, list]: """Convert a dictionary to a list of key-value pairs, unpacking list values to their own keys. If none of the values are a list, returns the dictionary untouched. """ if not any(isinstance(v, list) for v in p...
b351395715fa04ecf0148ecd70e0558f772213e1
667,705
import re def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
4bf0772ac808ddc9ad11a777961d67776dacefd9
667,708
def get_docker_job_options(job_options: dict) -> dict: """ Returns Docker-specific job options from general job options. """ keys = ["volumes", "interactive"] return {key: job_options[key] for key in keys if key in job_options}
418ecf5bba4dcf4ae7c7a4e813297b06d5e82bfe
667,710
def last_occurrence_index(l, val, before_index=None): """ Find the last occurrence of some value, before_index will not be included in the possible return value :param l: :param val: value to look for :param before_index: exclusive ending of the range :return: zero-based index """ ...
a2e1ce2ad457f5003ac49c68a416afe5751ef187
667,711
def calc_flux( energy, attenuation=1.0, photon_energy=9, T_lenses=0.586, T_apperture=0.75, T_air=0.39, ): """ "Calculate the photon flux at MID Args: energy (float): pulse energy in micro Joule. attenuation (float, optional): attenuation factor through absorbers. ...
d88809f283ea798fbd3b7ded4bbfa7a0476647be
667,718
def is_quoted(value): """ Return a single or double quote, if a string is wrapped in extra quotes. Otherwise return an empty string. """ ret = "" if ( isinstance(value, str) and value[0] == value[-1] and value.startswith(("'", '"')) ): ret = value[0] retur...
302ec7aa13a2e8c35a5aca5247b64e1eb4cbb5b7
667,722
def progress_bar(completed, total, step=5): """ Function returning a string progress bar. """ percent = int((completed / total) * 100) bar = '[=' arrow_reached = False for t in range(step, 101, step): if arrow_reached: bar += ' ' else: if percent // t != 0: ...
8d27569c0b4befa8b8949f92c7ea88333bbd09ba
667,724
def list_workspaces(client): """Get a list of workspaces the user can access on the active server. Args: client (obj): creopyson Client Returns: list: List of workspaces """ return client._creoson_post("windchill", "list_workspaces", key_data="workspaces")
82de46db12d155945e244e53ab510e392fdc3b5b
667,728
def add_period_cols(df): """ add to given `df` columns with month, day of week and day of month based on index dates Parameters ------------------------------------------------ `df`: pd.DataFrame Returns ------- pd.Dataframe """ df_new = df.copy() d...
0c43263227e363e432de8f662086e1b28bda51ac
667,735