content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_list_of_encodings() -> list: """ Get a list of all implemented encodings. ! Adapt if new encoding is added ! :return: List of all possible encodings """ return ['raw', '012', 'onehot', '101']
6e0749eb45f85afe4e5c7414e4d23e67335ba2b5
709,799
def region_to_bin(chr_start_bin, bin_size, chr, start): """Translate genomic region to Cooler bin idx. Parameters: ---------- chr_start_bin : dict Dictionary translating chromosome id to bin start index bin_size : int Size of the bin chr : str Chromosome start : int Start of the genomic region """ return chr_start_bin[chr] + start // bin_size
f17b132048b0ceb4bbf2a87b77327d0d63b3fd64
709,800
import os def get_img_name(img_path: str): """ Get the name from the image path. Args: img_path (str): a/b.jpg or a/b.png ... Returns: name (str): a/b.jpg -> b """ image_name = os.path.split(img_path)[-1].split('.')[0] return image_name
290bcaa133fd414874838f42c2781980954b98ef
709,801
def word_distance(word1, word2): """Computes the number of differences between two words. word1, word2: strings Returns: integer """ assert len(word1) == len(word2) count = 0 for c1, c2 in zip(word1, word2): if c1 != c2: count += 1 return count
b3279744c628f3adc05a28d9ab7cc520744b540c
709,803
def CheckVPythonSpec(input_api, output_api, file_filter=None): """Validates any changed .vpython files with vpython verification tool. Args: input_api: Bag of input related interfaces. output_api: Bag of output related interfaces. file_filter: Custom function that takes a path (relative to client root) and returns boolean, which is used to filter files for which to apply the verification to. Defaults to any path ending with .vpython, which captures both global .vpython and <script>.vpython files. Returns: A list of input_api.Command objects containing verification commands. """ file_filter = file_filter or (lambda f: f.LocalPath().endswith('.vpython')) affected_files = input_api.AffectedTestableFiles(file_filter=file_filter) affected_files = map(lambda f: f.AbsoluteLocalPath(), affected_files) commands = [] for f in affected_files: commands.append(input_api.Command( 'Verify %s' % f, ['vpython', '-vpython-spec', f, '-vpython-tool', 'verify'], {'stderr': input_api.subprocess.STDOUT}, output_api.PresubmitError)) return commands
d6e888b5ce6fec4bbdb35452b3c0572702430c06
709,804
def make_loc(caller): """ turn caller location into a string """ # return caller["file"] + ":" + caller["func"] + ":" + caller["line"] return caller["file"] + ":" + str(caller["line"])
e0db31ffd5c76636938bfe66184f9a2a6fbca496
709,806
import difflib import sys def diff(file1, file2): """ Compare two files, ignoring line end differences If there are differences, print them to stderr in unified diff format. @param file1 The full pathname of the first file to compare @param file2 The full pathname of the second file to compare @return True if the files are the same, o """ with open(file1, 'r') as input1: with open(file2, 'r') as input2: diffs = difflib.unified_diff( input1.read().splitlines(), input2.read().splitlines() ) no_diffs = True for diff in diffs: no_diffs = False print(diff, file=sys.stderr) return no_diffs
980090001ce265afd736e97396315a6a3b72441e
709,807
def processData(list_pc, imo): """ Cette fonction traite les données de getData pour écrire une seule string prête à être copié dans le csv et qui contient toutes les lignes d'un bateau """ str_pc = '' for i in range(len(list_pc)): if list_pc[i] == 'Arrival (UTC)': tab = list_pc[i-1].split(',') # [Port, Country] (good) or [Port, Region, Country] (bad) if len(tab) == 3: tab = ['"' + tab[0] + ',' + tab[1].strip() + '"', tab[2]] # [Port+(Region), Country] str_pc = str_pc + imo + ',' + tab[0] + ',' + tab[1] + ',"' + list_pc[i+1] + '","' + list_pc[i+3] + '","' + list_pc[i+5] + '"\n' return str_pc
abb9d0a8d9f3f1ed35e4f991a3ac14e51621f104
709,808
def convertInt(s): """Tells if a string can be converted to int and converts it Args: s : str Returns: s : str Standardized token 'INT' if s can be turned to an int, s otherwise """ try: int(s) return "INT" except: return s
a0eae31b69d4efcf8f8595e745316ea8622e24b3
709,809
import torch def pairwise_distance(A, B): """ Compute distance between points in A and points in B :param A: (m,n) -m points, each of n dimension. Every row vector is a point, denoted as A(i). :param B: (k,n) -k points, each of n dimension. Every row vector is a point, denoted as B(j). :return: Matrix with (m, k). And the ele in (i,j) is the distance between A(i) and B(j) """ A_square = torch.sum(A * A, dim=1, keepdim=True) B_square = torch.sum(B * B, dim=1, keepdim=True) distance = A_square + B_square.t() - 2 * torch.matmul(A, B.t()) return distance
2142b94f91f9e762d1a8b134fdda4789c564455d
709,810
def get_coaches(soup): """ scrape head coaches :param soup: html :return: dict of coaches for game """ coaches = soup.find_all('tr', {'id': "HeadCoaches"}) # If it picks up nothing just return the empty list if not coaches: return coaches coaches = coaches[0].find_all('td') return { 'Away': coaches[1].get_text(), 'Home': coaches[3].get_text() }
784b355adb885b0eb4f26e72168475e1abbe4d1f
709,811
import os def save_bedtools(cluster_regions, clusters, assigned_dir): """ Given cluster regions file saves all bedtools sanely and returns result :param cluster_regions: :return: """ for region in cluster_regions: output_file = "%s.%s.real.BED" % (clusters, region) cluster_regions[region]['real'] = cluster_regions[region]['real'].sort().saveas(os.path.join(assigned_dir, output_file)) if "rand" not in cluster_regions[region]: continue for n_rand in cluster_regions[region]['rand']: output_file = "%s.%s.rand.%s.BED" % (clusters, region, n_rand) cluster_regions[region]['rand'][n_rand] = cluster_regions[region]['rand'][n_rand].sort().saveas(os.path.join(assigned_dir, output_file)) return cluster_regions
5ef6ee5fd56eb3e6c0659b9979defcab6d9acefb
709,814
import random def about_garble(): """ about_garble Returns one of several strings for the about page """ garble = ["leverage agile frameworks to provide a robust synopsis for high level overviews.", "iterate approaches to corporate strategy and foster collaborative thinking to further the overall value proposition.", "organically grow the holistic world view of disruptive innovation via workplace change management and empowerment.", "bring to the table win-win survival strategies to ensure proactive and progressive competitive domination.", "ensure the end of the day advancement, a new normal that has evolved from epistemic management approaches and is on the runway towards a streamlined cloud solution.", "provide user generated content in real-time will have multiple touchpoints for offshoring."] return garble[random.randint(0, len(garble) - 1)]
c391891f97a7bc6df5287173aa160713cdfff675
709,815
def runningSum(self, nums): """ :type nums: List[int] :rtype: List[int] 5% faster 100% less memory """ sum = 0 runningSum = [0] * len(nums) for i in range(len(nums)): for j in range(i+1): runningSum[i] += nums[j] return runningSum
393849c4aa1d23b15717748066e21abceaf6d5d9
709,816
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. **to_kwargs Additional keywords to forward to every call to ``to``. Examples -------- >>> @preprocess(x=coerce(float, int), y=coerce(float, int)) ... def floordiff(x, y): ... return x - y ... >>> floordiff(3.2, 2.5) 1 >>> @preprocess(x=coerce(str, int, base=2), y=coerce(str, int, base=2)) ... def add_binary_strings(x, y): ... return bin(x + y)[2:] ... >>> add_binary_strings('101', '001') '110' """ def preprocessor(func, argname, arg): if isinstance(arg, from_): return to(arg, **to_kwargs) return arg return preprocessor
61ccce8b9ffbec3e76aa9e78face469add28437e
709,817
import os import logging def get_module_config_filename(): """Returns the path of the module configuration file (e.g. 'app.yaml'). Returns: The path of the module configuration file. Raises: KeyError: The MODULE_YAML_PATH environment variable is not set. """ module_yaml_path = os.environ['MODULE_YAML_PATH'] logging.info('Using module_yaml_path from env: %s', module_yaml_path) return module_yaml_path
b46b7d51817b93dd6b5e026b4e8b52503b2b432a
709,818
def Binary(value): """construct an object capable of holding a binary (long) string value.""" return value
2a33d858b23ac2d72e17ea8ede294c5311cb74be
709,819
import configparser def parse_config_to_dict(cfg_file, section): """ Reads config file and returns a dict of parameters. Args: cfg_file: <String> path to the configuration ini-file section: <String> section of the configuration file to read Returns: cfg: <dict> configuration parameters of 'section' as a dict """ cfg = configparser.ConfigParser() cfg.read(cfg_file) if cfg.has_section(section): return dict(cfg.items(section)) else: print("Section '%s' not found in file %s!" % (section, cfg_file)) return None
021e3594f3130e502934379c0f5c1ecea228017b
709,820
def FormatRow(Cn, Row, COLSP): """ """ fRow = "" for i, c in enumerate(Row): sc = str(c) lcn = len(Cn[i]) sc = sc[ 0 : min(len(sc), lcn+COLSP-2) ] fRow += sc + " "*(COLSP+lcn-len(sc)) return fRow
53d43fc897d1db5ed3c47d6046d90548939b1298
709,822
from typing import Dict from typing import Tuple def _change_relationships(edge: Dict) -> Tuple[bool, bool]: """Validate relationship.""" if 'increases' in edge[1]['relation'] or edge[1]['relation'] == 'positive_correlation': return True, True elif 'decreases' in edge[1]['relation'] or edge[1]['relation'] == 'negative_correlation': return True, False return False, False
b826eb1eb7bd1e7eed7fd8577b5c04d827a75e56
709,823
def c_str_repr(str_): """Returns representation of string in C (without quotes)""" def byte_to_repr(char_): """Converts byte to C code string representation""" char_val = ord(char_) if char_ in ['"', '\\', '\r', '\n']: return '\\' + chr(char_val) elif (ord(' ') <= char_val <= ord('^') or char_val == ord('_') or ord('a') <= char_val <= ord('~')): return chr(char_val) else: return '\\x%02x' % char_val return '"%s"' % ''.join((byte_to_repr(x) for x in str_))
e7cce729a00a7d2a35addf95eb097a3caa06bedd
709,824
import math def mag_inc(x, y, z): """ Given *x* (north intensity), *y* (east intensity), and *z* (vertical intensity) all in [nT], return the magnetic inclincation angle [deg]. """ h = math.sqrt(x**2 + y**2) return math.degrees(math.atan2(z, h))
f4036358625dd9d032936afc373e53bef7c1e6e1
709,825
def _parse_disambiguate(disambiguatestatsfilename): """Parse disambiguation stats from given file. """ disambig_stats = [-1, -1, -1] with open(disambiguatestatsfilename, "r") as in_handle: header = in_handle.readline().strip().split("\t") if header == ['sample', 'unique species A pairs', 'unique species B pairs', 'ambiguous pairs']: disambig_stats_tmp = in_handle.readline().strip().split("\t")[1:] if len(disambig_stats_tmp) == 3: disambig_stats = [int(x) for x in disambig_stats_tmp] return disambig_stats
bb05ec857181f032ae9c0916b4364b772ff7c412
709,826
def clean_vigenere(text): """Convert text to a form compatible with the preconditions imposed by Vigenere cipher.""" return ''.join(ch for ch in text.upper() if ch.isupper())
d7c3fc656ede6d07d6e9bac84a051581364c63a0
709,827
def f_score(r: float, p: float, b: int = 1): """ Calculate f-measure from recall and precision. Args: r: recall score p: precision score b: weight of precision in harmonic mean Returns: val: value of f-measure """ try: val = (1 + b ** 2) * (p * r) / (b ** 2 * p + r) except ZeroDivisionError: val = 0 return val
d12af20e30fd80cb31b2cc119d5ea79ce2507c4b
709,829
import os def get_all_sub_folders(folder_path): """get all sub folders to list Parameters ---------- folder_path : str Returns ------- list """ sub_folders = [] for path in os.listdir(folder_path): full_path = os.path.join(folder_path, path) if os.path.isdir(full_path): sub_folders.append(full_path) return sub_folders
65afa34dadbf4cdd37ebd7feeab9aca9b03570ad
709,830
def role_generator(role): """Closure function returning a role function.""" return lambda *args, **kwargs: role.run(*args, **kwargs)
35dd1a54cb53a6435633c39608413c2d0b9fe841
709,831
def in_scope(repository_data): """Return whether the given repository is in scope for the configuration. Keyword arguments: repository_data -- data for the repository """ if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all": return True # Determine if user has sufficient permissions in the repository to approve the workflow run return not repository_data["object"].archived and ( repository_data["permissions"] == "write" or repository_data["permissions"] == "admin" )
0e521f805f69a1c6f306700680d42fbe76595c3a
709,832
def eval_blocking(lamb, mu, k): """Finds the blocking probability of a queue. Args: lamb (float): The rate into the queue. mu (float): The rate out of the queue. k (int): Maximum number of customers able to be in the queue. """ rho = lamb/mu return rho**k*((1-rho)/(1-rho**(k+1)))
4c1ea7f5f7984fb24c85a5c1c6c77cdbc2e1e76a
709,834
def identity_show(client, resource_group_name, account_name): """ Show the identity for Azure Cognitive Services account. """ sa = client.get(resource_group_name, account_name) return sa.identity if sa.identity else {}
19018c895f3fdf0b2b79788547bf80a400724336
709,835
import math def get_angle(p1, p2): """Get the angle between two points.""" return math.atan2(p2[1] - p1[1], p2[0] - p1[0])
a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a
709,836
def per_application(): """ :return: a seeder function that always returns 1, ensuring at most one delegate is ever spawned for the entire application. """ return lambda msg: 1
7ecc568846ab484557e768ad372f4faf85238401
709,837
import requests from bs4 import BeautifulSoup def get_job_information(url): """ Uses bs4 to grab the information from each job container based on the url. Parameters ---------- url : str Career builder url of any job Returns ------ job_data : dict Contains Job Name, Company Name, Job Location, Description, Skills and apply link. """ website = requests.get(url).text job_soup = BeautifulSoup(website, 'html.parser') job_name = "N/A" try: job_name = job_soup.select('h2.h3')[0].getText() except Exception as err: print(f"The job tile could not be selected properly") print(err) print(f'Skipping {url}...') company_name = "N/A" try: company_name = job_soup.select('.data-details > span:nth-child(1)')[0].getText() except Exception as err: print(f"The company name could not be selected properly") print(err) print(f'Skipping {url}...') job_location = "N/A" try: job_location = job_soup.select('.data-details > span:nth-child(2)')[0].getText() except Exception as err: print(f"The location could not be selected properly") print(err) print(f'Skipping {url}...') job_description = job_soup.select('#jdp_description > div.col-2 > div.col.big.col-mobile-full > p') job_description_2 = job_soup.select('#jdp_description > div:nth-child(1) > div:nth-child(1)') desc = [ ] for idx, paragraph in enumerate(job_description): desc.append(job_description[idx].text) if len(desc) == 0: for idx, paragraph in enumerate(job_description_2): desc.append(job_description_2[idx].text) job_skills = [ ] skills_container = job_soup.findAll("div", {"class": "check-bubble"}) for idx, skill in enumerate(skills_container): job_skills.append(skills_container[idx].text) job_data = {'Job Title': job_name, 'Company': company_name, 'Location': job_location, 'Description': desc, 'Skills': job_skills, 'Application Url': url} return job_data
a5c0b53338dbacc7fe0e7c7eb91b66855968af2b
709,838
def simulation_test(**kwargs): """Decorate a unit test and mark it as a simulation test. The arguments provided to this decorator will be passed to :py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase .setup_simulation_test`. Args: **kwargs (dict): Keyword arguments to pass during setup. Returns: callable: The new unit test function. """ def _dec(func): func.simulation_setup_kwargs = kwargs return func return _dec
56aa51374e66bb765bfc3d4da51e3254d06c0b55
709,839
def region_filter(annos, annotation): """filter for Region annotations. The 'time' parameter can match either 'time' or 'timeEnd' parameters. """ result = [] for anno in annos: time = annotation.get("time") timeEnd = annotation.get("timeEnd") for key in ['text', 'tags']: if anno.get(key) != annotation.get(key): continue if anno.get("regionId") == 0: continue if anno.get("time") not in [time, timeEnd]: continue result.append(anno) return result
3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056
709,840
import os import subprocess import json def run_flow(command, contents): """Run Flow command on a given contents.""" read, write = os.pipe() os.write(write, str.encode(contents)) os.close(write) try: output = subprocess.check_output( command, stderr=subprocess.STDOUT, stdin=read ) decoded_output = output.decode("utf-8") clean_output = decoded_output[decoded_output.find('{"') :] result = json.loads(clean_output) os.close(read) return result except subprocess.CalledProcessError as err: raise err
5621c321d0fb35518aabfb04f0f1b088be2bfa79
709,841
def social_bonus_count(user, count): """Returns True if the number of social bonus the user received equals to count.""" return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count
b2469833f315410df266cd0a9b36933edb1f9ac6
709,842
def read_labels(labels_path): """Reads list of labels from a file""" with open(labels_path, 'rb') as f: return [w.strip() for w in f.readlines()]
3ebc61c76dd1ae83b73aa8b77584661c08a51321
709,844
def _gcs_uri_rewriter(raw_uri): """Rewrite GCS file paths as required by the rewrite_uris method. The GCS rewriter performs no operations on the raw_path and simply returns it as the normalized URI. The docker path has the gs:// prefix replaced with gs/ so that it can be mounted inside a docker image. Args: raw_uri: (str) the raw GCS URI, prefix, or pattern. Returns: normalized: a cleaned version of the uri provided by command line. docker_path: the uri rewritten in the format required for mounting inside a docker worker. """ docker_path = raw_uri.replace('gs://', 'gs/', 1) return raw_uri, docker_path
6e476860cb175dd2936cc0c080d3be1d09e04b77
709,845
def remove_apostrophe(text): """Remove apostrophes from text""" return text.replace("'", " ")
c7d918e56646a247564a639462c4f4d26bb27fc4
709,846
def generate_initials(text): """ Extract initials from a string Args: text(str): The string to extract initials from Returns: str: The initials extracted from the string """ if not text: return None text = text.strip() if text: split_text = text.split(" ") if len(split_text) > 1: return (split_text[0][0] + split_text[-1][0]).upper() else: return split_text[0][0].upper() return None
709e53392c790585588da25290a80ab2d19309f8
709,847
def part_allocation_count(build, part, *args, **kwargs): """ Return the total number of <part> allocated to <build> """ return build.getAllocatedQuantity(part)
84c94ca4e1b1006e293851189d17f63fc992b420
709,848
import itertools import os def count_frames(directory): """ counts the number of consecutive pickled frames in directory Args: directory: str of directory Returns: 0 for none, otherwise >0 """ for i in itertools.count(start=0): pickle_file = os.path.join(directory, f"{str(i).zfill(12)}.pickle") if not os.path.isfile(pickle_file): return i
94df6183e34a5d498493f20c03b00346bc38c50f
709,849
def __parse_sql(sql_rows): """ Parse sqlite3 databse output. Modify this function if you have a different database setup. Helper function for sql_get(). Parameters: sql_rows (str): output from SQL SELECT query. Returns: dict """ column_names = ['id', 'requester', 'item_name', 'custom_name', 'quantity', 'crafting_discipline', 'special_instruction', 'status', 'rarity', 'resource_provided', 'pub-date', 'crafter', 'stats'] request_dict = {str(row[0]): {column_names[i]: row[i] for i,_ in enumerate(column_names)} for row in sql_rows} return request_dict
09c61da81af069709dd020b8643425c4c6964137
709,850
import json def load_default_data() -> dict[str, str]: """Finds and opens a .json file with streamer data. Reads from the file and assigns the data to streamer_list. Args: None Returns: A dict mapping keys (Twitch usernames) to their corresponding URLs. Each row is represented as a seperate streamer. For example: { "GMHikaru":"https://www.twitch.tv/GMHikaru" } """ with open("statum\static\streamers.json", "r") as default_streamers: streamer_list: dict[str, str] = json.load(default_streamers) default_streamers.close() return streamer_list
bfeef64922fb4144228e031b9287c06525c4254d
709,851
def get_value_key(generator, name): """ Return a key for the given generator and name pair. If name None, no key is generated. """ if name is not None: return f"{generator}+{name}" return None
0ad630299b00a23d029ea15543982125b792ad53
709,852
import sys def check_if_string(data): """ Takes a data as argument and checks if the provided argument is an instance of string or not Args: data: Data to check for. Returns: result: Returns a boolean if the data provided is instance or not """ if sys.version_info[0] == 2: return isinstance(data, basestring) else: return isinstance(data, str)
403aabfde1c0d2f3c1ec4610cf83a4abe644acdb
709,853
def int_to_bigint(value): """Convert integers larger than 64 bits to bytearray Smaller integers are left alone """ if value.bit_length() > 63: return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True) return value
0f2d64887dc15d1902b8e10b0257a187ed75187f
709,854
import argparse import sys def cmd_line_parser(): """ This function parses the command line parameters and arguments """ parser = argparse.ArgumentParser(usage="python " + sys.argv[0] + " [-h] [passive/active] -d [Domain] [Options]", epilog='\tExample: \r\npython ' + sys.argv[0] + " passive -d baidu.com -o html") parser._optionals.title = "OPTIONS" parser._positionals.title = "POSITION OPTIONS" parser.add_argument("scan_model", type=str, help="active or passive") # active part active = parser.add_argument_group("active", "active scan configuration options") active.add_argument("-x", "--xxxxx", dest="load_config_file", default=False, action="store_true", help="xxxxxxxxxxxx") # passive part passive = parser.add_argument_group("passive", "passive scan configuration options") passive.add_argument("-w", "--word-list", default=False, help="Custom brute force dictionary path") # other parser.add_argument("-d", "--domain", dest="domain", default=False, help="Target to scan") parser.add_argument("-m", "--multi-domain", dest="domains_file", default=False, help="Multi Target to scan") parser.add_argument("-o", "--format", default=False, help="The format of the output file") if len(sys.argv) == 1: sys.argv.append("-h") return parser.parse_args()
b00ed099de4f2db3c66367e07278c9c0c67f3633
709,855
def CSourceForElfSymbolTable(variable_prefix, names, str_offsets): """Generate C source definition for an ELF symbol table. Args: variable_prefix: variable name prefix names: List of symbol names. str_offsets: List of symbol name offsets in string table. Returns: String containing C source fragment. """ out = ( r'''// NOTE: ELF32_Sym and ELF64_Sym have very different layout. #if UINTPTR_MAX == UINT32_MAX // ELF32_Sym # define DEFINE_ELF_SYMBOL(name, name_offset, address, size) \ { (name_offset), (address), (size), ELF_ST_INFO(STB_GLOBAL, STT_FUNC), \ 0 /* other */, 1 /* shndx */ }, #else // ELF64_Sym # define DEFINE_ELF_SYMBOL(name, name_offset, address, size) \ { (name_offset), ELF_ST_INFO(STB_GLOBAL, STT_FUNC), \ 0 /* other */, 1 /* shndx */, (address), (size) }, #endif // !ELF64_Sym ''') out += 'static const ELF::Sym k%sSymbolTable[] = {\n' % variable_prefix out += ' { 0 }, // ST_UNDEF\n' out += ' LIST_ELF_SYMBOLS_%s(DEFINE_ELF_SYMBOL)\n' % variable_prefix out += '};\n' out += '#undef DEFINE_ELF_SYMBOL\n' return out
233c55815cf5b72092d3c60be42caffc95570c22
709,856
def perdidas (n_r,n_inv,n_x,**kwargs): """Calcula las perdidas por equipos""" n_t=n_r*n_inv*n_x for kwargs in kwargs: n_t=n_t*kwargs return n_t
157825059ad192ba90991bff6206b289755ce0ba
709,858
def get_user(isamAppliance, user): """ Get permitted features for user NOTE: Getting an unexplained error for this function, URL maybe wrong """ return isamAppliance.invoke_get("Get permitted features for user", "/authorization/features/users/{0}/v1".format(user))
0b2fd6c58e2623f8400daa942c83bd0757edd21f
709,859
def wordcount_for_reddit(data, search_word): """Return the number of times a word has been used.""" count = 0 for result in data: # do something which each result from scrape for key in result: stringed_list = str(result[key]) text_list = stringed_list.split() for word in text_list: if search_word == 'Go': if word == search_word: count += 1 elif word.lower() == search_word.lower(): count += 1 return count
b0967aa896191a69cd1b969589b34522299ff415
709,860
def calc_precision(gnd_assignments, pred_assignments): """ gnd_clusters should be a torch tensor of longs, containing the assignment to each cluster assumes that cluster assignments are 0-based, and no 'holes' """ precision_sum = 0 assert len(gnd_assignments.size()) == 1 assert len(pred_assignments.size()) == 1 assert pred_assignments.size(0) == gnd_assignments.size(0) N = gnd_assignments.size(0) K_gnd = gnd_assignments.max().item() + 1 K_pred = pred_assignments.max().item() + 1 for k_pred in range(K_pred): mask = pred_assignments == k_pred gnd = gnd_assignments[mask.nonzero().long().view(-1)] max_intersect = 0 for k_gnd in range(K_gnd): intersect = (gnd == k_gnd).long().sum().item() max_intersect = max(max_intersect, intersect) precision_sum += max_intersect precision = precision_sum / N return precision
536e25aa8e3b50e71beedaab3f2058c79d9957e3
709,861
def __get_app_package_path(package_type, app_or_model_class): """ :param package_type: :return: """ models_path = [] found = False if isinstance(app_or_model_class, str): app_path_str = app_or_model_class elif hasattr(app_or_model_class, '__module__'): app_path_str = app_or_model_class.__module__ else: raise RuntimeError('Unable to get module path.') for item in app_path_str.split('.'): if item in ['models', 'admin']: models_path.append(package_type) found = True break else: models_path.append(item) if not found: models_path.append(package_type) return '.'.join(models_path)
f08685ef47af65c3e74a76de1f64eb509ecc17b9
709,862
def convert_where_clause(clause: dict) -> str: """ Convert a dictionary of clauses to a string for use in a query Parameters ---------- clause : dict Dictionary of clauses Returns ------- str A string representation of the clauses """ out = "{" for key in clause.keys(): out += "{}: ".format(key) #If the type of the right hand side is string add the string quotes around it if type(clause[key]) == str: out += '"{}"'.format(clause[key]) else: out += "{}".format(clause[key]) out += "," out += "}" return out
8b135c799df8d16c116e6a5282679ba43a054684
709,863
def truncate_string(string: str, max_length: int) -> str: """ Truncate a string to a specified maximum length. :param string: String to truncate. :param max_length: Maximum length of the output string. :return: Possibly shortened string. """ if len(string) <= max_length: return string else: return string[:max_length]
c7d159feadacae5a692b1f4d95da47a25dd67c16
709,864
def negative_height_check(height): """Check the height return modified if negative.""" if height > 0x7FFFFFFF: return height - 4294967296 return height
4d319021f9e1839a17b861c92c7319ad199dfb42
709,865
import requests def get_now(pair): """ Return last info for crypto currency pair :param pair: ex: btc-ltc :return: """ info = {'marketName': pair, 'tickInterval': 'oneMin'} return requests.get('https://bittrex.com/Api/v2.0/pub/market/GetLatestTick', params=info).json()
b5db7ba5c619f8369c052a37e010229db7f78186
709,866
def hsv(h: float, s: float, v: float) -> int: """Convert HSV to RGB. :param h: Hue (0.0 to 1.0) :param s: Saturation (0.0 to 1.0) :param v: Value (0.0 to 1.0) """ return 0xFFFF
638c1784f54ee51a3b7439f15dab45053a8c3099
709,867
def clamp(minVal, val, maxVal): """Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`.""" return max(minVal, min(maxVal, val))
004b9a393e69ca30f925da4cb18a8f93f12aa4ef
709,868
from functools import reduce import operator def product(numbers): """Return the product of the numbers. >>> product([1,2,3,4]) 24 """ return reduce(operator.mul, numbers, 1)
102ac352025ffff64a862c4c5ccbdbc89bdf807e
709,869
def solution(N): """ This is a fairly simple task. What we need to do is: 1. Get string representation in binary form (I love formatted string literals) 2. Measure biggest gap of zeroes (pretty self explanatory) """ # get binary representation of number binary_repr = f"{N:b}" # initialise counters current_gap, max_gap = 0, 0 for b in binary_repr: # end of gap, update max if b == '1': max_gap = max(current_gap, max_gap) current_gap = 0 # increase gap counter else: current_gap += 1 return max_gap
54b9dffe219fd5d04e9e3e3b07e4cb0120167a6f
709,870
def meta_caption(meta) -> str: """makes text from metadata for captioning video""" caption = "" try: caption += meta.title + " - " except (TypeError, LookupError, AttributeError): pass try: caption += meta.artist except (TypeError, LookupError, AttributeError): pass return caption
6ef117eb5d7a04adcee25a755337909bfe142014
709,871
def notNone(arg,default=None): """ Returns arg if not None, else returns default. """ return [arg,default][arg is None]
71e6012db54b605883491efdc389448931f418d0
709,872
def transform_and_normalize(vecs, kernel, bias): """应用变换,然后标准化 """ if not (kernel is None or bias is None): vecs = (vecs + bias).dot(kernel) return vecs / (vecs**2).sum(axis=1, keepdims=True)**0.5
bb32cd5c74df7db8d4a6b6e3ea211b0c9b79db47
709,873
def swap_flies(dataset, indices, flies1=0, flies2=1): """Swap flies in dataset. Caution: datavariables are currently hard-coded! Caution: Swap *may* be in place so *might* will alter original dataset. Args: dataset ([type]): Dataset for which to swap flies indices ([type]): List of indices at which to swap flies. flies1 (int or list/tuple, optional): Either a single value for all indices or a list with one value per item in indices. Defaults to 0. flies2 (int or list/tuple, optional): Either a single value for all indices or a list with one value per item in indices. Defaults to 1. Returns: dataset with swapped indices () """ for cnt, index in enumerate(indices): if isinstance(flies1, (list, tuple)) and isinstance(flies2, (list, tuple)): fly1, fly2 = flies1[cnt], flies2[cnt] else: fly1, fly2 = flies1, flies2 if 'pose_positions_allo' in dataset: dataset.pose_positions_allo.values[index:, [fly2, fly1], ...] = dataset.pose_positions_allo.values[index:, [fly1, fly2], ...] if 'pose_positions' in dataset: dataset.pose_positions.values[index:, [fly2, fly1], ...] = dataset.pose_positions.values[index:, [fly1, fly2], ...] if 'body_positions' in dataset: dataset.body_positions.values[index:, [fly2, fly1], ...] = dataset.body_positions.values[index:, [fly1, fly2], ...] return dataset
1f1941d8d6481b63efd1cc54fcf13f7734bccf8b
709,874
import traceback import os def format_exception_with_frame_info(e_type, e_value, e_traceback, shorten_filenames=False): """Need to suppress thonny frames to avoid confusion""" _traceback_message = "Traceback (most recent call last):\n" _cause_message = getattr( traceback, "_cause_message", ("\nThe above exception was the direct cause " + "of the following exception:") + "\n\n", ) _context_message = getattr( traceback, "_context_message", ("\nDuring handling of the above exception, " + "another exception occurred:") + "\n\n", ) def rec_format_exception_with_frame_info(etype, value, tb, chain=True): # Based on # https://www.python.org/dev/peps/pep-3134/#enhanced-reporting # and traceback.format_exception if etype is None: etype = type(value) if tb is None: tb = value.__traceback__ if chain: if value.__cause__ is not None: yield from rec_format_exception_with_frame_info(None, value.__cause__, None) yield (_cause_message, None, None, None) elif value.__context__ is not None and not value.__suppress_context__: yield from rec_format_exception_with_frame_info(None, value.__context__, None) yield (_context_message, None, None, None) if tb is not None: yield (_traceback_message, None, None, None) tb_temp = tb for entry in traceback.extract_tb(tb): assert tb_temp is not None # actual tb doesn't end before extract_tb if "cpython_backend" not in entry.filename and ( not entry.filename.endswith(os.sep + "ast.py") or entry.name != "parse" or etype is not SyntaxError ): fmt = ' File "{}", line {}, in {}\n'.format( entry.filename, entry.lineno, entry.name ) if entry.line: fmt += " {}\n".format(entry.line.strip()) yield (fmt, id(tb_temp.tb_frame), entry.filename, entry.lineno) tb_temp = tb_temp.tb_next assert tb_temp is None # tb was exhausted for line in traceback.format_exception_only(etype, value): if etype is SyntaxError and line.endswith("^\n"): # for some reason it may add several empty lines before ^-line partlines = line.splitlines() while len(partlines) >= 2 and partlines[-2].strip() == "": del partlines[-2] line = "\n".join(partlines) + "\n" yield (line, None, None, None) items = rec_format_exception_with_frame_info(e_type, e_value, e_traceback) return list(items)
f698739f88271bc6c15554be3750bc550f5102a7
709,875
import subprocess def get_volumes(fn): """Return number of volumes in nifti""" return int(subprocess.check_output(['fslnvols', fn]))
67596f0583295f837197e20dd95b1c04fe705ea4
709,876
import socket def find_available_port(): """Find an available port. Simple trick: open a socket to localhost, see what port was allocated. Could fail in highly concurrent setups, though. """ s = socket.socket() s.bind(('localhost', 0)) _address, port = s.getsockname() s.close() return port
1d81ff79fa824bc8b38c121a632890973f0639ea
709,877
import hashlib def calculate_hash(filepath, hash_name): """Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available.""" hash_name = hash_name.lower() if not hasattr(hashlib, hash_name): raise Exception('Hash algorithm not available : {}'\ .format(hash_name)) with open(filepath, 'rb') as f: checksum = getattr(hashlib, hash_name)() for chunk in iter(lambda: f.read(4096), b''): checksum.update(chunk) return checksum.hexdigest()
975fe0a2a4443ca3abc67ed950fb7200409f2497
709,878
def default_mp_value_parameters(): """Set the different default parameters used for mp-values. Returns ------- dict A default parameter set with keys: rescale_pca (whether the PCA should be scaled by variance explained) and nb_permutations (how many permutations to calculate empirical p-value). Defaults to True and 100, respectively. """ params = {"rescale_pca": True, "nb_permutations": 100} return params
0dcac3981154fbf0cc1fa0eeed6e83a1e1b63294
709,879
def deep_copy(obj): """Make deep copy of VTK object.""" copy = obj.NewInstance() copy.DeepCopy(obj) return copy
c00c4ff44dad5c0c018152f489955f08e633f5ed
709,880
def loss_calc(settings, all_batch, market_batch): """ Calculates nn's NEGATIVE loss. Args: settings: contains the neural net all_batch: the inputs to neural net market_batch: [open close high low] used to calculate loss Returns: cost: loss - l1 penalty """ loss = settings['nn'].loss_np(all_batch, market_batch) return -loss
fdca1bb0fa86d1972c2a0f8b1fab10183e98fb4e
709,881
def group_result(result, func): """ :param result: A list of rows from the database: e.g. [(key, data1), (key, data2)] :param func: the function to reduce the data e.g. func=median :return: the data that is reduced. e.g. [(key, (data1+data2)/2)] """ data = {} for key, value in result: if key in data.keys(): data[key].append(value) else: data[key] = [value] for key in data: data[key] = func(data[key]) return data.items()
7687521c216210badcda5ee54bd59a3bc6a234bd
709,883
import os def cleanup_path(paths, removedir=True): """ remove unreable files and directories from the input path collection, skipped include two type of elements: unwanted directories if removedir is True or unaccessible files/directories """ checked = [] skipped = [] for ele in paths: ele = os.path.abspath(ele) if os.path.exists(ele) and os.access(ele, os.R_OK): if os.path.isdir(ele) and removedir: skipped.append(ele) else: checked.append(ele) else: skipped.append(ele) return checked, skipped
36105a4617ea0cfffc870dd083540f81aaf56079
709,884
import os import glob def _findPlugInfo(rootDir): """ Find every pluginInfo.json files below the root directory. :param str rootDir: the search start from here :return: a list of files path :rtype: [str] """ files = [] for root, dirnames, filenames in os.walk(rootDir): files.extend(glob.glob(root + '/plugInfo.json')) return files
d3367d8f71598d1fa1303baec0d4f6803b1293b2
709,885
import os import fnmatch def rec_search(wildcard): """ Traverse all subfolders and match files against the wildcard. Returns: A list of all matching files absolute paths. """ matched = [] for dirpath, _, files in os.walk(os.getcwd()): fn_files = [os.path.join(dirpath, fn_file) for fn_file in fnmatch.filter(files, wildcard)] matched.extend(fn_files) return matched
47e8bd48956de87a72c996795f94b69979bf992f
709,886
import os def get_username(): """Return username Return a useful username even if we are running under HT-Condor. Returns ------- str : username """ batch_system = os.environ.get('BATCH_SYSTEM') if batch_system == 'HTCondor': return os.environ.get('USER', '*Unknown user*') return os.getlogin()
1e199e7e38ed6532253ee1f7f229bb1baffc5538
709,888
def matrix2list(mat): """Create list of lists from blender Matrix type.""" return list(map(list, list(mat)))
9b4b598eb33e4d709e15fd826f23d06653659318
709,890
def convert_handle(handle): """ Takes string handle such as 1: or 10:1 and creates a binary number accepted by the kernel Traffic Control. """ if isinstance(handle, str): major, minor = handle.split(':') # "major:minor" minor = minor if minor else '0' return int(major, 16) << 16 | int(minor, 16) return handle
ed4ef5107178bd809a421e0b66c621d9bdaceef1
709,891
def get_height(img): """ Returns the number of rows in the image """ return len(img)
765babc9fbc1468ef5045fa925843934462a3d32
709,893
def wpt_ask_for_name_and_coords(): """asks for name and coordinates of waypoint that should be created""" name = input("Gib den Namen des Wegpunkts ein: ") print("Gib die Koordinaten ein (Format: X XX°XX.XXX, X XXX°XX.XXX)") coordstr = input(">> ") return name, coordstr
d38a728c5a6ecd1fde9500175ea5895ade8c6880
709,894
def sum_squares(n): """ Returns: sum of squares from 1 to n-1 Example: sum_squares(5) is 1+4+9+16 = 30 Parameter n: The number of steps Precondition: n is an int > 0 """ # Accumulator total = 0 for x in range(n): total = total + x*x return total
669a5aa03a9d9a9ffe74e48571250ffa38a7d319
709,895
def froc_curve_per_side(df_gt, df_pred, thresholds, verbose, cases="all"): """ Compute FROC curve per side/breast. All lesions in a breast are considered TP if any lesion in that breast is detected. """ assert cases in ["all", "cancer", "benign"] if not cases == "all": df_exclude = df_gt[~(df_gt["Class"] == cases)] df_gt = df_gt[df_gt["Class"] == cases] df_pred = df_pred[~(df_pred["StudyUID"].isin(set(df_exclude["StudyUID"])))] df_gt["Side"] = df_gt["View"].astype(str).str[0] df_pred["Side"] = df_pred["View"].astype(str).str[0] total_volumes = len(df_pred.drop_duplicates(subset=["StudyUID", "View"])) total_tps = len(df_gt.drop_duplicates(subset=["PatientID", "Side"])) tpr = [] fps = [] if verbose: print("{} cases FROC:".format(cases.upper())) for th in sorted(thresholds, reverse=True): df_th = df_pred[df_pred["Score"] >= th] df_th_unique_tp = df_th.drop_duplicates(subset=["PatientID", "Side", "TP"]) num_tps_th = float(sum(df_th_unique_tp["TP"])) tpr_th = num_tps_th / total_tps num_fps_th = float(len(df_th[df_th["TP"] == 0])) fps_th = num_fps_th / total_volumes tpr.append(tpr_th) fps.append(fps_th) if verbose: print( "Sensitivity {0:.2f} at {1:.2f} FPs/volume (threshold: {2:.4f})".format( tpr_th * 100, fps_th, th ) ) return tpr, fps
6a113856a920f775be3ce652fa09d9d79fb9be00
709,897
import platform def check_platform(): """ str returned """ return platform.system()
73e813c55807e7d84517cb7ce51ce9db34e42c23
709,898
def save(self, fname="", ext="", slab="", **kwargs): """Saves all current database information. APDL Command: SAVE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). An unspecified directory path defaults to the working directory; in this case, you can use all 248 characters for the file name. ext Filename extension (eight-character maximum). slab Mode for saving the database: ALL - Save the model data, solution data and post data (element tables, etc.). This value is the default. MODEL - Save the model data (solid model, finite element model, loadings, etc.) only. SOLU - Save the model data and the solution data (nodal and element results). Notes ----- Saves all current database information to a file (File.DB). In interactive mode, an existing File.DB is first written to a backup file (File.DBB). In batch mode, an existing File.DB is replaced by the current database information with no backup. The command should be issued periodically to ensure a current file backup in case of a system "crash" or a "line drop." It may also be issued before a "doubtful" command so that if the result is not what was intended the database may be easily restored to the previous state. A save may be time consuming for large models. Repeated use of this command overwrites the previous data on the file (but a backup file is first written during an interactive run). When issued from within POST1, the nodal boundary conditions in the database (which were read from the results file) will overwrite the nodal boundary conditions existing on the database file. Internal nodes may be created during solution (for example, via the mixed u-P formulation or generalized plane strain option for current- technology elements, the Lagrangian multiplier method for contact elements or the MPC184 elements, or the quadratic or cubic option of the BEAM188 and PIPE288 elements). It is sometimes necessary to save the internal nodes in the database for later operations, such as cutting boundary interpolations (CBDOF) for submodeling. To do so, issue the SAVE command after the first SOLVE command. In general, saving after solving is always a good practice. This command is valid in any processor. """ return self.run(f"SAVE,{fname},{ext},,{slab}", **kwargs)
ddc79dc0f54e32d6cd96e115ad9842c1689c17b1
709,900
def _token_text(token): """Helper to get the text of a antlr token w/o the <EOF>""" istream = token.getInputStream() if istream is None: return token.text n = istream.size if token.start >= n or token.stop >= n: return [] return token.text
0821c44eea9dfc229034bebc45211f8e6336c552
709,901
def get_dict_or_generate(dictionary, key, generator): """Get value from dict or generate one using a function on the key""" if key in dictionary: return dictionary[key] value = generator(key) dictionary[key] = value return value
e31cd2b6661cf45e5345ce57d1e628174e6fd732
709,902
def createNotInConfSubGraph(graphSet, possibleSet): """ Return a subgraph by removing all incoming edges to nodes in the possible set. """ subGraph = {} for i in graphSet: subGraph[i] = graphSet[i] - possibleSet return subGraph
d3cbee9049416d7ff865306713e9a12f26717fae
709,903
import random def get_random_instance() -> random.Random: """ Returns the Random instance in the random module level. """ return random._inst
ee66055275153ce8c3eae67eade6e32e50fe1d79
709,904
import cgitb def FormatException(exc_info): """Gets information from exception info tuple. Args: exc_info: exception info tuple (type, value, traceback) Returns: exception description in a list - wsgi application response format. """ return [cgitb.handler(exc_info)]
733c2170a08f9880f8c191c1c6a52ee1ab455b7f
709,905
def _infer_added_params(kw_params): """ Infer values for proplot's "added" parameters from stylesheets. """ kw_proplot = {} mpl_to_proplot = { 'font.size': ('tick.labelsize',), 'axes.titlesize': ( 'abc.size', 'suptitle.size', 'title.size', 'leftlabel.size', 'rightlabel.size', 'toplabel.size', 'bottomlabel.size', ), 'text.color': ( 'abc.color', 'suptitle.color', 'tick.labelcolor', 'title.color', 'leftlabel.color', 'rightlabel.color', 'toplabel.color', 'bottomlabel.color', ), } for key, params in mpl_to_proplot.items(): if key in kw_params: value = kw_params[key] for param in params: kw_proplot[param] = value return kw_proplot
fec171caef3562344ee86684edc944b0d08af3f3
709,906
def rename_to_monet_latlon(ds): """Short summary. Parameters ---------- ds : type Description of parameter `ds`. Returns ------- type Description of returned object. """ if "lat" in ds.coords: return ds.rename({"lat": "latitude", "lon": "longitude"}) elif "Latitude" in ds.coords: return ds.rename({"Latitude": "latitude", "Longitude": "longitude"}) elif "Lat" in ds.coords: return ds.rename({"Lat": "latitude", "Lon": "longitude"}) elif "grid_lat" in ds.coords: return ds.rename({"grid_lat": "latitude", "grid_lon": "longitude"}) else: return ds
18647e3bbf82bae9d02db3e965c0ddfd51ddd6dd
709,907
def get_smallerI(x, i): """Return true if string x is smaller or equal to i. """ if len(x) <= i: return True else: return False
1588ef998f4914aa943a063546112766060a9cbf
709,908
def unfold(raw_log_line): """Take a raw syslog line and unfold all the multiple levels of newline-escaping that have been inflicted on it by various things. Things that got python-repr()-ized, have '\n' sequences in them. Syslog itself looks like it uses #012. """ lines = raw_log_line \ .replace('#012', '\n') \ .replace('\\n', '\n') \ .splitlines() return lines
9e23bdd82ac15086468a383a1ef98989aceee25e
709,909
def helperFunction(): """A helper function created to return a value to the test.""" value = 10 > 0 return value
2c4f2e5303aca2a50648860de419e8f94581fee7
709,910
from datetime import datetime def ts(timestamp_string: str): """ Convert a DataFrame show output-style timestamp string into a datetime value which will marshall to a Hive/Spark TimestampType :param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format :return: A datetime object """ return datetime.strptime(timestamp_string, '%Y-%m-%d %H:%M:%S')
1902e75ab70c7869686e3a374b22fa80a6dfcf1a
709,911
def nl_to_break( text ): """ Text may have newlines, which we want to convert to <br /> when formatting for HTML display """ text=text.replace("<", "&lt;") # To avoid HTML insertion text=text.replace("\r", "") text=text.replace("\n", "<br />") return text
d2baf1c19fae686ae2c4571416b4cad8be065474
709,912
import requests import logging def get_page_state(url): """ Checks page's current state by sending HTTP HEAD request :param url: Request URL :return: ("ok", return_code: int) if request successful, ("error", return_code: int) if error response code, (None, error_message: str) if page fetching failed (timeout, invalid URL, ...) """ try: response = requests.head(url, verify=False, timeout=10) except requests.exceptions.RequestException as exception: logging.error(exception) return None, "Error fetching page" if response.status_code >= 400: return "error", response.status_code return "ok", response.status_code
f7b7db656968bed5e5e7d332725e4d4707f2b14b
709,913