content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def hidden_answer(answer): """Return the answer where we replace alphabetic letters by underscore""" answer_hidden = re.sub('\w', '_', answer) return answer_hidden
62405d486ab2060dddf4d16f7e2bf4003bf35ead
685,205
import os import json def read_data_description(path): """Read data description from disk, S3 path, or URL. Args: path (str): Location on disk, S3 path, or URL to read `data_description.json`. Returns: description (dict) : Description of :class:`.EntitySet`. """ path = os.path.a...
74e8821352dc5b3bd851b792e91d7fc02bf43c03
685,206
def enlarge(n): """ Parma n is a number (either float or integer is OK) Function will enlarge the number """ return n * 100
18ef735b9e3b3fa1ab1a1b3aa0d6655371234bf9
685,207
def sstate_get_manifest_filename(task, d): """ Return the sstate manifest file path for a particular task. Also returns the datastore that can be used to query related variables. """ d2 = d.createCopy() extrainf = d.getVarFlag("do_" + task, 'stamp-extra-info') if extrainf: d2.setVar(...
274c60301f94e0d98cee18b03a6aeecbfcf371fd
685,208
from numpy import ravel,column_stack def lmfit_summary(basename,N,out): """Returns tab-separated header_str and data_str. The header_str spans two rows with the first row specifiying the fit variable names and the second row identifying (value,stderr) pairs. The first three columns in the data_str are...
5ffc632c67fc872ebb32e45938d501bf1e8dbfa5
685,209
def wrappers_mul(arr): """Some function that performs an inplace operation on the input. Accepts kwargs""" arr *= 25 return arr
75b3a4c4246a0e2c60e4bb28e7275f6b61b39af8
685,210
def get_nodes(edges): """ Get nodes from list of edges. Parameters ---------- edges : list List of tuples (source page, end page). Returns ------- list nodes, not unique """ nodes = [] for edge in edges: nodes += list(edge) return nodes
d4c713fb2aed97fe6629c3a6e39b6fed2cf41213
685,211
def t2n(torch_tensor): """ Convert torch.tensor to np.ndarray. """ return torch_tensor.cpu().detach().numpy()
c48d8a715acfd832bfbf5a86518d33e20c30cd15
685,212
import re def get_source(view): """ return the language used in current caret or selection location """ scope_name = view.scope_name( view.sel()[0].begin()) # ex: 'source.python meta.function-call.python ' source = re.split(' ', scope_name)[0] # ex: 'source.python' return source
e7f64a59762a1fa93a6fb35ff800438088bd1c82
685,213
import torch def build_vertices(corners1:torch.Tensor, corners2:torch.Tensor, c1_in_2:torch.Tensor, c2_in_1:torch.Tensor, inters:torch.Tensor, mask_inter:torch.Tensor): """find vertices of intersection area Args: corners1 (torch.Tensor): (B, N, 4, 2) corners2...
2aa4e7a4207841021831181e611c57fa63a21ef6
685,214
import subprocess import json def query_artifacts(api_token, user, project, branch, filter): """Queries CircleCI for a list of build artifacts. All parameters are strings. The returned value is a JSON object with the following attributes: "path": Path to the artifact in the project, relative to the working...
8b99bb2e786fd5ef1495bb8abb47dafae83e9e89
685,215
from typing import Optional import os import argparse def validate_file(file_path: str) -> Optional[str]: """ Validate that the file exists :param file_path: file path :return: raise error if file does not exist or return file path """ if not os.path.isfile(file_path): raise argparse.A...
419671c99e92674bc4cca5574b47ad53ee5a84ce
685,217
import numpy as np def create_events(raw, epoch_length): """Create events to split raw into epochs.""" file_length = raw.n_times first_samp = raw.first_samp sfreq = raw.info['sfreq'] n_samp_in_epoch = int(epoch_length * sfreq) n_epochs = int(file_length // n_samp_in_epoch) events = [] ...
22df85dda9d575819e729c28afee1174c7010490
685,218
def odict_to_attributes_gff(attributes): """ Parse the GFF attribute column and return a dict """ if attributes: atts = [] for k, v in attributes.items(): atts.append('{}={}'.format(k, v)) temp_atts = ";".join(atts) return temp_atts.rstrip() return '.'
1b0b06d5890e9b18516f42f5cb402566667c719e
685,219
def _get_ips(ips_as_string): """Returns viable v4 and v6 IPs from a space separated string.""" ips = ips_as_string.split(" ")[1:] # skip the header ips_v4, ips_v6 = [], [] # There is no guarantee if all the IPs are valid and sorted by type. for ip in ips: if not ip: continue ...
7f1c88f3006faab44680af39c9e87661a35e4462
685,220
import torch def greedy_coalescing(probs, thresholds, k=1): """ params- probs: [n x t]- tensor, prob score for each time (t times) for each instance thresholds: [n x 1]- threshold for each instance k: number of intervals to be returned for each returns- (start, end), where start and end ar...
e5f10e1364c7a500cfd8231a2ee008a52fd0a01c
685,221
def spotifython_hash(obj): """ Hash function to override the builtin one. Note: obj must implement spotify_id() By using this, we can have 2 different objects that represent the same thing have the same hash code. For example, if you get the same track from 2 different calls to User.top, they shou...
1c705af9e0b70a15ba0d7af5783deee90a8012fb
685,222
from typing import Union from typing import Tuple def doum_conveter(word: str) -> Union[Tuple[str, str], bool]: """ ๋‘์Œ ๋ฒ•์น™ ๊ตฌํ˜„ :param word: ๋‹จ์–ด :returns: tuple or bool """ doum = { "๋ผ": "๋‚˜", "๋ฝ": "๋‚™", "๋ž€": "๋‚œ", "๋ž„": "๋‚ ", "๋žŒ": "๋‚จ", "๋ž": "๋‚ฉ", ...
5c0673965459cc66a31950aa138d6e87404f00f6
685,223
def teacher_comment(test_score, student_name=''): """ This function takes an <int> test score and returns a teacher comment based on the score. Returns a string teacher comment """ if test_score > 90: return 'Great Job ' + student_name elif test_score > 80: return 'Pretty go...
6a14470ea24d204d717143791103cb40b56bb0e9
685,224
def decimal_entity_encode(encvalue): """ Convert input to a decimal entity. Example Format: &#72;&#101;&#108;&#108;&#111;&#32;&#87;&#111;&#114;&#108;&#100; """ decvalue = "" for item in encvalue: decvalue += "&#" + str(ord(item)) +";" return(decvalue)
4b78b4d4d1e9fca9c4de96e72c8e6c0519de0b83
685,225
def wildcard_target_ports(jobs): """Fetch list of wildcard target ports from a job list. Args: jobs: list of jobs to search for wildcard target ports. Returns: possibly empty list of wildcard target ports. """ ports = [] for job in jobs: for static_config in job["static...
51ddcfeb39715e95ee0ad516d78cb315d821e961
685,226
import re def _clean_value(value): # pylint: disable=R0915 """ Clean a value from the spreadsheet. """ value = str(value).strip() value = value.replace('\r\n', '\n') value = value.replace('\r', '\n') value = value.replace('{', '[bi]') value = value.replace('}', '[/bi]') value = value....
95df8715d1c1149e8f4c320a074ae1061c3b90dd
685,228
import sys import pkg_resources def parse_requirements(filename): """ load requirements from a pip requirements file. (replacing from pip.req import parse_requirements)""" lineiter = (line.strip() for line in open(filename)) reqs = [line for line in lineiter if line and not line.startswith("#")] if sy...
15f462122570c555686f7273173f8dc21c33de9a
685,229
def rmFromList(lst, thing=''): """Removes all values matching thing from a list""" lst = list(lst) for i in range(len(lst)-1, -1, -1): if lst[i] == thing: del lst[i] return lst
726cfd6a1dca73c66fb2f2bbd8767795bd0290fc
685,230
import json import six import base64 def _base64_encode(dictionary): """Returns base64(json(dictionary)). :param dictionary: dict to encode :type dictionary: dict :returns: base64 encoding :rtype: str """ json_str = json.dumps(dictionary, sort_keys=True) str_bytes = six.b(json_str) ...
dbd5e5bcfecb365ba0009f6e4e3f9ddaa8148bf1
685,231
def to_bytes(string): """Convert string to bytes type.""" if isinstance(string, str): string = string.encode('utf-8') return string
3432641862dbe5d45aa301f1f79caee0562fd867
685,232
def gen_I(n): """Returns an nxn identity matrix.""" return [[min(x // y, y // x) for x in range(1, n + 1)] for y in range(1, n + 1)]
4a94a879bba786e3ad5b541dd5721e735cdb4ce5
685,233
import os def resolve_path(engine, filename): """ Resolves a path relative to the Kurfile. """ filename = os.path.expanduser(os.path.expandvars(filename)) kurfile = engine._scope.get('filename') if kurfile: filename = os.path.join( os.path.dirname(kurfile), filename ) return os.path.abspath(filename...
8df034f57d78087820a1267284f59dbb5c62e82e
685,234
def check_in(position, info_pos_line_pairs): """ Check if position corresponds to the starting position of a pair in info_pos_line_pairs (return pair if found, empty list otherwise) :param position: list :param info_pos_line_pairs: list of lists :return: list """ # pos_pair form: [info,...
26231ec22468e6fccd14d55b30b818a8c1773b78
685,235
import re def substitute_and_count(this, that, var, replace=True, count=0): """Perform a re substitute, but also count the # of matches""" (result, ctr) = re.subn(this, that, var, count=count) if not replace: return (var, result) return (result, ctr)
f6f1323287d05fb8a01b5ee73269fe8f2a053a3d
685,236
from typing import Optional from typing import Tuple import re def get_stems(word: str) -> Optional[Tuple[str, str]]: """Split the word by the first vowel""" pattern = '([^aeiou]*?)([aeoiu].*)' return re.findall(pattern, word.lower())[0]
aec056f7ee11bd9ba92c0e329615a1e07efb2d78
685,237
def is_valid(x, y, grid, x_max, y_max): """Check the bounds and free space in the map""" if 0 <= x < x_max and 0 <= y < y_max: return grid[x][y] == 0 return False
48edd43ec518d7e3b0e9161123977d87bd8f6a09
685,238
def derive_sentiment_message_type(compound): """ Derives the type of the message based status of the sentiment :param compound :return: type of the message """ if compound > 0: return "success" elif compound == 0: return "info" else: return "error"
05df1d9485d06e274293e14ab2c0bb2a2bba6589
685,239
import subprocess def check_output(*args): """Run a command on the operation system. :type args: tuple :param args: Arguments to pass to ``subprocess.check_output``. :rtype: str :returns: The raw STDOUT from the command (converted from bytes if necessary). """ cmd_output = ...
13f9f87389a72ea507f39e6080d13a17d72dd745
685,240
import os def __read_ssh_key_from_file(path: str) -> str: """ Read the content of the given file """ with open(os.path.expanduser(path), "r", encoding="UTF-8") as content_file: content = content_file.read() return content
d14e7b93574933915befa17ae179d16c30694792
685,241
def decode(data): """ Normalize a "compressed" dictionary with special 'map' entry. This format looks like a way to reduce bandwidth by avoiding repeated key strings. Maybe it's a JSON standard with a built-in method to decode it? But since I'm REST illiterate, we decode it manually! For examp...
c952e08e300dbf0e9574a1076e3342ce0c3939f6
685,242
import torch def trainGenerator(netG, netD, optimiserG, inputs, targets, loss_func, device, lambdapar): """ This function trains the generator :param netG: The generator network :param netD: The discriminator network :param optimiserG: The optimiser for the generator :param inputs:...
a14bd4b8749f765966fb7b8601c09dbcf89eda67
685,243
from typing import Tuple from typing import List def get_moves( group_position: Tuple[int, int], size: int, neighbors: List[Tuple[int, int]] ): """ :param group_position: :param size: :param neighbors: :return: A list of move tuples from group_position to each neighbor """ return [(*gr...
1eb065f168a01447a2fe4184cc3dee60f0d5a25e
685,244
def exc_msg_str(exception, default="") -> str: """ Extract the exception's message, or its str representation, or the default message, in order of priority. """ try: msg = exception.args[0] except (AttributeError, IndexError): msg = None if not msg or not isinstance(msg, str...
db0b8fd6c2ad8aea31a3ae083e20ff6d5113195d
685,245
def hash_djb2(input_str: str) -> int: """Source: http://www.cse.yorku.ca/~oz/hash.html""" result = 5381 for x in input_str: result = ((result << 5) + result) + ord(x) return result & 0xFFFFFFFF
656acc7697c1257d14e0afc6888a723bb3a66265
685,246
def get(req, api): """ Go to your browser and open `localhost:8888/hello/world` It should display a page with the message `HELLO WORLD!!! Success on local, in method get!` Input: message: string Output: string """ message = req.query['message'] result = req.h...
f9d1e860fdcab478b26f34cbc972bf55fbb5a96c
685,247
import numpy def sigmoid(x): """ Sigmoid function of x, aka 1/(1+exp(-x)). Parameters ---------- x: a real number Returns ------- res: a real number The result of sigmoid function """ return 1 / (1 + numpy.exp(-x))
1c6cc9f4f117b1968fdcfdbe244fdacf4b83588e
685,248
import os def cuwb_data_csv(): """ 1 minute of CUWB data 6 People 3 w/o acceleration data 5 Trays :return: """ return os.path.dirname(os.path.realpath(__file__)) + '/fixtures/uwb.csv'
1c4147dfa488aff9c6e4a44a4e24d3993ea8412c
685,249
def make_album(artist, title): """Build a dictionary containing information about an album.""" album_dictionary = {'artist' : artist.title(), 'title' : title.title()} return album_dictionary
e717d11f8be8ae65e469c80225ad61a08b30cfcc
685,250
def run(args): """This function does absolutely nothing. It is called to pre-warm a set of functions so that we can hide the long cold-start time Args: args: unused Returns: dict: empty dict """ return {}
342159cdad75493ee5ddeaeee9a291f0e10c8799
685,251
def average_list(l1, l2): """Return the average of two lists""" return [(i1 + i2) / 2 for i1, i2 in zip(l1, l2)]
ce93cdeeacd8de5eb1d752300c738212ed84bd25
685,252
import re import argparse def regex_arg(s): """ Compile regex pattern from argparse argument """ r = re.compile(s) if r == None: raise argparse.ArgumentTypeError return r
f90c0965628cef75cd978b7f08ad8144212b00ad
685,253
import hashlib def generate_file_name(instance_str): """generate filename according to instance_str""" byte_obj = bytes(instance_str, 'utf-8') fname = hashlib.shake_128(byte_obj).hexdigest(5) fname = "{}.cpp".format(fname) return fname
7f44e34e4d2ee7598ea972ee4fdfb398b780bfcb
685,254
def rssf(rr, index, scale=10): """Read and scale single to float.""" return float(rr.registers[index]) / scale
93b2a141c4687583592f7dc8e1dedf61de74d2bd
685,256
def build_dict(path, d=None): """Recursively generates a dictionary of dictionaries from a list.""" if not d: d = {} if path: key = path.pop(0) d[key] = build_dict(path, d) return d
21502cbe7614674b7996ad76101191b39f70bea0
685,257
def route(cube): """Dynamic Solution""" L = [1] * cube for i in range(cube): for j in range(i): L[j] = L[j] + L[j - 1] L[i] = 2 * L[i - 1] return L[cube - 1]
69985c0ff4affbe53671f9120afd44a77e007c9a
685,258
import torch def dice_coef(output, target): """ calculates the dice score for a given prediction. :param output: :param target: """ smooth = 1e-5 if torch.is_tensor(output): output = torch.sigmoid(output).data.cpu().numpy() if torch.is_tensor(target): target = targe...
6d4469ca490e8689547a8ceee9fae59a7aaa7309
685,259
def distance(point1, point2): """ Returns the Euclidean distance of two points in the Cartesian Plane. >>> distance([3,4],[0,0]) 5.0 >>> distance([3,6],[10,6]) 7.0 """ return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5
f57446d1a27ca42e347b54310a9bc4184d4519ce
685,260
import os def append_to_path (path, directory): """Add a directory to the PATH environment variable, if it is a valid directory.""" if not os.path.isdir(directory) or directory in path: return path if not path.endswith(os.pathsep): path += os.pathsep return path + directory
a11258e363c01cd7b960fc78b7719f5715cb7d9b
685,261
def _get_hexplain(data: str) -> str: """Returns hex values of data without any prefixes.""" temp = [] for char in data: temp.append(hex(ord(char)).replace("0x", "")) return "".join(temp)
a92efdb8e82826b339f6dccf5316f917d53fedd5
685,262
def str_list_to_int_list(array_like): """ Function to map list of strings to list of integers Parameters: df_trips: DataFrame containing the column 'locations' and 'times' """ return list(map(int,array_like))
2ac649cc7a412a190bb2fd0b646fad66d4f9ac03
685,263
def factorial(n: int) -> int: """Funรงรฃo recursiva para o cรกlculo fatorial Args: n (int): Valor que terรก o fatorial calculado Returns: int: Fatorial calculado """ if n > 1: return factorial(n - 1) * n return 1
0aa773189f7b501a993378a599f9a4b780b0012d
685,264
def split_deck(key, n): """ Split the key like a deck of cards. """ size = len(key) n = n % size return(key[n:] + key[:n])
6f93466cef4f6ff7b20bf7c23b572ec77293b7fa
685,265
import random def randhex(size=32, rng=None): """ Gets a random hex string of @size in terms of number of characters. This is an extremely fast way to generate a random string. @size: (#int) approximate size of the hex to generate in number of characters @rng: the random numbe...
945e624035837285690f995a27cfa3c102ead241
685,267
from typing import Optional from textwrap import dedent import re def tidy_docstring(docstring: Optional[str]) -> str: """ Tidy up the docstring for use as help text. """ if docstring is None: return '' docstring = dedent(docstring).strip() docstring = re.sub(r"``(\d+)``", r"\1", docstring) docstring = re....
4bd72027e5c02cd8f774a6ed1a77dce81378941e
685,268
import requests import logging def validate_server(url): """ Validates if a konduit.Server is running under the specified url. Returns True if the server is running, False otherwise. :param url: host and port of the server as str :return: boolean """ try: r = requests.get("{}/heal...
5fde702b3b0d6e0ec7c19d7903a62c24a98b21c5
685,269
from typing import List def print_bitstring(width: int, bitset: List[int]) -> str: """Format and print a bitset of a certain width with padding.""" return "".join(map(lambda x: bin(x)[2:].zfill(8)[:width], bitset))
c13ecb3e6507dba9d742ddcb606f156ee6199cdb
685,270
def sol(s): """ Update rules as per the statement """ ba = 1 n = len(s) i = 0 t = 4 while i < n: if t < ba: return -1 if s[i] == "W": t = t + ba ba = 1 else: t = t - ba ba = 2*ba i+=1 return t
32446b1e32fe935a10bd1f27a56d58b2de0db374
685,271
def preset_args(request): """ Return preset names that can be used for args testing only; working in module scope """ return request.param
775e1711a3c2c86538404c0c89d0283077c93d25
685,272
import contextlib import socket def tcp_port_connectable(hostname, port): """ Return true if we can connect to a TCP port """ try: with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sk: sk.settimeout(5) ...
7a6c3f5baddfe1726e5f6c1c364c21c3cf94bbf9
685,273
def maxdt(area, shape, maxvel): """ Calculate the maximum time step that can be used in the simulation. Uses the result of the Von Neumann type analysis of Di Bartolo et al. (2012). Parameters: * area : [xmin, xmax, zmin, zmax] The x, z limits of the simulation area, e.g., the shallow...
24f18ef7b7a8194192d0b100fd7d32fc0c608f61
685,274
def get_simulation_attributes(cube): """Get model, experiment and mip information.""" model = cube.attributes['model_id'] experiment = cube.attributes['experiment_id'] physics = cube.attributes['physics_version'] run = cube.attributes['realization'] mip = 'r%si1p%s' %(run, physics) if expe...
719aef44715b6172a45f617c63eeae75673ae2c4
685,275
import sys def equal(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/equal/forum Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and plans to give them more than the others. One of the program manage...
90bacfdb259d397399adc739e0adaad013611f80
685,276
def _create_python_packages_string(python_packages: list): """ Builds the specific string required by Zeppelin images to install Python packages. :param python_packages: list containing Python package strings :return: the properly formatted Python packages string """ if len(python_packages) == ...
99c674f2a31936732fd5f2051cc61258cd267c96
685,279
import math def window(outsideLux): """Returns the effect of windows on lux.""" if outsideLux > 1: percent = 1/math.log(outsideLux) if percent > 100: percent = 100.0 return outsideLux*percent else: return outsideLux / 10.0
0b0f5e0456a25c1da1339aa70c15af8208a908e5
685,280
import numpy def load_grid_points(variant_group): """ Loads the grid point coordinates from the HDF5 variant group Args: variant_group (HDF5 group): the group belonging to the variant selection Returns (list(float), list(float), list(float)): the x, y and z coordinates of the grid po...
6ed3fb666273bc0dc032b53d0243b0ec23b0db09
685,282
from subprocess import run, DEVNULL, STDOUT from sys import executable def is_pip_installed() -> bool: """ Checks whether pip is installed for the current python interpreter :return: true if pip is available """ process = run(f'{executable} -m pip --version', check=False, stdout=DEVNULL, stderr=S...
89a5b2bd4534f30b01b22bada1f5175c51154a44
685,283
def count(input_, condition=lambda x: True): """Count the number of items in an iterable for a given condition For example: >>>count("abc") 3 >>>count("abc", condition=lambda x: x=="a") 1 """ return sum(condition(item) for item in input_)
20114116ca54ba409cabaa992dc2bae0f4599fc9
685,284
def reorder_labels(data, labels): """Reorder output or save cell data according to input labels.""" if len(data.labels) != len(labels): raise ValueError() mapper = {k: v for v, k in enumerate(data.labels)} idx = [mapper[label] for label in labels] data.labels[:] = data.labels[idx] for ...
826c0c99ed5f5a4968eaf2cd6a29ca160fbffe76
685,285
from typing import OrderedDict def format_budgets(budgets, allow_whitespace=False): """ Format budget-strings so that they are as short as possible while still distinguishable Parameters ---------- budgets: List[str] list with budgets allow_whitespace: bool if set to True, wil...
d54170b6da385ac67570151c13c041a14cdd986d
685,286
import click def confirm(text): # type: (str) -> bool """Confirm yes/no.""" return click.confirm(text)
452dadd394bfbea8fcb795cbfda7fe98cfd01bda
685,287
def pair_reads(r1, r2): """ Given bam entries for two ends of the same read (R1/R2) that have been aligned as if they were single-end reads, set the fields in the entries so that they are now properly paired. Args: r1, r2 (pysam.AlignedSegment): two ends of the same read, both a...
07f5f33e0633a46a7a3ff847f1e278ccd158df00
685,288
def get_current_smallest_mkt_cap(df, n=20): """ using df from investing.com and the load_sp600_files function, gets the n number of smallest market-cap stocks should use barchart.com or wrds as source of constituents """ sorted_df = df.sort_values(by='Market Cap') return sorted_df.iloc[:n]....
ad4275a01e761b1bc1d81daee2eaf25efc6d9849
685,289
def scale(mat): """ (function) scale ---------------- Do scaling on the matrix Parameter --------- - mat : input matrix Return ------ - scaled matrix """ # Do scaling on the matrix min_vals = mat.min(0) max_vals = mat.max(0) ranges = max_vals - min_vals ...
6e13cc87e3617b27b8620ee83cf4afc958b43a13
685,290
def get_block_string_indentation(value: str) -> int: """Get the amount of indentation for the given block string. For internal use only. """ is_first_line = is_empty_line = True indent = 0 common_indent = None for c in value: if c in "\r\n": is_first_line = False ...
eb631234db07651d32b9c93fce0a7fba1f8b7ee2
685,291
def is_valid_port(port): """Checks a port number to check if it is within the valid range Args: port - int, port number to check Returns: bool, True if the port is within the valid range or False if not """ if not isinstance(port, int): return False return 1024 < port <...
54163d81e37d42c118a76af32a1b493e52bff560
685,292
def mask_landsat8_sr(image): """Mask clouds and cloud shadows in Landsat surface reflectance image. Obtained from: https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C01_T2_SR Parameters ---------- image : ee.Image Input image (Landsat 8 Surface Reflectance). ...
eeed593eb73a89b4c55b4b1e6d8b56d350127cce
685,293
import re def safe_name(name): """Convert an arbitrary string to a standard distribution name Any runs of non-alphanumeric/. characters are replaced with a single '-'. """ return re.sub('[^A-Za-z0-9.]+', '-', name)
e3cf4edeed7d21b2f78671f9ce9450347584199a
685,294
def deepget(obj, keys): """ Deepget is a small function enabling the user to "cherrypick" specific values from deeply nested dicts or lists. This is useful, if the just one specific value is needed, which is hidden in multiple hierarchies. :Example: >>> import diggrtoolbox as dt >>...
45eef7c4a89323d61669eee5a01bda633e480218
685,296
def get_urls(): """ refine this to add urlpatterns """ return []
7861c373ffde7d07645e6cc77936a8b0018c8798
685,297
import functools def decorator(function): """Decorator""" @functools.wraps(function) def wrapper(*args, **kwargs): answer = function(*args, **kwargs) if answer > 10: answer=10 elif answer<-10: answer=-10 return answer return wrapper
90d0cc283b1136a357baa621126e19bec3a0cc49
685,298
import shutil def is_travis_installed() -> bool: """Return a boolean representing if travis gem is installed.""" return shutil.which("travis") is not None
3bcc3326fa23e669913aa23eebc672b65261868e
685,300
import getpass def input_pwd(tip_words='Please input your password:'): """Add tip_words to getpass.getpass()""" return getpass.getpass(tip_words)
d3b91539df40536ac834dfe81e31512fd2fef001
685,301
import os def license(license_path): """Get license filename.""" if license_path: return os.path.basename(license_path)
50c5ebcf8dbb102b24e5780005fe542e997567ee
685,303
import json def analyse_response(response): """transform response into dict """ data = response.content data = json.loads(data) return data
7302d8f1afad8b77facfc78ba7dc7a5c0cb2e475
685,304
def parse_generic_header(filename, params): """ Given a binary file with phrases and line breaks, enters the first word of a phrase as dictionary key and the following string (without linebreaks) as value. Returns the dictionary. INPUT filename (str): .set file path and name. params (list o...
565b600b419c718190289f23b5ceb5f1b0a7e111
685,305
def order_moves(moves): """ Order moves input parameter(s): move --> List of moves to be ordered return parameter(s): moves_ordered --> List of moves after ordering """ moves_ordered = [] # list to store ordered moves # capturing moves for move in moves: ...
5fb948ac9aa5009aa82aa450cef73e24b8eeb75c
685,306
def remove_template(api, assessment_id): """Remove all templates from an assessment.""" allTemplates = api.templates.get() for template in allTemplates: if template.name.startswith(assessment_id): api.templates.delete(template.id) return True
377a19f4762c02ceb5f6ca3d01c5c144007d6f8e
685,307
def get_rlz_list(all_rlz_records): """ Returns list of unique reverse lookup zone files """ # Casting as set() removes duplicates return list(set([i["zone_file"] for i in all_rlz_records]))
856597818b867336701a0e34eb3343d8603ac06f
685,308
def _phi0_dd(tau,dta): """Calculate fluid water potential ideal term DD-derivative. Calculate the second derivative of the ideal gas component of the Helmholtz potential (scaled free energy) for fluid water with respect to reduced density. :arg float tau: Reduced temperature _TCP/temp(K). ...
ab9dd23c0e5467bed29d183118f6a069d22eff77
685,309
def image_scale(img): """Retrieves the image cell size (e.g., spatial resolution) Args: img (object): ee.Image Returns: float: The nominal scale in meters. """ return img.projection().nominalScale().getInfo()
f0c61e158cafb82142e6d8c5479aef186f13b7e3
685,310
def has_c19_scope (scopes): """ Check if the COVID-19 GLIDE number or HRP code is present """ for scope in scopes: if scope.type == "1" and scope.vocabulary == "1-2" and scope.code.upper() == "EP-2020-000012-001": return True elif scope.type == "2" and scope.vocabulary == "2-1" and s...
1d9c96d093450bd4ab0200eb190302b36eb593f7
685,311
def person(author): """Any text. Returns the name before an email address, interpreting it as per RFC 5322. >>> person('foo@bar') 'foo' >>> person('Foo Bar <foo@bar>') 'Foo Bar' >>> person('"Foo Bar" <foo@bar>') 'Foo Bar' >>> person('"Foo \"buz\" Bar" <foo@bar>') 'Foo "buz" Bar'...
ed16d24e728b998e25a27385c4c1af0cf8d053ff
685,312
def fill_nan(df): """Iterates through a dataframe and fills NaNs with appropriate open, high, low, close values.""" # forward filling the closing price where there were gaps in ohlcv csv df['close'] = df['close'].ffill() # backfilling the rest of the nans df = df.bfill(axis=1) return ...
59ce164c5a4113400902de13590c5189a54a702e
685,313
def del_fake_nums(intList, step): #8 """ Delete fake numbers added by the fake_nums function (only used in decryption) """ placeToDelNum = [] for index in range(0, len(intList), step+1): placeToDelNum.append(index) newIntList = [item for item in intList] for index in reversed(placeTo...
a8bc781b60bfef5441bb69046f3b3db5196767a5
685,315