content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def CreateEmptyHubDictionary(input_map): """hub_map_tools.CreateEmptyHubDictionary() INPUTS: - input_map -- a hub map dictionary with teacher or grade name keys, and hub IDs for values OUTPUTS: - output_map -- a new dictionary keyed by unique hub IDs, and having ...
16f5b4bd723fdb73cad2dbbc6179cea747deabbf
628,185
def is_auto(auto): """Function to format auto""" if auto == 'None': return {'parsed' : 'None', 'string': 'N/A'} if auto == "True": formatted = "Yes" else: formatted = "No" return {'parsed' : auto, 'string': formatted}
2a0301d394ce9ed1aa5b027a531d9b810eba405b
628,186
def getMBR(ploygon): """ get the Minimum Bounding Rectangle of the given ploygon :param ploygon: the given polygon :return: the given ploygon's MBR """ left_bottom_x = float('inf') left_bottom_y = float('inf') right_up_x = float('-inf') right_up_y = float('-inf') for plg in ployg...
167977b8f4a6edcfdb1601bedc9a06db83119f73
628,187
def convert_qa_input_dict(infer_dict): """ Input dictionaries in QA can either have ["context", "qas"] (internal format) as keys or ["text", "questions"] (api format). This function converts the latter into the former. It also converts the is_impossible field to answer_type so that NQ and SQuAD dicts have t...
f4feab9c315040094277251e0e110536c6a4a646
628,188
def stats(df): """ This fucntion takes input as data and return total messages, links, media and emojis used in chat """ total_messages = df.shape[0] media_messages = df[df['Message'] == '<Media omitted>'].shape[0] emojis = sum(df['emoji'].str.len()) letter_count = sum(df['Message']...
c7331a062b48da7c56a43a9ae37a9c9b2927938f
628,189
def max_val(t): """ t, tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Returns the maximum int in t or (recursively) in an element of t """ def find_all_int(data): int_list = [] for item in data: if isinstance(item, l...
97102a1024371d1e6f8f959cea53ab309dd323ea
628,190
import re def demarkup_text(text): """ Return text lightly stripped from markup. The whitespaces are collapsed to one space. """ # keep the opening tag name of certain tags that contains these strings # note: <s> are from debian copyright files kept_tags = ( 'lic', 'copy', 'www', ...
de32a0eb5e7acfef92fd4edabe8e0abad4059b66
628,191
def spin_energy(J = -2, mu = 1.1, k = 1, state = [1,-1,1,-1]): """Computes the energy of some spin configuration. Note, all lists should be in the format of a sequential list where 1 is spin up and -1 is spin down :param J: Ferromagnetic constant, defaults to -2 :type J: int or float :p...
cb717dabd238b55f5bf6ff393bb8c1fd5b955c92
628,192
import torch def dice_loss(true, pred, smooth=1e-3): """`pred` and `true` must be of torch.float32. Assuming of shape NxHxWxC.""" inse = torch.sum(pred * true, (0, 1, 2)) l = torch.sum(pred, (0, 1, 2)) r = torch.sum(true, (0, 1, 2)) loss = 1.0 - (2.0 * inse + smooth) / (l + r + smooth) loss = ...
901fefc00e8cca31f97a1c93f980f21552b243db
628,193
def parse_reference(reference): """ Helper function, parses a 'reference' to document name and anchor """ if "#" in reference: docname, anchor = reference.split("#", 1) else: docname = reference anchor = None return docname, anchor
06a9ff5a6c0e211f636093800b80b2e72f8630b4
628,194
def html_figure(fig, specs): """Render a html-format figure""" #Create figure inline with 'js' set to only handlers (no further plot init) fig.value.set_render_options(switched_item_mode="inline", resizable="handlers only", click_to_display=s...
b8367383f4095b95675b97886236ed20a34a290a
628,195
import torch def torch_cat_dicts(L): """Concatenates a list of dictionary of torch tensors L = [{k: v1}, {k: v2}, ...] to {k: [v1; v2]} """ d = {} if L: K = L[0].keys() cat_fns = [torch.hstack if L[0][k].ndim == 0 else torch.cat for k in K] for cat_fn...
4bff7805f09170dcee91f7103bd6a4013db1f4ef
628,196
def _scrape_available_devices(text): """Scrapes the output of the adb devices command into a list :param text: Full output of adb devices command to scrape """ lines = text.split('\n') available_devices = [] for line in lines: words = line.split('\t') if len(words[0]) > 5 and ...
f28d88c7ec16ff9575f4f893260457c79b37fef3
628,197
def get_image_mismatch(image1, image2, size): """Return location of the first mismatch of two images (fast_images)""" for x in range(size[0]): for y in range(size[1]): if image1[x, y] != image2[x, y]: return (x, y, image1[x, y], image2[x, y])
9df81f3e6c8e3ed5ce49f3df170829a030fa7a83
628,198
def partition_games(df, frac=0.7): """ Returns a 2-tuple of arrays containing the indices. The first are the indices in the dataframe that correspond to the first <frac> games of each season. The second are the indices that correspond to the last <1-frac> games of each season. Assumes that the g...
f6d84bcbdc1b651c27976c1241144f1666dbd119
628,199
def max_consecutive_ones(x): # e.g. x= 95 (1101111) """ Steps 1. x & x<<1 --> 1101111 & 1011110 == 1001110 2. x & x<<1 --> 1001110 & 0011100 == 0001100 3. x & x<<1 --> 0001100 & 0011000 == 0001000 4. x & x<<1 --> 0001000 & 0010000 == 0000000 :param x: :return: """...
708ad1b17ed69576faafa265e5713f1edb9eb310
628,200
import pickle def read_universe(path): """read a universe to working directories as pickle Args: path (str): the name of path. Returns: str: filename """ u = pickle.load(open(path, "rb")) return u
45d7af84e46decb775fd860711f7ac66e4ef6f24
628,201
from typing import Optional from typing import Any def safe_ith(arr: Optional[list], ind: int, default: Any = None) -> Optional[Any]: """Performs safe index access. If array is None, returns default.""" if arr is not None: return arr[ind] return default
26b2f6ab8779461efb0400bda8b7c5c35d5f9fea
628,202
def roman_to_arabic(roman): """Convert Roman numerals to Arabic numerals :param roman: :type roman: str :return: :rtype: int """ roman = roman.upper() invalid = ['IIII', 'VV', 'XXXX', 'LL', 'CCCC', 'DD', 'MMMM'] if any(sub in roman for sub in invalid): return None to_ara...
a2a9455e8b713996a0b7ab7fa4b375f44d52dd5e
628,203
def decode_report_item_id(report_id): """Provided with a DOM report item id return the report_item id in the database""" return int(report_id.replace("reportItem", "").split("-")[1])
e3a6304f9bdfa1d9b3238a265b54a3240f9a592c
628,204
import re def cleansym(s): """This function strips off the garbage (everything after and including the first non-letter) in an element name.""" return re.split('[^a-zA-Z]',s)[0]
a5e255e2ca9b05f3aa3960e54efea758f05a4467
628,206
def count_refs_in_mapping( references, mapping ): """Count the number of references in the mapping""" count = 0 for r in references: if r in mapping: count += 1 return count
cde74f6bc17615946caf151b156f3f076a826095
628,207
def to_list(val): """ Method for casting an object into a list if it isn't already a list """ return val if type(val) is list else [val]
c087b7cee3ed633da959d3c77ada38f7a1cc13e8
628,208
import random def random_seq(size, nucleotides="ACTG"): """Generate a random nucleotide sequence of length `size` and composition `nucleotides` Parameters ---------- size : int length of desired sequence nucleotides : str, optional string of nucleotides to use in sequ...
694e5136330db21342fef8ac7de8174cc2245dae
628,209
import sys def gen_location(SubnetLocationFilter=None, HostFilter=None, DeviceFilter=None, InterfaceFilter=None, VrfFilter=None, HostAliasFilter=None, DeviceAliasFilter=None, InterfaceAliasFilter=None): """ helper function constructs json location format ONLY ONE input Parameters ---------- ...
6e41da9f9eba7488bac528f393e79e351000a914
628,210
def compile_output_errors( is_filename_error, filename_error_output, is_error, forecast_error_output ): """ purpose: update locally_validated_files.csv and remove deleted files params: * filepath: Full filepath of the forecast * is_filename_error: Filename != file path (True/False) ...
2c7e469c944adabcbcfa74c7f44acff5b739c68e
628,211
def convert(seconds): """ Convert seconds to (seconds, minutes, hours, remainder_seconds) """ r = seconds s = r % 60 m = (r - s) % (60*60) h = (r - s - m) % (60*60*60) return s, int(m/60), int(h/(60*60)), r - (s + m + h)
bd91005a7677f959d1e59a15505e08facdde2825
628,212
import re def filepath(term, base, schema, service="api"): """ generate file path for given parameters """ main = "-".join([term, base, service, schema]) main = re.sub("^-", "", main) main = re.sub("-*$", "", main) main = re.sub("--", "-", main) return main + ".json"
3524209158b673b54e91e06110398ca3ec355576
628,213
import numpy def fluxToMag(flux): """ Return the magnitudes from flux values Parameters ---------- flux: np.ndarray[float, ndim=N] array of fluxes Returns ------- mag: np.ndarray[float, ndim=N] array of magnitudes """ return -2.5 * numpy.log10(flux)
46bf4c02fa7ab0db9fa4e8731bac3224410d5350
628,214
def dup_mul_term(f, c, i, K): """ Multiply ``f`` by ``c*x**i`` in ``K[x]``. Examples ======== >>> R, x = ring("x", ZZ) >>> R.dmp_mul_term(x**2 - 1, ZZ(3), 2) 3*x**4 - 3*x**2 """ if not c or not f: return [] else: return [cf * c for cf in f] + [K.zero]*i
bfb4c67f26ed6d1929aea4e889cc0fb172d1ef34
628,215
def extract_ids(json_data, id_key): """Creates a list of all IDs retrieved from API :param json_data: :param id_key: :return: """ result_set = set() for data_item in json_data: result_set.add(data_item[id_key]) return list(result_set)
1df0418d83f17ee7842721e5e3112dfa70679fe1
628,216
from typing import List def grading_students(grades: List[int]) -> List[int]: """ >>> grading_students([73, 67, 38, 33]) [75, 67, 40, 33] """ def check_grade(n): if n < 38: return n m = n while m % 5: m += 1 return m if (m - n) < 3 else n ...
20b2cbdd993fca4000619b81a49e59998a6a8968
628,217
def clean_ad_ev_table(df): """ This function cleans the adverse event reporting data- correcting for drug labeling information using CMS database as the 'truth' to correct to """ df['drug_generic_name'] = df['drug_generic_name'].str.lower() df['drug_brand_name'] = df['drug_brand_name'].str.lower() ...
36450dbc8ae87b631c4ff89c45195902ded81c2b
628,218
def diff(value_a, value_b, position_a, position_b): """ Retorna o menor valor entre dois valores """ if not value_a or not value_b: return 101, 0 if value_a < value_b: return position_a, round((value_b - value_a), 2) elif value_a > value_b: return position_b, round((value_a - va...
1c50172f0c23c7c594dc940bd5deaa99e0308bdc
628,219
def parse_paths_as_list(arg): """ Allow singular path string or list of path strings :param arg: This could be a string... or it could be a list of strings! Who knows what could happen? :return: List of strings """ invalid_argument = False if type(arg) is str: arg = [arg] elif ...
c2baad538d729f47daac1230183af01c73345244
628,220
def _is_accepting(graph, state): """accepting state ?""" # no accepting states defined ? if not hasattr(graph.states, 'accepting'): return False return state in graph.states.accepting
c15b9a64da98f9b557a698360bd83d7ff97e58e6
628,222
def beep_boop(): """Builds and returns reply footer "Beep Boop I'm a bot...\"""" s = "\n\n-----\n\n" s += ("*Beep boop I'm a bot. And I live... AGAIN!*\n\n" + "*Sorry about my human letting me go dark for almost a year. What a dingus.*\n\n" "*I should be long-lived and fast to respond ...
8c7783f6142f9a3a70dd790df71d37e6c5917dae
628,223
import turtle def start(): """Initializes the turtle session with pre-defined presets""" turtle.getscreen() turtle.left(90) turtle.pen(fillcolor='#FFCB05', pencolor='#00274C', speed=5) return None
693d2dbde051a4eb89ebff5bb0a2f206a1779ebd
628,224
def pull_pairs(flat): """Return a Iterable of pairs of adjacent items in another Iterable `flat` should be of even size: `len(list(flat)) % 2 == 0` >>> list(pull_pairs([1, 2, 3, 4])) [(1, 2), (3, 4)] """ it = iter(flat) return zip(it, it)
fefb989b406e776d2b8f83057cbabfa4171b51b2
628,225
import time def get_time_millis(): """Returns current system time in milliseconds""" return int(round(time.time()*1000))
4b04f8f2a10898d0e4370525b19be9971292940e
628,226
def sizes_execpt(inp, dim): """return all except the specified dimension indices""" return [s for d, s in enumerate(inp.shape) if d != dim]
936ef2366eaa6bc32671e1c541a885cc44f833b1
628,227
def _find_neighborhoods_ids(input_list, neighborhoods_df): """ Read in a list of names of neighborhood names. Returns a list of neighbhorhood ids Args: input_list: a list containing the names of the neighborhoods in the treatment group. neighborhoods_df: a dataframe containi...
71ec994ce2e4fe28ec20a1e5604eea4159f8c172
628,228
def slowest_speed(speed_list): """ Compute the derived speed by finding the slowest object in the speed_list. :param speed_list: A list of objects with a speed_mb attribute. :returns: Speed as an integer. """ speed_mb = 0 if speed_list: for obj in speed_list: if not spee...
d7021efbc4d5d897233cf1e1948a14e4a6b73596
628,229
def world2pixel(x,y,w,h,bbox): """Converts world coordinates to image pixel coordinates""" # Bounding box of the map minx,miny,maxx,maxy=bbox # world x distance xdist=maxx-minx # world y distance ydist=maxy-miny # scaling factors for x,y xratio = w/xdist yratio = h/ydist # Calculate x,y pixel co...
381c053cec430f4eeb58a5fdef1a7978ec104cbe
628,230
def transform_dashed_name(name): """Add or remove unicode text separators & transformations for hyphens.""" if not name: return if '-' in name: name = '__ಠ__' + name.replace('-', '__u2010') + '__ಠ__' elif '__u2010' in name: name = name.replace('__u2010', '-').strip('__ಠ__') r...
54e0c19b0b6ab2d8eeb04cdafd0d1eccfebc8e5d
628,231
def dominating_set(G): """ Finds a greedy approximation for a minimal vertex cover of a specified graph. At each iteration, the algorithm picks the vertex with the highest degree and adds it to the cover, until all edges are covered. :param G: networkx graph :return: vertex cover as a list of ...
b1e446d2dd338d6e84a98543b6de33c6c86be836
628,232
def convert_iob_to_iobes(iob_tags): """Converts a sequence of IOB tags into IOBES tags.""" iobes_tags = [] # check each tag and its following one. A None object is appended # to the end of the list for tag, next_tag in zip(iob_tags, iob_tags[1:] + [None]): if tag == 'O': io...
edd195dc30650542e3542a270b47ee4d6bcdcbb8
628,233
def _steps_to_run(steps_in_current_epoch, steps_per_epoch, steps_per_loop): """Calculates steps to run on device.""" if steps_per_loop <= 0: raise ValueError('steps_per_loop should be positive integer.') if steps_per_loop == 1: return steps_per_loop return min(steps_per_loop, steps_per_e...
53f17a2f8fef1574ce997ef160fc01de627a61bb
628,234
def getTitlePerks() -> list: """ Get the list of perks to look for in the job description :return: list - list of perks """ perkList = ["Why you'll like working here", 'Benefits', "The top five reasons our team members joined us (according to them)", "What’s in it fo...
6dae31ce2ed55fab41ad495067ff0cdca4372bb0
628,237
import operator def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): ...
465684f0437416470b5544b94d5bc7bb4989e958
628,238
def make_sirius_json(parameters, structure, kpoints, magnetization): """ DEPRECATED Keyword Arguments: structure -- structure pseudos -- dictionary of UpfData """ raise Exception('deprecated') sirius_cell, sirius_pos = read_structure(structure, magnetization.get_dict()) sirius_json...
ad132560470c7952fa2cf98965cb0d5dd90c89ab
628,239
def prid(obj, show_cls=False): """Get the id of an object as a hex string, optionally with its class/type.""" if obj is None: s = 'None' else: s = hex(id(obj)) if show_cls: s += str(type(obj)) return s
12b00c07c075b0b9ff4ad7f1d0a2deabb1fa2af3
628,240
import re import fnmatch import sys def IsAuthorInFile(email, name, filename): """Return whether we find the name/email in the authors filename""" # Organization emails have emails listed as <*@domain.com>. This matches those # patterns. email_pattern_regex = re.compile(r'.*<([^>]+)>') with open(filename, ...
681cbcb7230ec010638da1167bd7ab0eb5980a88
628,241
def extract_seq_pseudo_label_from_submission(submission_df, rna_seq_id, pred_cols=None): """ Each Kaggle's OpenVaccine submission csv file can be used to make a pseudo label. OpenVaccine submission format is explained here: https://www.kaggle.com/c/stanford-covid-vaccine/overview/evaluation Exampl...
72ff4c68bf45d5e5a4a4cfd5f2d1c6146b248858
628,242
def calculate_point_triplet_orientation(coordinate_1, coordinate_2, coordinate_3): """ Returns a value that represents the negative sine of the angle created by connecting coordinate_1 to coordinate_2 to coordinate_3. If this connection occurs in a clockwise fashion the value will be negative, counterc...
b478c38af7ba37a84dc4ecff1af81a26f911463c
628,243
import collections def sapt_psivars(): """Returns dictionary of PsiVariable definitions. """ pv1 = collections.OrderedDict() pv1['SAPT EXCHSCAL1'] = {'func': lambda x: 1.0 if x[0] < 1.0e-5 else x[0] / x[1], 'args': ['SAPT EXCH10 ENERGY', 'SAPT EXCH10(S^2) ENERGY']} # spe...
308992bd180c619bc8a29c622009215bb533c136
628,244
from typing import Union from typing import List def create_column_statement(name: str, data_type: str, nullable: bool, constraints: Union[List, None] = None, **kwargs) -> str: """Function for generatin...
0b1b199f7f700a73ab69f98745e57ecf3b39a345
628,245
def _MergeProguardConfigs(proguard_configs): """Merging the given proguard config files and returns them as a string.""" ret = [] for config in proguard_configs: ret.append('# FROM: {}'.format(config)) with open(config) as f: ret.append(f.read()) return '\n'.join(ret)
af65bdb4b5063b47d8876862a544fcfefd27ec37
628,246
def _header2fn(hdr): """Get the first file name from a mime header block. Helper fns so fetchfile less prolix """ for h in hdr.headers: if h.startswith('Content-Disposition') and ('filename' in h): s = h[h.find('filename'):].split('"') if len(s) < 3: retu...
14dd63561fa6c826c740e7667b63196ba34f8067
628,247
import os def _def_copy_pred(srcpath, destpath): """ Default file copying predicate. Does not overwrite newer files. :param srcpath: Source path. :param destpath: Destination path. :return: True if the source file is newer than the destination file. """ if not os.path.exists(destpath): ...
1438e53440ae6847f0dcb4219d173e1ac11a523d
628,248
import os import glob def list_filter_files(dir_path, file_filter): """Function: list_filter_files Description: Return a list of files from a directory folder with a file filter that will contain a file name or wildcard expansion file name. Arguments: (input) dir_path -> Directory pat...
64b00af0577464c828b600190bb7cc193011aa5d
628,249
def get_warp(transforms): # grab the warp from the forward transforms """Return the transform1Warp.nii.gz file""" for name in transforms: if 'transform1Warp.nii.gz' in name: return name raise ValueError('transform1Warp.nii.gz not found')
49fa8f1812f87ac810cbee9cbd698d34de2c6bef
628,250
def scoped_logger_name(module_name: str, config_name: str = "maestral") -> str: """ Returns a logger name for the module ``module_name``, scoped to the given config. :param module_name: Module name. :param config_name: Config name. :returns: Scoped logger name. """ if config_name == "maest...
c9d3add60b9e01956692b4c3e9ce4efff474503b
628,251
import hashlib def hash_string(input_value: str, num_length: int = 8, method='sha256') -> str: """ hash str function input to number with default method, SHA256 algorithm. """ return str(int(getattr(hashlib, method)(input_value.encode('utf-8')).hexdigest(), 16) % 10 ** num_length)
ffe563331f6e5a04fbf407a54de37e30218a20af
628,252
import os def compare_by_creation_time(file1, file2): """ compare two files by creation time. if creation time equals, comparing modification time. """ if not os.path.exists(file1) or not os.path.exists(file2): return 0 res = int((os.stat(file1).st_ctime - os.stat(file2).st_ctime) ...
abe4d75b456d9dbce2cd84a83202bf8d25aebf48
628,254
def make_mocked_isfile(configuration): """ Creates mocked isfile function that returns values according the given configuration. The created function raises :class:`ValueError` should the unit under test try to "isfile" a path that is not present in the configuration. One global mocked function wi...
70eedaa9dfab1394782d51683bc4b8f050dab902
628,255
def gcd(a, b): """Возвращает наибольший общий делитель для A и B""" while b != 0: reminder = int(a % b) a = b b = reminder return a
4f0ffb5739748ae2a408a600d6ba232f4cb13015
628,256
def op_help(oper, left_op, right_op): """Helper method does math on operands and returns them""" if oper == '+': return left_op + right_op elif oper == '-': return left_op - right_op elif oper == '*': return left_op * right_op else: return left_op / right_op
5f52ea03cc05679fd2882170e39babb864094150
628,257
def render(environment, filename, context): """Populate a template file with data rendered from the context. @param filename: A C{str} with the path to a Jinja2 template. @param context: A C{dict} with all the data needed by the template. """ template = environment.get_template(filename) render...
9e0bb4e3592d06032dee9138feafae62a1c1f6cd
628,258
import pickle def serialize(x): """Return a pickled object.""" return pickle.dumps(x)
c3debbc8df9b457879a784344ab7885b95b9ecd3
628,259
def preload(pytac_lat): """Load the elements onto an 'elems' object's attributes by family so that groups of elements of the same family can be more easily accessed, e.g. 'elems.bpm' will return a list of all the BPMs in the lattice. As a special case 'elems.all' will return all the elements in the latt...
b65c6950442bf3afd55f1b3cc5c67529170c3b69
628,260
import collections def knightProbability(self, N, K, r, c): """ BFS, use a set to track the nodes in a tree remaining in the board in each step Time: O(8 * N ^ 2 * K) Space: O(N ^ 2) """ q = {(r, c): 1} level = 0 directions = {(dx, dy) for dx in (-2, -1, 1, 2) for dy ...
5d91cf50413252982233a6501c7e97221134d4eb
628,261
def dsigmoid(y): """Derivative function of the function represented in :py:func:`sigmoid`. * If :math:`y = tanh(x)`, then :math:`Dy = 1 - y^2`, * if :math:`y = s(x)`, then :math:`Ds = y - y^2`. * There are infinite sigmoid functions. Just put here the derivative of the ``sigmoid`` fun...
0c11e341a5d6da006163ddc2e353f46ded0a0a50
628,262
import logging import os def DownloadFASTQs(dfu, fastq_ref_list, output_dir): """ dfu: DataFileUtil Object fastq_ref_list: (list<s>) list of refs 'A/B/C' A,B,C are integers output_dir: (s) Path to scratch directory or tmp_dir """ fastq_fp_l = [] for i in range(len(fastq_ref_list)): ...
7924b4aa26baa94db0e481787da987bc12f02749
628,263
import re def has_been_rewritten(code): """Return True if the code has been rewritten by rewrite_lnotab already. >>> def fun(): ... pass >>> has_been_rewritten(fun.func_code) False >>> rewrite_function(fun) >>> has_been_rewritten(fun.func_code) True """ return re.match(r"\...
12d8d27e392b376dec8b1a28a8bcd8c21e2a289c
628,264
def pairs(k, arr): """ Runtime: O(n * log n) After sorting, we can iterate through the list from both sides in O(n) to find the pairs. """ arr.sort() if len(arr) < 2: return [] pairs = [] start = 0 end = len(arr)-1 while (start < end): n1 = arr[start] ...
65ef93f5fdbe63215e4130a7696208ad52fe95f0
628,265
def list_to_csv(parlist, sep=", "): """Returns a csv string with elements from a list.""" result_str = "" for par in parlist: result_str += str(par) + sep return result_str[:-len(sep)]
86b816790f982f9133661a8c4e775a7e13209aed
628,266
def normalize_pack_version(version): """ Normalize old, pre StackStorm v2.1 non valid semver version string (e.g. 0.2) to a valid semver version string (0.2.0). :rtype: ``str`` """ version = str(version) version_seperator_count = version.count('.') if version_seperator_count == 1: ...
32f241ac1c5098ae526daaa5686ccc5fbc021a6a
628,267
import importlib def load_command_class(name): """ Given a command name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = importlib.import_module(f's2e_env.commands.{name}') return module.Comman...
43359285196ce8ab8f68423fea0429df341feaae
628,268
import random def generate_random_rounds(): """ Generate a random number of rounds of iterations. This should not be considered a secure random number, just number of iterations, its no secret. """ rounds = random.randint(100000, 200000) return rounds
085aabc2e9248b3f248707bbce29c6a5e5091f2f
628,271
def build_datasets_by_publisher_query() -> str: """Build query to count datasets grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?dataset) AS ?count) FROM <https://datasets.fellesdatakatalog.digdir.n...
6c1dfdbc3bad0da05d12a0aecfa3118ff6d8558a
628,273
def find_all_plot_names(plot_name, column_names): """Returns whether or not all the plot names are found in the list of column names. Args: plot_name(str or list): the plot column name to look for, or an array of plot column names column_names(list): a list of names to look through for ma...
a3ef2eaa2f9a4a7949581ffcaa85d2e978f0410c
628,275
import numpy def find_nearest(array,value): """ http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """ idx = (numpy.abs(array-value)).argmin() return idx,array[idx]
11af51688f9a668b47023a6a65a6257545ac4638
628,276
def swap_values(x: int, y: int) -> tuple: """ Returns swap values """ temp = x x = y y = temp return x, y
a224f97b3d71b2c6f35fc7ec9c560c71e8d89b23
628,277
def update_list(content, new_values): """Update a list with additional or new values.""" new_content = content[:] if content else [] new_values = [x.strip() for x in new_values.split(",")] if isinstance(new_values, str) else new_values or [] for value in new_values: if value == "-": ...
553b6b134fd57827c52df4e0ac80acb321530d24
628,278
def is_true_sequence(values): """Are card values in sequence?""" for i, j in zip(values, values[1:]): if i - 1 != j: return False return True
8690299cf990b7e01092a88aa361b2151eb43387
628,280
def cli(ctx, organism_id, suppress_output=False): """Delete an organism Output: A list of all remaining organisms """ return ctx.gi.organisms.delete_organism(organism_id, suppress_output=suppress_output)
558fa918e00e1b2a431c25a6a5624b494aad7957
628,281
def checkColumns(board: list) -> bool: """ Returns True if there is no repeating numbers in the columns. """ for i in range(len(board[0])): column = [] for line in board: if line[i].isnumeric(): column.append(line[i]) if len(column) != len(set(column))...
8f4c974fef412f6a791cf7b525ddb15edea64c77
628,282
def scattering3d(x, filters, rotation_covariant, L, J, max_order, backend, averaging): """ The forward pass of 3D solid harmonic scattering Parameters ---------- input_array: torch tensor input of size (batchsize, M, N, O) Returns ------- output: tuple | torch tensor if m...
3af071147358321bebe947a69d23657984bfe86c
628,283
def f(z): """ A function of metallicity Z, which we will set as the yield of Sr from core-collapse supernovae. """ return 3.5e-8 * (z / 0.014)
c86494dd24a4b3525ab0357eff538d66b169700c
628,285
def load_manual_evaluation_file(file_path, avoid_file_path): """ Load normal head, tail, rel files, divide them into dicts where the key is unique head rel pair and the values are the targets in the evaluation set. We also skip all tail entities that does not exist in the training file....
06687fe8543ee7fd8692ad9ee29d2d7cca118be4
628,287
from typing import Dict from typing import Any import inspect def get_argument_values_of_current_func() -> Dict[str, Any]: """Get arguments of the function this is called in. Returns: Dict[str, Any]: Dictionary containing named arguments """ frame = inspect.stack()[1].frame args, _, _, va...
854af0fcf362af3c64375e50f1a742e391d7df41
628,288
from typing import Optional from typing import List from typing import Tuple import gzip def decompress(comp: bytes) -> Optional[List[Tuple[str, str]]]: """Compress into pairs""" uncomp = gzip.decompress(comp) # Split by 0 byte fields = uncomp.split(sep=bytes(1)) # That gives us a final empty fiel...
4dd219c6b021e2f00b1acc5ce9c44e66b331f40c
628,289
import base64 import hashlib def create_base64_checksum(http_method: str, raw_url: str, raw_header: str, request_body: str) -> str: """Create a base64 encoded hash string for an Apex JWT token""" string_to_hash = http_method.upper() + "|" + raw_url.lower() + "|" + raw_header + "|" + request_body base64_ha...
3044fb876bce734b6a9dbcbb6c11c13cb68d5626
628,291
import subprocess import logging def call_acme_tiny(args): # pragma: no cover """Low-level call to acme-tiny. Args: args: (list of string) CLI arguments to pass to acme-tiny Returns: certificate (bytes) or None. """ p = subprocess.Popen(['acme-tiny'] + args, stdout=subproces...
b7de9470af3b3213ca6ddcdf7010b3156d1c1a36
628,292
def helper(x): """old version of date format helper, run in py2 and old pandas """ splited_list = list(map(int, x.strip('[').strip(']').split(','))) d = {} for counter, value in enumerate(splited_list): k = str(len(list(splited_list)))+"-"+str(counter) d[k] = int(value) retur...
744dfb074fe0f15938b6a91b0e40d7fe74f3f32d
628,293
import inspect import textwrap def appender(defaultdocs, passed_to=None): """Decorator for appending commonly used parameter definitions. Useful in cases where functions repeatedly use the same parameters. (But where a class implementation is not appropriate.) `defaultdocs` -> dict, format as shown...
22eb66fe552af0e8680b989e182d3fe6d45e3a91
628,295
def GetMessageFromQueue(session, queueurl, delete_after_receive=False): """Get message from the queue to process :param session: Session to use for AWS access :type session: boto3.session.Session :param queueurl: URL of the queue from which to receive messages :type queueurl: str :param delete_after_receiv...
04d28777329fd6ca85936e827c41b46b0c444b5f
628,296
def pretty_alloc_sizes(sizes): """Prettifies allocatation sizes""" min_size = sizes[0] max_size = min_size for size in sizes: if size < min_size: min_size = size elif size > max_size: max_size = size if min_size == max_size: return 'all {} bytes'.for...
3b243e20a1c93d44df94b144a253df6675287ca2
628,299
def remote_env_fun(trainer, env_function): """ Create a dictionary with the following mapping: result[env_wrapper.env_id] = env_function(env) where each entry in the dictionary comes from one of the active envs in the trainer. env_function must be a function that takes an environment as its sing...
f240d8f5ad9f58dfab1c4da6e87fcd3cc1999181
628,300