content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def test_external_csv(): """ Example csv file with real genotype-phenotype map """ # Find directory with test files base_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.abspath(os.path.join(base_dir,"data")) return os.path.join(data_dir,"test_data_external.c...
1f1883aeca9ddd115644ed888b599f96564964c8
629,218
def standalone(x): """ Stand-alone functions can also be documented. @param x: some input. @return: 2+2. """ return 2+2
030825647da9e40d612b0a0b7a03268688c949e7
629,219
import os import csv def file_path_and_data(): """ Asks the user for a path to a csv file and return the file path and data :return: path, path to a file, given by the user (str) :return: data, data from the given file (list of lists) """ while True: file_name = input("Enter path to te...
200fc76d1c7e29abcf9cd4d37103d89b9b745255
629,220
def rk4(f, y0, dt): """ Keyword Arguments: f -- y0 -- dt -- """ k1 = f(y0) k2 = f(y0 + 0.5 * dt * k1) k3 = f(y0 + 0.5 * dt * k2) k4 = f(y0 + dt * k3) y1 = y0 + dt / 6 * (k1 + 2 * (k2 + k3) + k4) return y1
a1f1ef0eed64ec720b68495b9b97dfb3120a0847
629,221
def create_put_request(item): """Create a PutRequest object.""" return {'PutRequest': {'Item': item}}
c1ed85b84161ccee0aa84acc0d3004cae5e4adad
629,222
def filter_invalid_unicode(text): """Return an empty string and True if 'text' is in invalid unicode.""" return ("", True) if isinstance(text, bytes) else (text, False)
cdc488b4a7610a74e2b0e6a63ea365664f92e1bf
629,223
def get_sub_fan(graph, maximal_fan, u, v, cd_path, d): """ constructs a sub-fan of "maximal_fan" such that color `d` is free on its last node; :param graph: nx.Graph(); each edge should have an attribute "color" :param maximal_fan: maxmial resulting from `get_maximal_fan` :param u: node in "graph" ...
bbe40f97296c47cd6ff8cd936564e0a67e7d9b45
629,224
import json def get_city_from_string(ctx: str): """ Parses the city out of the JSON contained in the given string. :param ctx: a string containing JSON. :return: (city id, city name) tuple or (None, None) if not found. """ js = json.loads(ctx) for j in js["data"]: if "iglu:com.dbi...
51298c7e2b3c6c2441e5500fdfb0e7aaf42abbdb
629,225
def toBytes(b): """ Converts a string to a bytes object by encoding it as utf-8. """ if type(b) == str: return b.encode("utf-8") else: return b
29912d7cbc75c7d7a6b4e73bf3b7a4935699ef68
629,226
def read_file_to_string(path): """ Returns the contents of a file at ``path`` as a string. :param path: A path string :return: Contents of the file as a string :raises FileNotFoundError: If ``path`` does not exist :raises UnicodeDecodeError: If file does not contain UTF-8/ASCII text """ ...
2f55a15b690bed9e0a92f85883aafe1eda7413c2
629,227
import random def random_string(): """ Generate a random string (currently a random number as a string) """ return str(random.randint(0,100000))
f54b24d2f8ad4a8d67629df4ba93dd7203f41e90
629,228
def slash_esc(string): """ :type string: str :rtype: str """ return string.replace("/", r"\/")
a74a1ecbdaaaeb24093705527781a8d4003efcdb
629,229
import sys def stdout_capture(func): """Decorator to capture stdout during a test for testing the command line If you need to actually print to stdout during a test, use ._print""" sys_stdout = sys.stdout class MockWriter(object): _print = sys_stdout.write def __init__(self): ...
38fa0b0aa26738704d3a51d24b648df519241020
629,230
def get_cors_preflight_view(service): """Return a view for the OPTION method. Checks that the User-Agent is authorized to do a request to the server, and to this particular service, and add the various checks that are specified in http://www.w3.org/TR/cors/#resource-processing-model. """ def _...
129feffba2ca7d1690d83e22b69b398c4362c32a
629,231
def _pos_trace_func(state): """Trace function which records the state position (pos) component.""" return {'pos': state.pos}
28029a353adc375fbc3d1e0d6c74f3762f8ea48e
629,232
def preproc_image(img): """Chop off edges and then downsample to (224, 224, 3)""" if img.shape[-1] == 4: img = img[:, :, :3] if img.shape == (224, 224, 3): return img hdiv, hcrop = img.shape[0] // 224, (img.shape[0] % 224) // 2 wdiv, wcrop = img.shape[1] // 224, (img.shape[1] % 224)...
e986a2f81379b5293e36e1b82d5be768e9693274
629,233
def primeiro_e_ultimo(numeros): """Obtém o primeiro e o último número da lista. Caso não haja pelo menos dois números retorna None para indicar que o problema não tem solução. """ return [67, 12]
2c17eaadd7b213460c4b3d2fdc1b5d4f64e180ff
629,234
def strip_wikilink_to_article(wikilink): """Strip wikilink to article. Parameters ---------- wikilink : str Wikilink Returns ------- stripped_wikilink : str String with stripped wikilink. Examples -------- >>> strip_wikilink_to_article('[[dansk (sprog)|dansk]]'...
d81502263ec5b1685969ed1954ba9403fec9495f
629,235
def let(cls, **kwargs): """Produce new Injector with some dependencies overwritten.""" return type(cls.__name__, (cls,), kwargs)
5d07a62be950906829fc469eb28071c33a657801
629,236
def auto_untype(arg): """ The oposite of auto_type : takes a python base object and tries to convert it to XML typed string. """ if arg is True: return 'TRUE' elif arg is False: return 'FALSE' else: return arg
5725b4d13a2ff8440e80a8e3db6ffc7c76244123
629,237
def fao56_penman_monteith(net_rad, t, ws, svp, avp, delta_svp, psy, shf=0.0): """ Estimate reference evapotranspiration (ETo) from a hypothetical short grass reference surface using the FAO-56 Penman-Monteith equation. Based on equation 6 in Allen et al (1998). :param net_rad: Net radiation at crop ...
922e7ae8b4c80b622a0eb7e7bb17185a5c20a99b
629,238
def is_empty(module, container_name, facts): """ Check if container can be removed safely. To be removed, a container shall not have any container or device attached to it. Current function parses facts to see if a device or a container is attached. If not, we can remove container Parameters ...
e91eb5dfa36c14d701082d0831d6be5147d88179
629,239
def get_total_chemsys(entries, open_elem=None): """ Args: entries: open_elem: Returns: """ elements = {elem for entry in entries for elem in entry.composition.elements} if open_elem: elements.add(open_elem) return "-".join(sorted([str(e) for e in elements]))
ba75b5f736b183dc74cca9bafa1b5b40ba92b65e
629,240
def swift_order(path: list, schema: dict) -> dict: """ Generates Swift struct member order for each level of the Plotly JSON schema hierarchy. """ order = {"/".join(path): list(schema.keys())} for key, item in schema.items(): if isinstance(item, dict) and 'valType' not in item: order = {...
75c1d8cb5a910e54f3a68cd6adb928ec675bf7e2
629,241
def convert_to_dict(data): """Returns a dictionary of US state and the total number of COVID-19 cases as key-value pairs. Parameters: data (list): a list of lists that contain states and total number of cases Returns: dict: a dictionary that contains state and the total number of cases as ...
55ce00b08a6f4b1e21d08df101ccb7cb639fbd1d
629,242
def oven_show_json(oven_player_json, ace_spades_json): """Expected JSON for oven_show model-fixture""" return { "type": "show", "player": oven_player_json, "cards": [ace_spades_json, ace_spades_json], }
73d2638f3c6112cdc8a14d1233239efdc945ac7c
629,243
def SUBTRACT(x, y): """ Subtracts two numbers to return the difference, or two dates to return the difference in milliseconds, or a date and a number in milliseconds to return the resulting date. See https://docs.mongodb.com/manual/reference/operator/aggregation/subtract/ for more details :p...
096f22edbde4a330c486dca51299d76d4ed173f0
629,245
def option_strike(name): """Pull apart an OCC standardized option name and retreive the strike price, in integer form""" return int(name[-8:]) / 1000.0
cfd7d6cd540185ee4c21b99fd32ac71cca019083
629,246
def cc(key): """ Changes python key into Camel case equivalent. For example, 'compute_environment_name' becomes 'computeEnvironmentName'. :param key: :return: """ components = key.split('_') return components[0] + "".join([token.capitalize() for token in components[1:]])
311d253842638f581dd1dd051270f3d6098e2955
629,247
def is_header(line: str, name: str) -> bool: """only the first 4 chancters are read, but we're going to ensure all the letters are correct""" return line.startswith(name[:4]) and line == name[:len(line)]
5844a4cbb4b9416bb468e7d5621fcf4ca1af249c
629,248
import re def parse_remote_states(tf_content): """ Parse remote states configurations from the provided file content. Returns a list of tuples. Ex.: ('foundation', 'gc://tf-bootstrap-vdf/terraform/foundation') Sample configuration: data "terraform_remote_state" "foundation" { backend = "gcs" config ...
b395108991ab11ec18b2737c63abf7ecf2a3ac78
629,249
def clamp(n, smallest, largest): """Ensure 'n' is no smaller or larger then a certain range. If the number is smaller than the range it will be returned as the smallest. If the number is larger than largest it will be returned as the largest. Args: n (int): integer to inspect ...
51fb99ddc7c1f468232c077a9f75542203b63514
629,250
def run_verbose(message, fn, args=[]): """ Calls the function provided by 'fn' with the parameters provided in 'args'. Prints '[message] ... done', with '[message] ...' printed at the start of the function call and 'done' printed at the end of the function call. """ print('{} ...'.format(message...
c6916cf5d99973f764b10ad2c61c34516417e3c5
629,251
def getInterfaceAtoms(cur, pdb): """ Gets interface atoms from database :param cur: cursor to database :param pdb: pdb object to get atoms from :return: list of interface atoms """ cur.execute(''' select Chain,ResId,Symbol from NinterfaceAtoms where PDB='%s' ''' % pdb.name) i...
05eaee03679b6728049413cd644f47890b240c59
629,252
from datetime import datetime def _midnight(): """ Truncate a date to midnight. Default to UTC midnight today.""" return datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
0791492c129135eaea3fcf5619806dc182f8b6fa
629,253
import hashlib import binascii def decrypt(hashed_string, user_input): # Verify Hashing """Verify hash string""" salt = hashed_string[:64] hashed_string = hashed_string[64:] pwdhash = hashlib.pbkdf2_hmac('sha512', user_input.encode('utf-8'), ...
11b893327c55c663a71f1a8dd0bab03ab3ece9f9
629,254
def make_description(args, exclude): """ Make a description for our checkpoints. :param args: arguments from argparse :param exclude: arguments to exclude from argparse :return: description of experiment run """ all_args = vars(args).items() included_args = [k + "_" + str(v) for k, v in ...
50389d5130deca235ba99284d2fa6d86e096c406
629,255
def xtick_formatter(x, pos): """ A formatter used in main_paper function to divide ticks by specific amount. From Stackoverflow #27575257 """ s = '%d' % int(x / 1000) return s
e34e5ad57d58275c5bb79d72536084a80129a980
629,256
def sum_htcl_branches(nested_dict, adj_frac, sum_val): """Sum all leaf node values under a given nested dict level. Args: nested_dict (dict): The nested dict with values to sum. adj_frac (dict): Adjustment fraction to apply to values. sum_val (dict): Summed values. Returns: ...
9543150451c192c9953577af44032c8b6530f0fa
629,257
def pathaddbackslash(cpu_context, func_name, func_args): """ Appends a backslash to the path """ wide = func_name.endswith(u"W") path_ptr = func_args[0] curr_path = cpu_context.memory.read_string(path_ptr, wide=wide) full_path = curr_path + "\\" cpu_context.memory.write_string(path_ptr...
a37f4e9eefd05f0f39fdf2344b79815617e470c8
629,259
def filter_rgi_name(name): """Remove spurious characters and trailing blanks from RGI glacier name. This seems to be unnecessary with RGI V6 """ if name is None or len(name) == 0: return '' if name[-1] in ['À', 'È', 'è', '\x9c', '3', 'Ð', '°', '¾', '\r', '\x93', '¤', '...
15ac9ea762630b3533af34f218257ae0a9260911
629,260
def match_reference(candidate_len, reference_lens): """ 计算当c<=r时,最佳匹配的r的长度 :param candidate_len: :param reference_lens: :return: """ best_len = abs(reference_lens[0] - candidate_len) best_ref = reference_lens[0] for length in reference_lens: if abs(length - candidate_len) < b...
b11a6b4a19d58c1e1bbdd93d8ecf35ffe359f100
629,262
def remove_undefined(payload: dict) -> dict: """Takes a dictionary and removes keys without value""" return {name: value for name, value in payload.items() if value is not None}
5253a2340afdf0d8d431cd85d5a99b74ee8552cd
629,264
import socket def send_all(s, text, stutdown_after_sending=True): """send_all(socket, text, stutdown_after_sending=True) Send all text to the socket. Used during handshaking and in the clientserver module. If stutdown_after_sending, the socket is shut down. Some protocols rely on this. It i...
5f24df23db227f021746d3cf37b84f361259294a
629,266
def _kwargs_arg(**kwargs): """ Check kwargs argument """ fieldselector = "" labelselector = "" limit = 1000 watch = False resourceversion = "" _continue = "" allowwatchbookmarks = False if 'fieldselector' in kwargs and kwargs.get("fieldselector") is not None: fieldse...
11303b97d22d46a80bb0500061a60a2367ab87ae
629,267
def adjust_repeat_data(li, suffix='+'): """ 分析序列li里的值,对出现重复的值进行特殊标记去重 :param li: list,每个元素值一般是str :param suffix: 通过增加什么后缀来去重 :return: 新的无重复数值的li >>> adjust_repeat_data(['a', 'b', 'a', 'c']) ['a', 'b', 'a+', 'c'] """ res = [] values = set() for x in li: while x in values:...
6b5f01bf2a39840d5e9ff0f28420c34aeddba4e6
629,268
from typing import Any def update( dct: dict[str, Any], dct_merge: dict[str, Any], ) -> dict[str, Any]: """Recursively merge dicts.""" if not isinstance(dct, dict): return dct for key, value in dct_merge.items(): if key in dct and isinstance(dct[key], dict): dct[key] = ...
ac7ecc086b668da2122220c7ad4309257e678110
629,269
def get_omniglot_order(): """Returns the omniglot alphabet names, in the order used in previous works. Returns: Alphabet names of the 50 Omniglot tasks, in the same order as used by multiple previous works, such as "Diversity and Depth in Per-Example Routing Models" (https://openreview.net/pdf?id=BkxWJ...
cd9137aab8274bdd77fdb5668fe6a7d23a25ca3d
629,270
def is_subseq(s, subs): """ bool: verifica se subs è sottosequenza di s. """ found = 0 pos_r = 0 while pos_r < len(s): if s[pos_r] == subs[found]: found += 1 if found >= len(subs): return True pos_r += 1 return False
d2db5c449d09443bb55a4d08a977b15de7c531a3
629,271
import json def to_json(response): """Convert raw response into json output.""" return json.dumps(response, indent=2)
a6bcbe8765c9eaeeb335e2b95c151af13527c204
629,272
def mock_pack_data(name='SomePack'): """ Creates mock data to create a pack. """ data = { 'name': name, 'submit': '' } return data
e56fa55a0989a1d8e6d2c6b123597bec7125e110
629,273
def mesh_conway_dual(mesh): """Generates the dual mesh from a seed mesh. Parameters ---------- mesh : Mesh A seed mesh Returns ------- Mesh The dual mesh. Examples -------- >>> mesh = Mesh.from_polyhedron(6) >>> dual = conway_dual(mesh) >>> dual.number_...
918cf0d9ed5d55e64d72bbc95e0aac87ac7c782e
629,274
def catmull_rom_one_point(x, v0, v1, v2, v3): """Computes interpolated y-coord for given x-coord using Catmull-Rom. Computes an interpolated y-coordinate for the given x-coordinate between the support points v1 and v2. The neighboring support points v0 and v3 are used by Catmull-Rom to ensure a smooth ...
81cc7f693db8a24830ef128955abc084f75ba87a
629,275
from typing import Callable import functools from typing import Any def handle_exception_decorator(func: Callable, callback: Callable) -> Callable: """Method decorator that tries to execute the given function and handles any exception by setting the object's status. Arguments: func: T...
8ffc43262fffed566ed82a820165f69f56a26a09
629,276
import signal def getsignal(signum): """Handle references to %SIG not on the LHS of expression""" result = signal.getsignal(signum) if result == signal.SIG_IGN: return 'IGNORE' elif result == signal.SIG_DFL: return 'DEFAULT' return result
33fc3f44c04bb608c1e6653efc78fbb0514c8b56
629,277
def get_rna_base_seq(): """ Returns the sequence of RFAM: AANN01066007.1 """ base_seq = "CTGAGCCGTTACCTGCAGCTGATGAGCTCCAAAAAGAGCGAAACCTGCTAGGTCCTGCAGTACTGGCTTAAGAGGCT" return base_seq
f73ba3959397c6c9c98d163cb1ab5421cb476b94
629,279
import calendar def millis(input_dt): """Convert datetime to milliseconds since epoch""" # Python 3 (or 2 with future module) return 1000 * int(calendar.timegm(input_dt.timetuple())) # Python 2 # return 1000 * long(calendar.timegm(input_dt.timetuple())) # return 1000 * long(time.mktime(input_d...
e337830774554a1e382dc4fdc74806703f33d98b
629,280
import json def validate_response( client, req_method, url, headers, data, expected_resp_code ): """Util function testing response code.""" if data: res = getattr(client, req_method)( url, headers=headers, data=json.dumps(data) ) else: res = getattr(client, req_meth...
660d6ab804feccbc9a295166e8d4cfb0316b0f44
629,281
import pickle def load_data(filename): """Return a Data object loaded from the given pickle file.""" with open(filename, "rb") as f: return pickle.load(f)
91c9d3b9a66a5603992b32be3eb758c88e21dd1c
629,282
def get_fields(db, fields_sql): """ Calls the database and gets fields information. Input: database connection object, SQL query Returns: dictionary of student information, key=field name """ fields = {} with db.cursor() as cursor: cursor.execute(fields_sql) for id, name, fu...
6f0345af4be9eca3214bf5b66e972aaea138778b
629,283
def first(predicate, iterable): """return first element in iterable that satisfies given predicate. Args: predicate: a function that takes one parameter and return a truth value. iterable: any iterable, the items to check. Return: first element in iterable that satisfies predicate,...
c090bb223cb7b83d5f471fdeb6f6b3dc871484c1
629,285
def GetRayFileHeader(): """Returns the header string for a ray file, without color info """ hstr='' hstr=hstr + 'lt_rdf_version: 2.0' + '\n\r' hstr=hstr + 'dataname: untitledRayData' + '\n\r' hstr=hstr + 'lt_datatype: radiant_power' + '\n\r' hstr=hstr + 'lt_radiant_flux: 1' + '\n\r' ...
c4c62fa7eb2bd7496eea37691f4944013a943ae3
629,286
def ttyname(fd): """Return a string which specifies the terminal device associated with file descriptor fd. :type fd: int :rtype: string """ return ''
ba394050d2327ee9226c4dfa64071bca429fc606
629,287
import string import random def random_string(count=10): """ Return a random string with the length of given count. Args: count: the count of random charactors to return. (default: 10) Returns: string, with random charactors, with the length of count. """ charactors = string....
37768b1565c5d8f577e5c88b4df5cef269392a66
629,290
import inspect import functools def normalize_bound(func): """ 'As long as given args are same', callable with @functools.lrc_cache returns cache by this func. Without this, it might not return cache. It depends on the way or order of giving args. @normalize_bound @lrc_cache() def example(foo...
d705d91596f5634f26859c9e08d5a3e7c2ac28a7
629,291
def unflatten(data, dims): """ Given a batch of flattened 1-D tensors, reshapes them into specified N-Dims. """ B = data.size(0) return data.view(B, *dims)
d9ac2fbaa695213d42e785027a6d36899f2da2ac
629,292
import os def AbsolutePath( path, relative_to ): """Returns a normalised, absolute path to |path|. If |path| is relative, it is resolved relative to |relative_to|.""" if not os.path.isabs( path ): path = os.path.join( relative_to, path ) return os.path.normpath( path )
750f4473515a5e8b02b26b93d974bcc533bf6466
629,293
import hmac def secure_data_hmac(data: bytes, key: bytes) -> bytes: """Hashes and encrypts the data using HMAC Args: data (bytes): data to be secured key (bytes): crypto key used for hashing Returns: bytes: data HMAC """ return hmac.digest(key, data, 'sha512')
b1b6333d65debe5486a8619aba1584d9194cf6eb
629,294
from typing import Tuple def complete_index(index: Tuple, n_dims: int) -> Tuple: """ Complete the index with empty slices. This will expand ellipses if present, or pad at the end if not. Args: index: The index in which to replace ellipses n_dims: The number of dim...
d268c7abf9680842dab38f407fed0498c6164b18
629,295
def find_or_create(session, klass, **kwargs): """ Return either an existing klass object that matches kwargs, or create a new one """ r = session.query(klass).filter_by(**kwargs).one_or_none() if r is None: r = klass(**kwargs) session.add(r) return r
d7fe8f544b8696c79ff0e8fac11bf010abf15362
629,296
def remove_quantopian_imports(code: str) -> str: """ we implement the algorithm api inside pylivetrader. the quantopian api is removed. :param code: :return: """ result = [] skip_next_line = False for line in code.splitlines(): if "import" in line and "\\" in line: ...
52d60d2e196296875b664626c924c26c2b903331
629,297
def calc_PV_power(absorbed_radiation_Wperm2, T_cell_C, eff_nom, tot_module_area_m2, Bref_perC, misc_losses): """ To calculate the power production of PV panels. :param absorbed_radiation_Wperm2: absorbed radiation [W/m2] :type absorbed_radiation_Wperm2: float :param T_cell_C: cell temperature [degr...
31673aaf6d693fba150975841b3ae2717f7d0d5c
629,298
def split_df(data, columns=None): """ Get part columns of data. -------- Inputs: - data: Data - columns: columns, List Output: - data: Data, (default get all columns) """ if columns == None: return data else: return data[columns]
35c47d289135b73dd5bc208e9ce5774421dad696
629,299
def power_law_vband_norm(x, slope): """Power law normalised at 0.55 microns (V band).""" return (x / 0.55) ** slope
93569ef42998e324a3beda3ec4693b62328c713f
629,300
import json def json_dumps_formatted(data): """Return json string with standard format""" return json.dumps( data, indent=2, separators=(", ", ": "), ensure_ascii=False ).encode("utf-8")
bc07001145853ebcff03fbd083f666b1fcc77e07
629,301
def get_chrom_sizes(fai_file, exclude_scaffolds=True): """ Get the names and sizes of all the chromosomes in a reference by iterating over the index. """ chroms = {} with fai_file.open('r') as fin: for line in fin: # get the chrom name and size contig, size, _, _, _ ...
a04bf433cf51fd9732e4528e7e861cbb161c40ab
629,302
from pathlib import Path def get_pdf_dir(args): """ コマンドライン入力: 第1引数に1ファイルにしたいPDFフォルダを指定 :param args: pdf dir :return 第一引数に指定したフォルダ名を返す """ pdf_dir_ = args[1] pdf_dir_name = Path(pdf_dir_) print(f"pdf dir name : {pdf_dir_name}\n") return pdf_dir_name
63d17d0f216998819af3bd41a156fa0a9b09f730
629,303
import requests def request_get(url, proxies, headers, params=None, data=None): """Perform requests.""" try: response = requests.get(url, params=params, headers=headers, cookies=None, verify=False, ...
537aea2e10af09b331b69ec68792c800ed3d1bc2
629,304
def bin_to_int(bin): """Binary to int. 0x16 0x22 -> 0x16*256 + 0x22. """ tmp = 0 buf = list(bin) buf.reverse() for i in buf: tmp = 256*tmp + i return tmp
fd6a51aea86b43563011f9f1c69bb0d4aae8e072
629,305
import pprint def pformat_truncate(o, width=50): """Convert the object to printable representation and truncate it if too long Note: If the object is a multiline string or pformat returns a multiline string, only the first line of the string will be returned Args: o (object): Object to...
9119054d8c473f8906fc223b727b41785e4ca12f
629,306
def filter_sentiments(sentiments): """ 过滤情感度大于1的假数据 :return list """ return list(filter(lambda x: float(x) <= 1.0, sentiments))
267fe7d4dbd091cf8fe563e1dc3d963babc5124a
629,307
def get_trader_energy_offer_ramp_rate(trader_id, ramp_rates): """ Given dictionary of trader offer ramp rates, extract the energy offer ramp rate for a given trader. Not all traders participate in the energy market so the function may return if no energy offer ramp rate exists. """ # Check that...
85cd01a30ffd32e0f61088f7ef5bb09ca803b8cf
629,308
import os def is_testing() -> bool: """Indicates whether Spark is currently running tests.""" return "SPARK_TESTING" in os.environ
535891649bf3640d4577884b893b985854d0debe
629,309
def create_schema_name(account): """Create a database schema name.""" return f"acct{account}"
ab90ec89f353f41ac9643f1aca44ab3d52bd2fa5
629,310
def ecart_seuil_de_risque(risque): """ :param risque: un objet ProcessusRisque ou ActiviteRisque !return: un entier compris entre -215 et 215 la fonction prend un objet risque et renvoie la différence entre son seuil de risque et son facteur risque. si le risque n'est pas encore estimé, elle renvoie...
eb69fcfd4c6b894f803ae1407189e8c601e0e8fb
629,311
def specific_match(versions, position=0): """Matches a specific position in a trie dict ordered by its keys Recurse on the trie until it finds an end node (i.e. a non dict node) Position = 0 indicates it will follow the first element Position = -1 indicates it will follow the last element """ if...
bfccc9f3a6fcd4cfeab3c0cbd0d27ec5a32256f9
629,312
def divide_by_four(a): """Return a / 4. """ return a / 4.0
ff64759a439a95626ee60eb18614d9ab18636f82
629,313
def int_tuple(arg): """Convert a string of comma separated numbers to a tuple of integers""" args = arg.split(',') try: return tuple([int(e) for e in args]) except ValueError: raise ValueError('Expected a comma separated list of integers, ' + 'found %s' % arg)
dc6c94f8efbeee3352570d8a32b85dc3c9a7a908
629,314
def find(word, letter, start): """Modify find so that it has a third parameter, the index in word where it should start looking.""" if start > len(word): return -1 index = start while index < len(word): if word[index] == letter: return index index = index + 1 ret...
bad8ff0af68b10b002279d13d0ceb021622c001b
629,315
def format_perc(x, dec_places=1): """ format_perc x: a number to format as a percentage dec_places: an integer for the number of digits past the decimal """ format_str = '{{:,.{}f}}%'.format(dec_places) return format_str.format(float(100*x))
1a57d0bda0dd1c7a5734d29fd77db8edc09328a7
629,316
from bs4 import BeautifulSoup def get_text_from_html(data): """ Get text from html. This is used to get the position and the employee status. """ soup = BeautifulSoup(data, 'html.parser') return soup.get_text().split('-')
fdb005cf669b893be86c587c15b0aab77cd1df7e
629,317
def find_service_roles(roles, type): """ Look for roles like spark_worker, spark_master, namenode, ... We will have duplicate roles depending on how many host are running the same role :param roles: list of service roles :param type: the type of role we are looking for, ie "SPARK_MASTER" :retur...
07353d2c2328ef805309794adf5b63516f7c50c1
629,318
import torch def error_detection(dataset_obj, S, data_in, data_recon, l21=False): """ Uses 1) outlier matrix S; 2) reconstruction error """ ##### S based outlier detection S_out = S.data ## Cell if dataset_obj.dataset_type == 'image' and (not dataset_obj.cat_cols): error_mt...
745a3c9b1ad6269a70908cddf1eb35bdf69f53e0
629,319
def check_puppet_class(rec): """ Checks if the given file is a puppet class :param rec: file path :return: check result """ return rec.lower().endswith(".pp")
93e0f57c44c6b942488c0281e7a6fe6c735bc6fc
629,320
def l1(epoch, batch, args=None): """Stick to l1 loss""" return 1.0
2a3ec3ba6cf243b9f935ed57d735ae6d2d1c5cb7
629,321
import math def surface_disque(rayon): """ fonction qui calcule et renvoie la surface du disque :param rayon: le rayon du disque :type rayon: int ou float :return: la surface du disque (unité (au carré) de celle du rayon) :rtype: float """ return math.pi*rayon**2
424b81b84c21a8e1f848497124bcff971b7f0e15
629,322
def draw_polygon_segments(vertices): """Draws a polygon outline = its segments as lines args: vertices - a array of points""" if len(vertices) < 1: raise ValueError("vertices should have at least one point") def func(ctx): vertex_iter = iter(vertices) ctx.move_to(*next(ve...
b4eddd98d4312967d4c0c1db57ebb2dee90147be
629,324
def get_datetime_str(record): """ Get the datetime string for a record. Args: record: the record to get data for. Returns: datetime string. """ return str(record.getDataTime())[0:19].replace(" ", "_") + ".0"
93bab7ed0457d372e9cd556e280eb4fa963e9fcd
629,325
def find_average_score(generation): """ Generation is a dictionary with the subjects and score. Returns the average score of that generation """ sum = 0 for score in generation.values(): sum += score return sum/len(generation.values())
8fb830914824fda08d1e925e2dbe37fb20d1b4bd
629,326
def mutation(chromosomes,mutation_rate,mode,ID,adaptive=False,**kwargs): """ mutation operator Parameters ---------- 'chromosomes' (list): GA.chromosome objects in population 'mutation_rate' (float): determing the rate/chance of random perturbations in the solutions (e.g. chan...
c82213575195cae1b41fa33f6c67effe3ebed439
629,327