content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _val_to_bool(val): """Convert a text representation to a bool.""" if val == 'true': return True else: return False
7a5e2428b5025fad318622ff040c7b97282c8af3
633,679
def find_newv(v, tcon, icon): """Find the list of indices for the new tensor after contraction of indices icon of the tensors tcon. """ if len(tcon) == 2: newv = v[tcon[0]] + v[tcon[1]] else: newv = v[tcon[0]] newv = [i for i in newv if i not in icon] return newv
1ebd0290f73d2f3227a1d344c9f7b442992e8aac
633,680
def extract_instances(reservations): """Extract instances from a list of reservations""" instances = [] for reservation in reservations: try: groups = [group.groupName for group in reservation.groups] except AttributeError: #boto version < 2.0rc1 try: ...
f52093250c7a898c84b48048c064e95d40e7cb89
633,681
import torch def getTheLargestComponent(affinity_mat: torch.Tensor, seg_index: int, device: torch.device): """ Find the largest affinity_mat connected components for each given node. This is for checking whether the affinity_mat is fully connected. Args: affinity_mat: (torch.tensor) ...
f782f32d17795e3ff94b158b86380faacd3c69a5
633,682
def add_open_sups(derivation): """Adds the open sups line as a fourth element (index3)""" open_sups = list() for step in range(len(derivation)): if derivation[step][1] == 'SUP': open_sups.append(derivation[step][0]) elif derivation[step][1] == 'I¬' or derivation[step][1] == 'I→':...
d676cabd38b38d58a6322f7957af03a0057a5c70
633,683
import socket import re def strip_volatile(message): """ Strip volatile parts (PID, datetime) from a logging message. """ volatile = ( (socket.gethostname(), 'HOST'), (r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}-\d{4}', 'DATE'), ) for regexp, replacement in volatile: messag...
e4847082169a7a3584209899243b6d4ad150119f
633,685
def accuracy(pred, labels): """ return num of correct predictions :param pred: tensor of prediction :param labels: tensor of labels :return: """ output = (pred > 0.5) correct = 0 for pred, label in zip(output, labels): if int(pred) == label: correct += 1 return correct
6ec01eaff4c3f5501284c77c828d4775c8109799
633,687
def rgb_from_int(val): """Return an RGB tuple converted from an int in the range [0, 0xffffff].""" return tuple([ ((val >> 16) & 0xff) / 0xff, ((val >> 8) & 0xff) / 0xff, (val & 0xff) / 0xff])
8fa2447d8ee3df1b084331204fb8b79a5885847a
633,688
def per_keyed_by_geo(row): """ args: row - should look like ((geo, hhgq, age, hisp, race), cnt) returns tuple keyed by geo """ assert len(row) == 2, f"Person row tuple {row} is not of length 2" (geo, hhgq, age, hisp, race), cnt = row return ((geo,), ((hhgq, age, hisp, rac...
0cc1c8026ad1f527e104c46b3aff1e9aa2c8550e
633,689
import requests def exchange_token(refresh_token, token_endpoint, client_id): """Exchange token for access token.""" response = requests.post( token_endpoint, data={ 'grant_type': 'refresh_token', 'client_id': client_id, 'refresh_token': refresh_token, ...
bd8573ce96961f67dee5fb7af62bcceca93f9ae8
633,690
def integracionMonteCarloStieltjes(Kappa, dim, n, sortearPunto): """ Integracion por Montecarlo. Phi: funcion a integrar n: tamaño de la muestra (cantidad de iteraciones) dim: dimensionalidad del problema sortearPunto: funcion que sortea un punto en un espacio dim-dimensional con una cierta dist...
901021caa6387b16288b407fcd0a60ad755bb5b3
633,691
import requests import json def __login(username, password): """ 登录模块 \n :return: 登陆成功 / 登陆失败 """ data1 = {'student_id': username, 'password': password} r1 = requests.post('http://172.17.173.97:8080/api/user/login', data=data1) user_dict1 = json.loads(r1.text) user_dict = user_dict1 ...
832b36144ab610ba17d8740e3189029be792da2f
633,692
from bs4 import BeautifulSoup import requests def get_soup(url: str) -> BeautifulSoup: """ Generic BeautifulSoup page scraping starter code :param url: String, the url of the page to scrape :return: BeautifulSoup object """ try: page: requests.Response = requests.get(url) soup:...
bd0d5d14c8e6d1b12b6061f14babc317105849aa
633,693
def combining_blocks( blocks: list[list[int]], correction_blocks: list[list[int]], ) -> list[int]: """Function for combining data blocks and correction blocks. Args: blocks: List consisting of lists - blocks of information. correction_blocks: List containing lists - corr...
b16916b0e82834378cc3174c57330e69490364cf
633,694
import re def detect_file_content(content: str, f: str="/etc/passwd") -> bool: """ Detect specific file content in content :param str content: file content that should be analyzed :param str f: file that the content should be compared with :return bool: True if the content was recognized, False other...
c4043b2c2bd6b43f3e1b6e8bfda201950d9120ac
633,695
def should_be_zipped(input_file, input_files): """ Determine whether a given input file should be included in the zip. Compiler includes and target files should only be included if there is no compiler info file present. """ return (input_file in ['metadata.json', 'compiler_info.json'] ...
8f6667928357807e0dba683ac1f655911a0703fc
633,696
def get_idx_via_binary_search(nums: list[int], target: int) -> int: """Returns the index of target if it exists, otherwise -1 Complexity: n = len(nums) Time: O(logn) Space: O(1) Args: nums: array of integers sorted in ascending order target: element for which to sea...
4aa52f2a22d13be23d2fdb69b2e6495d43369254
633,697
import torch def gaussian_sample(mu, sigma): """ Sample a gaussian variable using the reparametrization trick. Arguments: mu (torch.Tensor): Mean. sigma (torch.Tensor): Standard deviation. Same size as mu. Returns: z (torch.Tensor): Samples. Same size as mean. """ ...
5017285f806723f0ec7aa1c3f713fa5d3785216b
633,698
def rejectBranchUsage(err=''): """ Prints the Usage() statement for this method """ m = '' if len(err): m += '%s\n\n' %err m += 'This script will reject a Task Branch (TB) on Salesforce.\n' m += '\n' m += 'Usage:\n' m += ' rejectbranch -s <stream> -b <branch_Name...
15df8232cd17d04dadf83f55bc06efe96d351b79
633,699
def compare_digest(a, b): """ ** From Django source ** Run a constant time comparison against two strings Returns true if a and b are equal. a and b must both be the same length, or False is returned immediately """ if len(a) != len(b): return False result = 0 for ch_a, ...
9f96e33e9ee37208a152ed3a4d79c22909b79b58
633,700
from typing import Dict import time import requests def stock_js_weibo_nlp_time() -> Dict: """ https://datacenter.jin10.com/market :return: 特定时间表示的字典 :rtype: dict """ url = "https://datacenter-api.jin10.com/weibo/config" payload = {"_": int(time.time() * 1000)} headers = { "aut...
69292b924e058122822bb6caec970d2fc39da508
633,701
def rem_punt(sid_list): """Remove PUNT from a SID list and return the new SID list""" mod_list = sid_list mod_list[0] = mod_list[0][:-3] + "100" return mod_list
908fc85bd5f87140f7b95dca2524c133bdc3f95d
633,702
import os import glob def get_all_csv_paths(all_root_paths): """ Function used to get all csv data files example: './NONPD/sub-hc1/ses-hc/Fp1/' gets all csv's at path NONPD/sub-hc1/ses-hc/Fp1/*.csv' :param all_root_paths: :return all_image_paths: complete paths to all images we are going to input ...
8847e0e4e176d02220324fd5d6a0cbce153757e7
633,703
def square_this(x): """Return the square of a number.""" return x**2
2e93801ba9d53b11acb3600f012fffa7d2ee0801
633,704
import os def realpath(path: str) -> str: """ Wrapper for os.path.realpath """ return os.path.realpath(path)
44a50aafc3ac2ad2c39a003496acf340b8a97c16
633,705
def _rfr_getattr_ ( self , att ) : """Get fit-parameter as attribute >>> r = .... >>> print r.sigma """ ## pars = self.floatParsFinal() for p in pars : if att == p.GetName() : return p # pars = self.constPars() for p in pars : if att == p.GetName() : return...
4046a73d4c39f990ef7c79b32c772e69f8fcc150
633,706
async def assert_reply_matches(self, contents: str, regex): """ Send a message and wait for a response. If the response does not match a regex, fail the test. Requires a properly formatted Python regex ready to be used in the ``re`` functions. :param str contents: The content of the trigger message. (A co...
f898b0904a7d6909453eb204fdd1abfeb42437c2
633,707
import os def extractionDonnerSeries(chemin_sous_repertoire_racine) : """ Fonction qui va extraire les titres des différents episodes des differentes saison d'une series. param : chemin_sous_repertoire_racine (string) -> chemin vers l'un des sous repertoires du dossier racine qui contient un ens...
2443ef94cef508c1507acc3263cf0367d6eaab35
633,709
def nullable(languages: dict, attr: str, **kwargs) -> dict: """ :param languages: :param attr: :param kwargs: :return: """ to = kwargs['to'] __add = f'{attr}.add' __delete = f'{attr}.delete' __change = f'{attr}.change' if kwargs['from'] is None: return { l...
cb9881d90b2bda9dbd9ddea1869f2971745e2af1
633,710
def list_apim_api(client, resource_group_name, service_name): """List all APIs of an API Management instance. """ return client.api.list_by_service(resource_group_name, service_name)
d6242d20fa146784f646280fae390653325659ca
633,711
def cast_value(value, requested_type): """ Tries to cast the given value to the given type """ try: if requested_type == "Boolean": return value == "True" if requested_type == "Integer": return int(value) if requested_type == "Float": return float(valu...
dbf99b4989e44a068f72cdd60e17048db5d14c88
633,712
def remote_bazel_options(crosstool_top): """Returns bazel options for the "remote" execution strategy.""" k8 = [ "--cpu=k8", "--host_cpu=k8", "--crosstool_top=" + crosstool_top, "--define=EXECUTOR=remote", ] return k8 + [ "--spawn_strategy=remote", "--genrule_strategy=remote"...
60a1a851b2b51dcd58602d416d4a20b0f690fa6e
633,713
def get_mode_H_array(mode_H, mode_MR, mode_OR): """暖房の運転モードを取得する Args: mode_H(str): 暖房方式 mode_MR(str): 主たる居室の運転方法 (連続運転|間歇運転) mode_OR(str): その他の居室の運転方法 (連続運転|間歇運転) Returns: tuple: 暖房の運転モード """ # 運転モード(暖房) if mode_H == '住戸全体を連続的に暖房する方式': # 全館連続 return tu...
77bc356e7212a250c5e15fff63ecb34052548088
633,715
def is_short_info(obj): """Return whether the object is a short representation of a dataset""" fields = ['bodySize', 'bodyRows', 'bodyFormat', 'numErrors', 'metaTitle', 'commitTime'] return bool(set(obj) & set(fields))
62a4f59d29b5999a6bd5e10eed5513f5925f1d01
633,716
def compute_average_bits(encodings, frequency): """ Compute the average storage bits of the current layer after Huffman Coding. :param 'encodings': Encoding map mapping each weight parameter to its Huffman coding. :param 'frequency': Frequency map mapping each weight parameter to the total number of its...
8bf4296f742dab76145c8fbc6d37249b054aff18
633,717
def decode_name(nbname): """ Return the NetBIOS first-level decoded nbname. """ if len(nbname) != 32: return nbname l_ = [] for i in range(0, 32, 2): l_.append( chr( ((ord(nbname[i]) - 0x41) << 4) | ((ord(nbname[i + 1]) - 0x41) & 0xf)...
8626be13d1c6b1f7be5de1481c38e0b049501d6e
633,718
def split_list(ls, sep): """ Split list similarly to split string, according to some separator """ ret = [] cur = [] for x in ls: if (x != sep): cur.append(x) elif cur: ret.append(cur) cur = [] if cur: ret.append(cur) return ret
fc978be22ff39ad416bd1e6a0ec0974758852c47
633,719
import sys def odd_reads(reads): """ Report reads that don't have a mate with a blast match :param reads: the dict of reads from the blast file :return: two sets of reads that are missing, one from read 1 and one from read 2 """ miss = set() for r in reads: if reads[r][0] and not ...
93c3b8a7e5377e51fa57e23d9362374b8db64268
633,720
def get_function_indent(line: str) -> int: """ Get function indents from begging of the file. """ first_function_entrance = line.index('def') indents = line[:first_function_entrance] indents_space_count = len(indents) return indents_space_count
1e42e082f0c171255c6cac4d426191a83d12a719
633,721
def subject_member_update(client, memb_id, values): """Update an SubjectMember object""" return client.subject_member_update(memb_id=memb_id, values=values)
425fa1d21186d5c18e9478cb6a6ec200c56f7f12
633,722
def get_grey_colour( word, font_size, position, orientation, random_state=None, **kwargs): """wordcloud colouring""" return "hsl(360, 0%, 0%)"
702dcc9d82e1644ec58b3ad1d781b2627f0d97f8
633,723
def horizontal_check(board: list): """ Check if board are ready for game by its row. Return True of False >>> print(horizontal_check(board = ["**** ****","***1 ****","** 3****",\ "* 4 1****"," 9 5 "," 6 83 *","3 1 **"," 8 2***",\ " 2 ****"])) True """ for _, value i...
7057e9084dfcd64a506aa09517017066de788c54
633,724
from pathlib import Path def existing_git_submodule(path: Path) -> bool: """Check if a git submodule exists :param Path path: Submodule path :return: True, if .git file exists inside path """ return Path(path / '.git').is_file()
a0fb29aad65373f49d5306daa3ac13475f328a72
633,725
import numpy as num def local_clustering_in(network): """ Returns the local clustering coefficient for input connections for every single node """ adj = network.adjacency*1-num.diagflat(num.diag(network.adjacency*1)) returned = num.zeros(len(adj)) for (counter,row) in enumerate(adj): ...
9a435ce92aa24431afa495bdc2ff3070e4717ddf
633,726
from typing import List from typing import Any import os def searchExts(ext: str, path: str): """Search for extensions""" files: List[Any] = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith(ext): files.append(root + '\\' + str(file)) re...
4eb0927e2b1702278449f2fe138b462e031ec094
633,727
from pathlib import Path import os def fetch_all_jobs_path(): """ This method creates (if doesnot exists) a folder where all jobs will be stored :return: return all jobs folder path """ prnt_fld = Path.home() fld_path = os.path.join(prnt_fld, "ml_olfa", "all_jobs") if not os.path.exists(f...
f1c07ce87b6c90a5ac1eff858a4d70d78efb1af4
633,729
import os import sys def get_default_netrc_path(): # pragma: no cover """Returns the default path of the '.netrc' file.""" home_dir = os.path.expanduser('~') path = os.path.join( home_dir, '_netrc' if sys.platform.startswith('win') else '.netrc') return path
7a213f7048b5bf7549e2595b40690d8fdbcc44e7
633,730
def round_odd(x): """Round X to nearest odd integer.""" return int(x + 1 - x % 2)
25dcf95626a280b61d4a1b1c9270fe9d358a0688
633,731
import os import sys def get_dir(): """ returns the directory path of the python file executed """ return os.path.dirname(sys.argv[0])
70c37d6cc223a588f802f76619a8c0fec2455998
633,732
import os import subprocess import io import yaml def get_yaml(filename, refname): """ Fetch a yaml file from a specific branch, return its contents to caller as parsed object""" try: devnull = open(os.devnull, "w") fdata = subprocess.check_output(("/usr/bin/git", "show", "%s:%s" % (refname, f...
59b64184f6fbdd5184bf4675b3330efda7b3083a
633,733
def consensus_decision(consensus): """ Given a consensus dict, return list of candidates to delete/archive. """ delete = [] archive = [] for k, v in consensus.items(): tags = v['tags'] if 'delete' in tags or 'rfi' in tags: delete.append(k) elif 'archive' in tags ...
789526ef84e6522651a2e13f676688320445fc95
633,735
def xy2block(x, y): """convert an index to a the x-y-coordinate of the 3x3 block (the third neighborhood) of the cell. Possible values are x from 1..3 and y from 1..3""" return [((x - 1) // 3) * 3 + 1,((y - 1) // 3) * 3 + 1]
69317adb5f50edd7e9ccbad0f36c7174122d4d09
633,737
def _input_wrap(prompt, default=None): """ Run input() with formatted prompt, and return The while loop can be used to ensure correct output """ understood = False while not understood: result = input(prompt.format(default=default)).lower().strip() if result in {"y", "yes"}: ...
112e1bf613e1fc79d570107e881edbb8f721076c
633,738
import hashlib def hash_file(file_path): """ Return the hash of a file. """ md5 = hashlib.md5() with open(file_path, 'rb') as file: md5.update(file.read()) return md5.hexdigest()
f15f591f5e5ca1ae3d807b3b47fddccf3cfdceaa
633,739
def getmAxId(root): """Returns the highest id number from the xml """ a=0 for face in root.iter('Face'): id = int(face.attrib.get('id')) if(id>a): a=id return(a)
cd6c20933d460a442b2eb48525a5dae895ba6544
633,740
import argparse def get_parser(): """ Set logging level from command line. """ parser = argparse.ArgumentParser() parser.add_argument( "--loglv", help="set the log-level for the module, default is `INFO`", default="info" ) return parser
3124be65a82f6499d0be4f9af533d24faee8c562
633,741
def configs_for_ha(atlas_hosts, metadata_port, is_atlas_ha_enabled, metadata_protocol): """ Return a dictionary of additional configs to merge if Atlas HA is enabled. :param atlas_hosts: List of hostnames that contain Atlas :param metadata_port: Port number :param is_atlas_ha_enabled: None, True, or False :...
7475b18d9e325b9a3a0d81937c48a3814390d2d3
633,745
def enrich_with_triples(results, subject, pred='MENTIONED_IN'): """ Enrich with rdf triples a json dictionary in the form of: entity-URI -- MENTIONED_IN -- 'Text 'Title'. Only entities with uri's are considered. Input: - results: dic, json-style dictionary genereated from the extract...
fb90b0cbddca3496dca90e2993f34d2e250ff4c4
633,746
import os def Is64Windows(): """Check if the installed version of Windows is 64 bit that is supported for both 32 and 64 apps""" return 'PROGRAMFILES(X86)' in os.environ
c99d4b845ce6099b32bb2134c37f1f47edc68408
633,747
from typing import List from typing import Tuple def wordtag_soft_acc(list_a: List[Tuple[str, str]], list_b: List[Tuple[str, str]]) -> float: """ Calculate extra metrics of word-tag Args: list_a: prediction list list_b: real list Returns: acc: the extra a...
9ffd51f1c906e88cae8378f6427ed9bc70a15f94
633,749
import math def insert_image_into_grid(final_image, tile_size, image, location, wm=0, hm=0, center=True): """ Given a PIL image object - `final_image`, insert the image found at `image_path` into the appropriate `location` and return it. location is defined as the 2d locatio...
193d52d4c8df43b2a3941e6dbd180b1b81c358fb
633,750
def cer(e): """ Canonicalize the representation of an undirected edge. Works by returning a sorted tuple. """ return tuple(sorted(e))
799a7765c2b77d50828c5b3a365713305a84531e
633,751
def delete_migration(connection, basename): """ Delete a migration in `migrations_applied` table """ # Prepare query sql = "DELETE FROM migrations_applied WHERE name = %s" # Run with connection.cursor() as cursor: cursor.execute(sql, (basename,)) connection.commit() ...
de81e8443343c90aae4690e7c1b2bed9e8dd3239
633,752
import requests def getLikeCount(page_name): """ URL = "https://fr-fr.facebook.com/pg/" + PAGE_NAME + "/community/?ref=page_internal" LOWER_DELIMITER_0 = "Total des mentions J’aime</div>" LOWER_DELIMITER_1 = "</div>" UPPER_DELIMITER_0 = "\">" r = requests.get(URL) page_text = r.text ...
ed438a195cfe8bba948c1deac1d4a18007bbf351
633,753
def remove(n, digit): """Return all digits of N that are not DIGIT, for DIGIT less than 10. >>> remove(231, 3) 21 >>> remove(240132, 2) 4013 """ kept, digits = 0, 0 while n != 0: n, last = n // 10, n % 10 if last != digit: kept = kept / 10 + last ...
48f874a402c011c44884d7d25c4d32904b573e64
633,754
def build_slack_message(integration, title, title_link, fallback_text, fields, pre_text, body, color, thumb_url, image_url): """Build message using Slack webhook format. This will build the payload data for HTTP requests to services such as Slack, Mattermost and Discord. Args: ...
108c9d556cc70aafaf7c4f2c53a2356c753c1a6a
633,756
import re def format_native_language_sentence(nativeLanguageSentence): """ Cleans and formats a scraped nativeLanguageSentence. Returns the new sentence """ # Remove <a> tags and extra whitespace nativeLanguageSentence = re.sub(r"\s\s+", " ", nativeLanguageSentence) nativeLanguageSentence = re.sub( ...
fd6a1932103d2cb704d3124fde5667dc807ed7b8
633,757
def iface_definition(iface, ssid, psk): """Returns the corresponding iface definition as a string, formatted for inclusion in /etc/network/interfaces.d/""" return \ """iface {} inet dhcp wpa-ssid "{}" wpa-psk {} """.format(iface, ssid, psk)
4f4e2899250e7002edcdb65af6674cfe3815ab57
633,758
def get_walk_data(walk, data): """Retrieve data specific to a given walk. Args: walk (str): walk identifier. data (dict): holds all data matrices/lists, including unique walk identifiers in 'subject_walk_IDs'. Returns: walk_data (dict): all data matrices/lists for a sin...
b18578bead7c92fa248903f74f3732cf2c10641d
633,759
def degrees(graph): """Returns a list of node degrees in a ProgramGraph. Args: graph: A ProgramGraph. Returns: An (unsorted) list of node degrees (in-degree plus out-degree). """ return [len(graph.neighbors(node)) for node in graph.all_nodes()]
c267577c476ddce3112870532753eb6a4cbcfdd5
633,760
def checkio(array: list) -> int: """ sums even-indexes elements and multiply at the last 0을 포함한 짝수 인덱스의 값들의 합과 리스트 맨 마지막 값의 곱 연산 결과 출력 """ return 0 if array==[] else sum(array[i] for i in range(0,len(array),2))*array[len(array)-1] # # one-liner(speedy) # return sum(array([::2])*arra...
f6c9853b5e4ea3858b3417ff1792e51d03f3e4b9
633,761
def clientlogin(token): """ Authorization: header to pass to self.client.{get,post}() calls:: self.client.post(url, data, **clientlogin(token)) """ return {'HTTP_AUTHORIZATION': 'GoogleLogin auth={0}'.format(token)}
8c38b06e1ac7a2c211234d7621752dd069d15bcd
633,762
import math def haversine(origin, destination): """ Returns the distance between two points using the haversine formula http://www.platoscave.net/blog/2009/oct/5/calculate-distance-latitude-longitude-python/ >>> int(haversine((-1.31017, 51.7459), (-1.199226, 51.749327))) 7647 """ ...
1bd61ffb086eaf8898cf545e65d851b338c38626
633,763
import argparse def parse_args(): """Parse command line arguments.""" description = 'Command line interface to Duco Ventilation System' parser = argparse.ArgumentParser(description=description) parser.add_argument('--type', dest='modbus_type', default='serial', help='modbus cl...
f62a1dbf207298c60f3f7ebea613bfa5b6a59511
633,764
def normalize_matrix(criteria_matrix, col_sums): """ Normalizes the members of criteria matrix using the vector col_sums. Returns sums of each row of the matrix. :param criteria_matrix: :param col_sums: :return: """ normalized_matrix = {} row_sums = {} for state in criteria_matri...
213b2a67be51acb9425872d967c81290270e77c5
633,765
def add_named_system(builder, name, system): """ Although the Drake docs *say* that DiagramBuilder.AddNamedSystem is supported in the python bindings, that does not appear to be true. So i've implemented it here""" s = builder.AddSystem(system) s.set_name(name) return s
c62d200ba6e651faa8bf524ac2d8e7d077ae0e9c
633,766
def namedit(oldname): """ Change name of key to more readable format """ newname = oldname.replace(">", "") if "|" not in newname: return newname newname = newname.split("|")[3] newname = newname.split(".")[0] return newname
72fa2b45f0a9fbc1a8f060fea7f1ff1f22885614
633,767
def filtering(text): """ Filter empty spaces and new lines from text """ length = len(text) n_0 = '' i = 0 while i < length: if text[i] == n_0: text.remove(text[i]) length = length - 1 continue i = i + 1 i = 0 n_0 = '\n' length = len(te...
019880f5327c0560f9b5791b695a70348c065721
633,768
import requests import time def request_url_json(url: str) -> dict: """Get JSON object version of reponse to GET request to given URL. Args: url: URL to make the GET request. Returns: JSON decoded response from the GET call. Empty dict is returned in case the call fails. """ print(url) try...
98c0ed775c58a99984c09d2c545a8b03f6492f0c
633,769
def kmer_count(k, rc=False): """ Counts the number of possible k-mers Args: k (int): kmer size rc (bool): Use canonical k-mers Returns: int: number of possible kmers """ if not rc: return 4**k n_palindromes = 0 if k % 2 == 0: n_palindromes = 4**(...
26545d0dabdf562b16dcbc323a79e7fc50f7e303
633,770
import requests def latest_block_hash(): """Return the latest block hash.""" r = requests.get('https://blockchain.info/q/latesthash') if r.status_code != 200: err_string = f"latest_block_hash failed with {r} because {r.reason}" print(err_string) raise Exception(err_string) ...
742a017d2ab177c6dc515dbb4fe99c6218122ae9
633,771
def long_repeat(line): """ length the longest substring that consists of the same char """ line_length = len(line) if line_length <= 1: return line_length count_list = [0] current_count = 1 current_ch = '' for i in range(0,line_length): ch = line[i] if ch...
4f7a2dfc5ec6ed08eaa9fc114e4484324b8bdfaa
633,772
def get_initial_cholcovs_index_tuples(n_mixtures, factors): """Index tuples for initial_cov. Args: n_mixtures (int): Number of elements in the mixture distribution of the factors. factors (list): The latent factors of the model Returns: ind_tups (list) """ ind_tups = [] ...
4f05cbe919fa47360eaf41064f79c9c5a5f7d940
633,773
import os def chan_path_from_rel_path(rel_path, channeldir): """ Convert `rel_path` form os.walk tuple format to a tuple of directories and subdirectories, starting with the `channeldir` folder, e.g.,:: >>> chan_path_from_rel_path('content/open_stax_zip/Open Stax/Math/Elementary', ...
68d2ae82d550868be656643ff1981a18a42fc546
633,774
def parametrizeTimeoutMixin(protocol, reactor): """ Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param ...
c544304edaab99ab69de0d23c261a1fa69239ae4
633,775
import hashlib def checksum_file(path): """Compute the sha256 checksum of a path""" hasher = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) return hasher.hexdigest()
913114ed0a21edc2bfd64312d5f503dfb2310746
633,776
from typing import Optional import torch import itertools def unit_box(n: int, scale: Optional[torch.Tensor] = None) -> torch.Tensor: """ Create a (scaled) version of a unit box Args: n: number of dimensions scale: scaling of each dimension Returns: torch.Tensor: scaled unit ...
13ee8e3498e3f613e7f8286c80d5098af24b1dcc
633,777
import re def kw_broad(words): """Return ``words`` in broad match. :param words: list of strings :returns formatted: `words` in broad match type >>> keywords = ['[learn guitar]', '"guitar courses"', '+guitar +tutor'] >>> kw_broad(keywords) ['learn guitar', 'guitar courses', 'guitar tutor'] ...
4896a9fdb044fdc36524869baf45c4f2413a6832
633,778
import os def format_as_yaml(func): """ Decoratate a function that reads lines from a file. Put some YAML formatting around each line of the file and add a header, and footer. Examples -------- >>> from __future__ import print_function >>> import os >>> from standard_names.utiliti...
302dbcfe274406ed3d435611625f54bf94d383bb
633,779
def get_p2p_ssqr_diff_over_var(model): """ Get sum of squared differences of consecutive values as a fraction of the variance of the data. """ return model['ssqr_diff_over_var']
193b81827c6dd5a3f2ff3c1456a8acf29707f49e
633,780
def SetPageSize(unused_ref, args, request): """Set page size to request.pageSize. Args: unused_ref: unused. args: The argparse namespace. request: The request to modify. Returns: The updated request. """ if hasattr(args, 'page-size') and args.IsSpecified('page_size'): request.pageSize = ...
3482ce9d17407bc21c629520f96207b75c2b15e4
633,781
def normalize_path(filepath): """Assume .mst extension if missing""" filepath = filepath.strip() if '.' not in filepath: return filepath + ".mst" else: return filepath
71ed63bdda425d484b40b6982d3f6b8a1091f7d0
633,782
def reverse_y_mapper(height, mapper): """ Returns a coordinate mapper function for grids with reversed Y coordinates. :param height: width of strip :param mapper: grid mapper to wrap :return: mapper(x, y) """ max_y = height - 1 def y_mapper(x, y): return mapper(x, max_y - y) ...
9a33ef9a7b9fb831198fc567ee64965f68835a70
633,783
import re def _modify_expr(expr): """ Filter unsupported characters from expr, modify expr for correct work of RPN algorithm in special cases. :param expr: expression :return: filtered expr """ # filter unsupported characters expr = re.sub(r'[^\w +\-*/^%><=,.!()]', '', expr) # ...2...
cc375af3b11933ac2802eab889aab04cbdc4cc15
633,784
def ip_version(vnum): """String version of ip version""" return 'ipv4' if vnum == 4 else 'ipv6'
81f7df80861e2f7cb675b4e56bf50f03c1eeb515
633,785
import os import importlib import time def merge_file(file_before, file_after, file_output_name = None): """merge files and save as file args: file_before (str) file_after (str) file_output_name (str) returns: saved_file (str) """ file_name = os.path.basename(...
7be45c911257f1525234b35ed90bfb94aab90f5d
633,786
def create_padding_mask(seq): """ Mask all the pad tokens in the batch of sequence. It ensures that the model does not treat padding as the input. The mask indicates where pad value 0 is present: it outputs a 1 at those locations, and a 0 otherwise. The input shape is [batch, seq_len], the output sh...
e133a2f93ea0ea9a4e053b384831971bff85bd1a
633,790
def ns_between(l, r, ns): """Checks if all ns are between l and r (inclusive).""" return all(l <= n <= r for n in ns)
dfa30d7ddf3abe0832387df1205591c09fc88e99
633,791
def unique_id_fixture(hass): """Define a config entry unique ID fixture.""" return "12345"
cefeb9a4b912ae58ce766089df5bedfab6fc5105
633,792
import os def is_npu_device(): """Return whether is npu device or not.""" return os.environ.get('DEVICE_CATEGORY', None) == 'NPU'
487c353b67f4b71d0b190d3d06b099a13aa786b2
633,793