content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy def pitchclass_histogram(sequence, duration=False): """Returns a pitch-class histogram of the sequence 0 represents C, 1 represents C# and so on. If duration is set to True, then the histogram will consider the note durations (default is considering each occurence as a count) """ ...
b9e422294308a704a4b4792835fb30207359988b
658,713
def input_artist(): """Collect artist name""" name = "dummy" # otherwise loop does not start name = input("\nPlease enter the name of the artist to scrape. Press 'Enter' to finish:\n\n ") name = name.lower().strip().replace(' ', '-').replace('+', '_') return name
2bfa3874749c1fb1038d3f35cf5faa798d089510
658,714
import codecs def read_file(filename): """Read a file and return the text content.""" inputfile = codecs.open(filename, "r", "utf-8") data = inputfile.read() inputfile.close() return data
4d2debe4f6d3d93f9a1e26775d48e5930c7075e6
658,715
import os def _write_header(grid, outfile, basepath): """ Write the header of the new grid. Basically copies the old header. Parameters ---------- grid : h5py file Handle of grid to process outfile : h5py file Handle of output grid to write to basepath : str, optional ...
9a41261e0826f49f121c7fa46ac1eeba6536c7a9
658,716
import csv import json def file_to_dict_list(filepath): """Accept a path to a CSV, TSV or JSON file and return a dictionary list""" if '.tsv' in filepath: reader = csv.DictReader(open(filepath), dialect='excel-tab') elif '.csv' in filepath: reader = csv.DictReader(open(filepath)) elif ...
73189d8237a2b7071f6735079e723260aaecb4eb
658,718
from pathlib import Path def getMountPoint (path): """ Return mount point of path """ path = Path (path).resolve () while True: if path.is_mount (): return path path = path.parent
4349edfe16ddffee94e90458387286207ae8839c
658,719
import textwrap def hex_to_rgb(value): """ Convert color`s value in hex format to RGB format. >>> hex_to_rgb('fff') (255, 255, 255) >>> hex_to_rgb('ffffff') (255, 255, 255) >>> hex_to_rgb('#EBF442') (235, 244, 66) >>> hex_to_rgb('#000000') (0, 0, 0) >>> hex_to_rgb('#000') ...
f749f97230f86c5190c1c3c0ed42cd9a6bdd954f
658,720
def map_range(x, X_min, X_max, Y_min, Y_max): """ Linear mapping between two ranges of values """ X_range = X_max - X_min Y_range = Y_max - Y_min XY_ratio = X_range / Y_range y = ((x - X_min) / XY_ratio + Y_min) // 1 return int(y)
34eaac1753b96bd823526f23ba55cb4d70902217
658,721
def simple_interest_fv(P, r, t): """The future value of a simple interest product consists of the initial deposit, called the principal and denoted by P, plus all the interest earned since the money was deposited in the account Parameters ---------- P: float Principal, initial deposit. ...
b883f8cf2fd07f19a906fd279f3e6ab27dc76a72
658,722
def list_tables(conn): """List all tables in a SQLite database Args: conn: An open connection from a SQLite database Returns: list: List of table names found in the database """ cur = conn.cursor() cur.execute("SELECT name FROM sqlite_master") return [i[0] for i in cur.fetc...
941f1f92d5a421eca2e874e5575a27b68f875483
658,723
def sum_multiples(limit): """Sums all multiples of 3 and 5 under `limit` Args: limit (int): The limit that the sums will be calculated up to Returns: int : The sum of all multiples of 3 and 5 up to `limit` """ return sum(x for x in range(limit) if x % 3 == 0 or x % 5 == 0)
5dfe9b98e660bf97841e3b2b5c7e8e24972f2f20
658,724
import os def next_filename(filename): """Check if a given file exists, and return a new filename for a numbered copy if it does.""" filename = str(filename) if os.path.isfile(filename): base, extension = filename.rsplit('.', 1) i = 2 while True: next_check = '{}_{}.{}'...
405aed81785a91065feb593427370840d2dc918d
658,725
def get_filename_from_path(text): """Get the filename from a piece of text. Find the last '/' and returns the words after that. """ return text[text.rindex('/') + 1:]
cc378520912b64338152ac6ad49cb8fa9a967e53
658,726
import six def ensure_unicode_string(value: str) -> str: """Ensure the value is a string, and return it as unicode.""" if not isinstance(value, six.string_types): raise TypeError("Expected string value, got: {}".format(value)) return six.text_type(value)
ec391f0ff73c586cc524e0b144ac7d798d4e1ef2
658,727
def mask_tensor(tensor, mask): """Mask the provided tensor Args: tensor - the torch-tensor to mask mask - binary coefficient-masking tensor. Has the same type and shape as `tensor` Returns: tensor = tensor * mask ;where * is the element-wise multiplication operator """ ass...
fb2c404acf68b7b32444ded391e09472cc75fb75
658,728
def handle_http_error(error): """ Translate the unhandled error into an appropriate api response. """ return error.response
61b9fff99dceda2c74f75876216182089e9896ad
658,729
def add_shadeless_nodes_to_material(mat, shadeless_clr): """ Inject nodes to the material tree required for rendering solid colour output """ mix_node = mat.node_tree.nodes.new('ShaderNodeMixShader') mix_node.name = 'InjectedShadelessMix' dif_node = mat.node_tree.nodes.new('ShaderNodeBsdfDiffuse...
c8417d87d84d0de177818f51dcfd27648c01e9ef
658,730
def get_jwt_from_file(file_name): """ Getting a jwt from a file. Typically, an SA token, which would be at: /var/run/secrets/kubernetes.io/serviceaccount/token """ with open(file_name) as f: return f.read()
e6ef575ad25f91034e434795b09fc791f940c603
658,731
def _bool(item): """_bool Args: item (Any): item Returns: bool: item in bool type """ if item == True: return True if item == False: return False if item == 'true': return True if item == 'True': return True if item == 'false': ...
5432c099593bd3a0f5ef5578fb5c96bfa21916f3
658,732
import hashlib def hash_url(url): """Returns a sha256 hash of the given URL.""" h = hashlib.sha256() h.update(url.encode('ascii', errors='ignore')) return h.hexdigest()
ee6f208efbb58fc9ab9649c5ac6f4da161435cd8
658,733
def bin(number, prefix="0b"): """ Converts a long value to its binary representation. :param number: Long value. :param prefix: The prefix to use for the bitstring. Default "0b" to mimic Python builtin ``bin()``. :returns: Bit string. """ if number is None: raise TypeError("'%...
bef65a7958804a596d090a840d3a47ce175e6528
658,734
import random def bernoulli_trial(p): """베르누이 확률 변수 1 또는 0를 확률 p의 따라서 리턴""" x = random.random() # random(): 0이상 1미만의 난수 리턴 return 1 if x < p else 0
cdad5c17040e8d2bff4f4bf42acc79afe5c5d27c
658,735
def session_num_pageviews(session): """Number of pageviews in session.""" return len([r for r in session if 'is_pageview' in r and r['is_pageview'] == 'true'])
3a894c621cb76a8865d4753a3f9925a2cd54d8de
658,736
def as_int(tokens): """ Converts the token to int if possible. """ return int(tokens[0]) if tokens else None
390d22b72f072e43cd2934c5dda001e0f5d3d434
658,737
import argparse def build_parser(): """CLI parser""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "infile", type=str, help="Input file. If column-delimited, assume first column is se...
9fddcb3587b21a6ea6f225312061615788eb582d
658,738
def _device_matcher(device): """Check if device is monsoon. Method copied from official Monsoon API. """ # pylint: disable=bare-except try: return device.idVendor == 0x2AB9 and device.idProduct == 0x0001 except: return False
dbf01537bba4d65700b761cbf52132bc11779c03
658,739
from datetime import datetime def get_now(): """ A wrapper function of datetime.now helps handle tests Returns: datetime: time right now """ return datetime.now()
8c3471aa0043aa75f23e393b86933ab62604aecf
658,740
def parser(key_name, parser_function): """A decorator function for mapping parsers to key names.""" def store_parser_map(class_reference): """Store the parser map.""" if not hasattr(class_reference, "__deserialize_parser_map__"): setattr(class_reference, "__deserialize_parser_map__...
eabaecaedbb5ca580b3d94df0a2a883128199fc9
658,741
from datetime import datetime def _build_msg_string(instead, since): """Build a deprecation warning message format string.""" if not since: since = '' elif '.' in since: since = ' since release ' + since else: year_str = month_str = day_str = '' days = (datetime.utcnow(...
c86ca3cc3c0ddb2e47dac1f6cd4a00c4479a110e
658,742
import mpmath def cdf(x, mu=0, sigma=1): """ Normal distribution cumulative distribution function. """ # Defined here for consistency, but this is just mpmath.ncdf return mpmath.ncdf(x, mu, sigma)
8a1019ac75edd07db57c937298b3e00bcea387df
658,743
def swizzle(pixels, width, height, blockW=4, blockH=4): """Swizzle pixels into format used by game. pixels: buffer of pixels, which should be an np.array of at least 2 dimensions. width, height: size of buffer. blockW, blockH: swizzle block size, which depends on pixel format. Returns a li...
0941abc72bbe9f78f0a341641a86533e4227bd95
658,744
def sim_percentage_change(obj_1, obj_2): """Calculate the percentage change of two objects Args: obj_1 ([type]): object 1 obj_2 ([type]): object 2 Returns: float: numerical similarity """ try: a = float(obj_1) b = float(obj_2) max_ab = max(abs(a), ab...
eb450b9834552f2b37674a618f0923dc3df8b17b
658,745
def safeadd(*values): """ Adds all parameters passed to this function. Parameters which are None are ignored. If all parameters are None, the function will return None as well. """ values = [v for v in values if v is not None] return sum(values) if values else None
4cfefbfa5ba7754efee813a3daddb3f4d908f990
658,746
def apply_fn_over_range(fn, start_time, end_time, arglist): """Apply a given function per second quanta over a time range. Args: fn: The function to apply start_time: The starting time of the whole duration end_time: The ending time of the whole duration arglist: Additional argument list Returns...
2aeb2809ce1096c4121a07244181097ac099ab71
658,747
def delimit(items): """ Delimit the iterable of strings """ return '; '.join(i for i in items)
771a435b3771fbf2bcdad54cae9f707102756d13
658,749
import os def count_files(path): """Count total files under the path of folder """ file_num = 0 for root, dirs, files in os.walk(path): file_num += len(files) return file_num
2d5f0a47d2fc09a2382f26881565ce815bdedae4
658,750
import math def xyarcsec2pix(xyarcsec, phi, scale): """Determine pixel shifts from E and N offsets from Sgr A*. xyarcsec: 2-element list containing the RA and Dec in degrees. phi: position angle (E of N) in degrees. scale: arcsec per pixel. """ # Expected in arcseconds xarc = xyarcsec[0] ...
ba1a2b9ae74cf30c7fd243ed1a30d96c185a7ccc
658,751
def get_scale(W, H, scale): """ Computes the scales for bird-eye view image Parameters ---------- W : int Polygon ROI width H : int Polygon ROI height scale: list [height, width] """ dis_w = int(scale[1]) dis_h = int(scale[0]) ret...
66d83aa29f14a77e614ce4effd331f04a52e8acb
658,752
import argparse def define_train_input_parameters(): """ Build all arguments needed for the "training" script :return: parsed arguments """ # Mandatory (or not) arguments to run the program ap = argparse.ArgumentParser() ap.add_argument('data', help='path to training dataset directory') ...
530c43f7e85d3417a7f1b5e19e3bdad51d54be73
658,754
import random def executeScriptToGetData(): """ Simulate some actions for text tile exemple """ lv = random.randrange(1, 49) rl = random.randrange(1, 49) bv = lv + rl return {'title': 'Sensor title', 'subtitle': 'Sensor subtitle', 'big_value': f'{bv}%', 'left_la...
20c941deec01b4eb3fe52e0e7c544e02360a0704
658,755
def to(value,dtype): """Force conversion to int data type. If failed return 0: dtype: int8, int32, int64""" isfloat = "float" in str(dtype) try: return dtype(value) except: return 0 if not isfloat else 0.0
f97763fcf7eb6b0f603c34cb77102fae5c35d5a9
658,756
import torch def gram(m: torch.Tensor) -> torch.Tensor: """ Return the Gram matrix of `m` Args: m (tensor): a matrix of dim 2 Returns: The Gram matrix """ g = torch.einsum('ik,jk->ij', m, m) / m.shape[1] return g
6e0482c08df9fa525e965a9662dc35ec3bdfdcd5
658,757
def find_lowest(tem, l): """ :param tem:int, the temperature that user entered. :param l:int, the lowest temperature so far. This function finds the lowest temperature. """ min = l if tem < l: return tem return l
af27f6ab91bf58c2d201195671cdb5aa74f99b97
658,758
def conv_C2K(value): """Converts degree Celsius to Kelvin. Input parameter: scalar or array """ value_k = value+273.15 if(hasattr(value_k, 'units')): value_k.attrs.update(units='K') return(value_k)
719ae5391e71fc996dc35d4a997d7fe77be75af9
658,759
def intersect_two_lists(list_a, list_b): """ Finds the intersections between two lists of TimeSlots. Internally, each list should not have any TimeSlots that intersect """ result = [ ] for item_a in list_a: for item_b in list_b: intersect = item_a.intersect(item_b) if intersect: result.append(interse...
a9625aa05a1cf75ff67ff6dcdc572c430e3d128d
658,760
def time_steps(self): """Get a list containing all time steps The time steps are defined by the class **TimeStepDate** **TimeStepDate class description**:: Type | Name --------- | ---------- int | year int | month int | day int ...
791990ca0a8e2d4d193f691e49c271800981e2d6
658,761
def eval_cell(cell): """ evaluates the new cell that received the pawns from another cell return : 0 if nothing, 1 or -1 if not a full tower and 5 or -5 if full tower """ if not cell: return 0 x = 1 if len(cell) < 5 else 5 return x if not cell[-1] else -x
b20ab0b6b12b3a35e8638281c93ad15082b511fd
658,762
def get_player_classes(flags : dict, player_dict : dict): """Helper class for cmd play. Returns the classes representing the players based on the inputted player flags """ arg_count = len(flags["default"]) players = [0]*4 if arg_count == 1: players = (flags["default"]*4).copy() eli...
a6fa58ab6c48d9b278d31afa5a4ffd7aeb4f490b
658,763
def find_sol(c, ws, vs, memo): """ Finds an optimal solution for the given instance of the knapsack problem with weight capacity c, item weights ws, and item values vs, provided maximum total value for subproblems are memoized in memo. """ sol = [] for n in reversed(range(len(ws))): ...
d66aeac659cb7ec6fc54d52e6e32066faaebda37
658,764
def _masked_idx(mask, indices): """Return index expression for given indices, only if mask is also true there. Parameters: mask: True/False mask indices: indices into array, of shape (n, mask.ndim) Returns: idx: numpy index expression for selected indices idx_mask: mask of s...
ad92a03f08f4778f570a0dc88263a2e243e4c175
658,765
def find_best_matches(text_features, photo_features, photo_ids, num_images, prev_idx): """ Compares the text feature vector to the feature vectors of all images and finds the best matches. Returns the IDs of the best matching photos. Code taken from https://github.com/haltakov/natural-language-image-se...
a9b13ef69de7749cdbfa0e4d4589a65694fba99b
658,766
def dummy_decompressor(data): """ Overview: Return input data. """ return data
7d7209160adef5d486a480437ace9dfde6c7d018
658,767
def GMLreverser(pointlist): """Reverses the order of the points, i.e. the normal of the ring.""" revlist = pointlist[::-1] return revlist
b09da94e21b2162f722c6fc9b05cfb0e100c14c8
658,768
import argparse import unittest import os def main(argv=[]): """ Test main script """ parser = argparse.ArgumentParser(description='Executes the vsgen unit tests.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--testname', help='Specifies the test name to exec...
8b54ad701ef45be20e654d43253669b8e22df8d1
658,769
def natMult3and5(limit): """Find the sum of all the multiples of 3 or 5 below 'limit'""" sum = 0 for i in range(limit): if i % 5 == 0 or i % 3 == 0: sum += i return sum
64eb21299b4c270a3c0d80beb3f710c0ebc1e256
658,770
def element_wrapper(element_name): """NOTE: Not injection safe""" def f(content): return "<%s>%s</%s>" % (element_name, content, element_name) return f
3998459b5f2290ff9ae31a0b687763c6d5c5b58b
658,771
def simple_item_spec(): """A specification for a string item.""" return {'foo': {}}
de5955b13df0407e6eadff50f578f85ca1469362
658,772
def unban_sticker(bot, update, session, chat, user): """Broadcast a message to all users.""" chat.current_sticker.banned = True return 'Sticker unbanned.'
9dc58bb42cb207acfaa074fe53cd8804ba78bd44
658,773
import functools import operator def compute_check(msg): """ Compute the check value for a message AUCTUS messages use a check byte which is simply the XOR of all the values of the message. """ if len(msg) == 0: return 0 return functools.reduce(operator.xor, msg)
1dec5ac53abaa406760d3a0005cdde01953ef68e
658,774
def trivium_annexum_numerordinatio_locali( trivium: str) -> str: """trivium_annexum_numerordinatio_locali Args: trivium (str): /Path to file/@eng-Latn de_codex (str): /Numerordinatio/@eng-Latn Returns: str: numerordinatio_locali Exemplōrum gratiā (et Python doctest, id...
4bbc96b86edd6caf95a2161c0577866eb049c0e7
658,775
def my_layout(G): """For grafer fra make_cliques der koden ligger i de to første tallene""" pos = dict() for i in G.nodes(): x = i.split()[0] pos[i] = (int(x[0]), int(x[1])) return pos
3cba9780fdf3ab356a5e512294c4038705a8a9ce
658,776
def get_flags(args): """Returns the options set in the command line string normalized ("_" is transformed to "-") """ train_stdin = False test_stdin = False flags = [] for i, arg in enumerate(args): if arg.startswith("--"): flag = args[i] # syntax --flag=v...
c9a85373a6ddcf528c874d1de9e0b98619cdf740
658,777
import math def cos(x): """cos(x) Return the cosine of x.""" x = complex(x, 0) real = math.cos(x.real) * math.cosh(x.imag) imag = -math.sin(x.real) * math.sinh(x.imag) return complex(real, imag)
90910e081ad9a2e35876d1bdd6851a4be279f580
658,779
from typing import List from typing import Dict def can_sum(target_sum: int, nums: List, memo: Dict = {}) -> bool: """ :param target_sum: non negative target sum :param nums: List of non negative numbers :param memo: memoization i.e. hash map to store intermediate computation results :return: Bool...
70a1aa3ca8c6bb5229d3b379bed36ed885396493
658,780
import requests def create_private_contribution(username="",password=""): """ Create a private contribution on earthref.org/MagIC. Parameters ---------- username : str personal username for MagIC password : str password for username Returns --------- response: API...
c2bfd5a74fdabf782ccef0bd4b1e145512ed38b3
658,781
def _get_bbox(gdf): """Get tuple bounding box (total bounds) from GeoDataFrame""" xmin, ymin, xmax, ymax = gdf.total_bounds return (xmin, ymin, xmax, ymax)
1a472d73f0d9fbeefe7e3e07f38cd1fd211e7eae
658,782
def make_anagram_2(a,b): """ Using fixed size memory """ count_list = [0]*26 for n in a: count_list[ord(n)-ord('a')] += 1 for n in b: count_list[ord(n)-ord('a')] -= 1 return sum(map(abs,count_list))
862f80ce4e490827bb34aa58a7efcc2eed65798a
658,783
def parse_dnsstamp_address(address, default_port=None): """ Parses an address from a DNS stamp according to the specification: - unwraps IPv6 addresses from the enclosing brackets - separates address string into IP(v4/v6) address and port number, if specified in the stamp address """ ...
23326fb77ecdc7348e24a01befddc58bf99af0c2
658,784
def ellipsis_to_three_dots(dictionary): """Method that replaces all ellipsis (…) with three dots (...) in the dictionary ketys.""" newdict = {} for key in dictionary: newdict[key] = dictionary[key] if "…" in key: new = key.replace("…", "...") newdict[new] = newdict.p...
b08b7b89daeddc8ff28070dbc24dbc31b7d0866a
658,785
from datetime import datetime def calc_season(season): """ Input: a season (pre-summer, summer, post-summer, winter, all) Returns: start and end date as strings min_date: minimum date, in the yyyy-mm-dd hh:mm:ss format max_date: maximum date, in the same format """ if season =...
3115b495368bb70e5f0c03d6d136c4406b576640
658,786
def mod_family_accession(family_accession): """Reduces family accession to everything prior to '.'.""" return family_accession[:family_accession.index('.')]
ec033cd33fccd8fbd7a0c4407d706ca32fb87fb2
658,789
def isalpha(obj): """ Test if the argument is a string representing a number. :param obj: Object :type obj: any :rtype: boolean For example: >>> import pmisc >>> pmisc.isalpha('1.5') True >>> pmisc.isalpha('1E-20') True >>> pmisc.isalpha('1EA-...
b32853e658c6ef453f841292a066bf751708b696
658,790
from typing import Callable def is_hiqed(fun: Callable, fun_name: str) -> bool: """check if this function has been registered in HiQ system The function could be one of: full_qualified_name="<method 'read' of '_io.TextIOWrapper' objects>", fun_name='read' full_qualified_name='<function main...
752de13eb1cb305b0741ed9cd23576a5b9126226
658,791
def unique(seq): """Remove duplicate elements from seq. Assumes hashable elements. Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary""" return list(set(seq))
41e7fd05f0b6a709af8e09c468f99c0bd081dfb3
658,792
def join_base_url_and_query_string(base_url: str, query_string: str) -> str: """Joins a query string to a base URL. Parameters ---------- base_url: str The URL to which the query string is to be attached to. query_string: str A valid query string. Returns ------- str ...
c1c0dcd67fa32bc71134807ad66874aacd51c00d
658,793
def get_empirical_tput(tbs, ttime): """ Returns the empirical throughput :param tbs: total bytes sent for each flow as a dict :param ttime: total time for a session for each flow as a dict :return: a dict type containing all flow ids with their emp throughputs """ etput = {} for l in tbs...
30b627bb90735761f7a0b01162b5d2af1984786e
658,794
import re def xml_get_tag(xml, tag, parent_tag=None, multi_line=False): """ Returns the tag data for the first instance of the named tag, or for all instances if multi is true. If a parent tag is specified, then that will be required before the tag. """ expr_str = '[<:]' + tag + '.*?>(?P<matched_t...
c8c527f34a45f4e27e36d47ef8d356366483ac61
658,795
def fast(request): # type: ignore """--fast config option""" return request.config.getoption('--disable-extra-checks')
a0e9ce1ccf12ea58a6ed5087e07d00e7ebd9b1bc
658,796
import os import json def get_timestamp(): """get timestamp the sim was run""" for filename in os.listdir(os.getcwd()): if filename.endswith('.json'): with open(filename, "r", encoding="utf8") as file: data = file.read() sim = json.loads(data) ...
d368eb51e11b11382e156f02d236a5c653711aca
658,797
def calc_check_digit(number): """Calculate the check digits for the number.""" # we use the full alphabet for the check digit calculation alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' # convert to numeric first, then double some, then sum individual digits number = ''.join( str(alphabet....
87a296883ccc589d5a018dfe4c8c8cdaac5667fa
658,798
import re def _parse_stock_codes(text, has_prefix=False): """解析股票代码""" if has_prefix: pattern = re.compile(r"(s[hz]\d{6})") else: pattern = re.compile(r"s[hz](\d{6})") return re.findall(pattern, text)
c81a807c5249499a7e5d211eafe012c0bedb800d
658,799
def linkMaterial(currMod): """ :param currMod: :return: material """ mat = currMod.get('mat', None) return mat
42d73818a5beea5bc2aa59bed67db9306593fc37
658,800
import os def get_txt_files(directory): """This function takes a directory as input and return all of the txt files in it. Arguments --------- directory -- a direcoty path (absolute) """ files = os.listdir(directory) txt_files = [] for file in files: if '.txt' in file: ...
bff72ee59083f9054fcc3dc8843a6240a8d73207
658,801
import re def remove_from_polymer(polymer, unit): """Remove all occurrences of unit, regardless of polarity from polymer.""" regex = f'{unit}' return re.sub(regex, '', polymer, flags=re.IGNORECASE)
ec86903e000ef2eedd3d7c31550bd1645dc05886
658,802
import requests from bs4 import BeautifulSoup def all_services(): """Creates a list with all business services""" url = "https://www.indeed.com/career-advice/career-development/business-services-types" response = requests.get(url=url) soup = BeautifulSoup(response.content, 'lxml') service_tags = s...
963ce5f9c80e8e35618b0b1d218fdf33507e8f55
658,803
def greatest_increase_or_decrease_in_profits(change_in_profits_and_losses_list, increase_or_decrease, key_1, key_2): """Determine the greatest increase or decrease in profits (date and amount) over the entire period. Args: change_in_profits_and_losses_list (dict): Changes in profits and losses containi...
f14ddec35f506778f3f72a03029118152a862134
658,804
import os def dir2list(dir_location:str) -> list: """ A function to return a given directory in the form of a list -> dir_location: str = location of a directory in string... ex : "C:\\abc\\cdef" ---- => list: ex : ["C:", "abc", "cdef"] """ if not isinstance(dir_location, str): ra...
d9b0adacd6c315849bd6e3f8a35b7dac5f7ede56
658,805
def test_model(model, test_data): """ Run predictions. Args: model: Trained model. test_data: Test dataset. Returns: List of NumPy arrays containing predictions. """ return model.predict(test_data.dataset.data, num_iteration=model.best_iteration)
537683be363800389bdd1fd0e741e83f2f8a0ff2
658,806
def userspec_from_params(user, password): """Given username and password, return a dict containing them.""" return dict( username=user, password=password, )
af3e761ee2774d36e3e4f4f13ae5736ec39e6c2f
658,807
def argmax(seq, func): """ Return an element with highest func(seq[i]) score; tie goes to first one. >>> argmax(['one', 'to', 'three'], len) 'three' """ return max(seq, key=func)
897dac0d922e369fb14107ef10a14916089d4702
658,808
def gen_cddis_repro_specifiers(analysis_centre, version, project, solution): """ IGS files following the long filename convention require specifiers Some common specifiers are used by the analysis centres that submit to CDDIS Given the analysis centre, generate the version, project and solution specifie...
0e8038d37711944737b6873fd73ddf366e6f8ea1
658,810
import collections def pmerge(d, fs): """Merge d with dicts of {(length, precision, scheme, pool): f}.""" r = collections.OrderedDict() r.update(d) for f in fs: r[f.meta.length, f.meta.precision, f.meta.scheme, f.meta.pool] = f return r
ea374394c51eb3027f262abe899f7ff8cad1f7fc
658,811
from typing import Iterable from typing import List import re def freeze_pkgs(text: str, new_list: Iterable[List[str]]) -> str: """loop through new list and replace every occurence of a package with its freeze version""" for pkg in new_list: try: name, version = pkg except Valu...
b1b45e4fcb834da97d18edd9671fb6f6ef9db704
658,812
def crop_img(img): """ crops input image so that only road is visible """ return img[65 : -25, :, :]
79667f98cf8ea7c9eaf8176bbe1e6fa26b31a69f
658,813
import pkgutil def modules_in_pkg(pkg): """Get the modules in the provided package :param pkg: the full package :type pkg: module """ modules = [] for _importer, modname, ispkg in pkgutil.walk_packages(pkg.__path__): if ispkg: continue modules.append(modname) ...
27f81ddd07e5f4782606c210e72f49ad41770c52
658,814
from typing import List def best_time_to_buy_and_sell_stock(prices: List[int]) -> int: """ https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ :param prices: a history of prices os shares :return: the max difference between low to high, when low index is prior the higher """ # Check...
8b8602d1f74cd7cc8ffa3dae76e84b015fd9c8d8
658,815
def get_input_size(dataset_name): """ Returns the size of input """ dataset_name = dataset_name.lower() mapping = { 'mnist': 28 * 28, 'adult': 6, 'pums': 4, 'power': 8 } if dataset_name not in mapping: err_msg = f"Unknown dataset '{dataset_name}'. Ple...
307843635d264a14c472a09be85a19a7d3bf53be
658,816
def quote(string: str) -> str: """ Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts. :param string: :return: """ if ' ' in string: return '"' + string + '"' return string
460b394ddc3223bf3ff7b6fc9b7893802fd7e1b9
658,817
def order_polygon(upper_boundary, lower_boundary): """Create correct sorting to draw filled polygon Arguments --------- upper_boundary lower_boundary Returns ------- """ min_max_polygon = [] for pnt in upper_boundary: min_max_polygon.append(pnt) for pnt in reversed(...
c69c2f62a8ba1b1ce72987c26b327e269fdeaf0e
658,818
def __extract_term(expression): """ Extract a term from an expression with parantheses :param expression: The expression starting with a '(' :return: The extracted term string """ open_parantheses = 0 i = 0 for char in expression: if (char == '('): open_p...
f6ad6d10e79f1f9eb6c83fccdd237556b126dd3f
658,819