content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import jinja2
def make_jinja_env(templates_dir):
"""
Create the default Jinja environment given the template folder.
Parameters
----------
templates_dir : str or pathlib.Path
The path to the templates.
Returns
-------
env : jinja2.Environment
The environment used to r... | 79d03ae0aeaf7dafed04001e44b2446756313444 | 662,749 |
def get_guideseq_genes():
"""
for this to work, there needs to be a column in the pandas dataframe called "Target gene"
N.B. These are nto really all genes, but we're using that to streamline with Azimuth
"""
return ['RNF2', 'FANCF', 'EMX1', 'VEGFA_site1', 'VEGFA_site3',
'HEK293_sgRNA4',... | 2382873dd52260764e3317a073ed60b025852b77 | 662,750 |
def p_test_loc_uty(α_spt, p_lt, p_li, p_e):
"""Local test pressure unity check.
Reference:
DNVGL-ST-F101 (2017-12)
sec:5.4.2.1 eq:5.6 p:93
(local_test_press_unity)
"""
p_lt_uty = (p_li - p_e) * α_spt / p_lt
return p_lt_uty | eb3f7886422e666381646181c10858d6db68d16b | 662,751 |
def adapt_state_dict(to_load, to_receive):
"""
Adapt distributed state dictionaries to non-distributed
"""
iterator = zip(list(to_load.keys()),
list(to_receive.keys()))
for kl, kr in iterator:
if kl != kr:
kl_new = kl.replace('.module', '')
assert kl_new == kr
to_load[k... | ce6e0f1023564685e0a4b05fe3225634af39d736 | 662,752 |
def _generator_transfer(m, t):
"""
Constraint rule for electricity generation in generator
@ In, m, pyo.ConcreteModel, model containing problem
@ In, t, int, time indexer
@ Out, constraint, bool, constraining evaluation
"""
return - m.elec_generator_production[0, t] == 2.0 * m.elec_generator_produ... | 892e19da1a01b5118e183914aa9c1f15ea2ef78f | 662,753 |
def getSparkFrameFromCSV(sparkSession, localFileSystemPath, selectionColumns=None):
"""
This function returns a sparkSession dataframe from the provided csv file path
Syntax:
status, message, df = getSparkFrameFromCSV(sparkSession, "/path/to/data/dataset.csv")
Args:
sparkSessio... | 813cebcb040448776c9466bce7de56ffd13c65c9 | 662,754 |
from typing import List
import pathlib
from typing import Dict
from typing import Any
import pickle
def _open_hydra_pickles(paths: List[pathlib.Path]) -> Dict[str, Any]:
"""Open pickles in directory of Hydra log and return dict of data.
Parameters
----------
paths : List[pathlib.Path]
Paths t... | fc5b187549251fc7aba7e711b64551e254bfde8d | 662,755 |
def jaccard_distance(context_tokens: list[str], category_tokens: list[str]):
"""Simple function for calculating Jaccard Distance
Args:
context_tokens (list[str]): List of context words (i.e. target words)
category_tokens (list[str]): List of words in category
Returns:
[float]: Valu... | 490c516f6e3136a736d3e420d2061c6c221d1730 | 662,756 |
def area_triangle(base, height):
"""
Calculate the area of a triangle.
param "base": width of the triangle base
param "height": height of the trianble
"""
return base*height/2 | 3b8db9723baec6f203d23a53ee6d8d44e0c6c90c | 662,757 |
def sides_split(addr_edge_df):
"""Split tigerline dataframes into sides
Parameters
----------
addr_edge_df: pd.DataFrame/tigerline dataframe with address features & edges data
"""
l_addr_edge_df = addr_edge_df.copy()
r_addr_edge_df = addr_edge_df.copy()
l_addr_edge_df = l_addr_edge_df.d... | c36d5153226a26a5a0c533c4380f10edd594d847 | 662,758 |
def which_ids_have_tag(ids, cur, tag = '940'):
"""
:type ids: set
:type cur: psycopg2.extensions.connection
:param tag: str
:return: set
"""
cur.execute("SELECT record from metabib.real_full_rec WHERE tag = '940';")
ids_having_tag = set()
for record in cur:
ids_having_tag.ad... | 712f9bb85e5013fd99d38741faa524006b079fb1 | 662,759 |
def get_vars(varstr):
"""Gets 2d variable labels from a single string"""
variables = ['x', 'y', 'z', 'px', 'py', 'pz', 't']
#all_2d_vars = {}
for var1 in variables:
for var2 in variables:
if(varstr == f'{var1}{var2}'):
return [var1,var2] | 22afb8040276879bd7b468bcdd84633b5ef9a0d5 | 662,760 |
def query(port, prop, repo=False):
"""Query q property of a package."""
args = ("pkg", "rquery" if repo else "query", port.attr["pkgname"])
if prop == "config":
args += ("%Ok %Ov",)
else:
assert not "unknown package property '%s'" % prop
return args | 0d7d7a7f58d7d207d26b5e876c95efda35f1b70f | 662,761 |
import argparse
def parse_args(args):
"""returns the arguments the user gave"""
parser = argparse.ArgumentParser(description='manage a cad project')
parser.add_argument('command', choices=['add'],
help='the cm command to run')
parser.add_argument('options', nargs='*',
... | e0a368e76833cb0e2581083e88fcf492783cd2d0 | 662,762 |
def classifiers2string(li):
"""
Shortens the list of classifiers into a string.
@param li list
@return string
Example::
['Development Status :: 4 - Beta', 'Programming Language :: Python',
'Programming Language :: Python :: 3', 'Programming Language :: Pytho... | 4cbd558080e7617ab143ae688d13fa494bd25af0 | 662,763 |
def get_unique_repo_urls(vulnerability_entries):
"""
Retrieves a unique list of repository urls sorted by frequency.
:param vulnerability_entries:
:return:
"""
unique_repo_urls = {}
for entry in vulnerability_entries:
if entry.Vulnerability is None:
continue
commi... | 10cfadd6b61249656c3cf555a86596b9635eca17 | 662,764 |
def next_event_name(trace: list, prefix_length: int):
"""Return the event event_name at prefix length or 0 if out of range.
"""
if prefix_length < len(trace):
next_event = trace[prefix_length]
name = next_event['concept:name']
return name
else:
return 0 | f8e01a7ad8795c97ac4909f0996c70a8236916b4 | 662,765 |
def is_xlsx(filename: str) -> bool:
"""Checks if a filename suggests a file is an .xlsx file"""
return filename.endswith(".xlsx") | 4265f1c2743c9d0dc609d29ccafdcab273f034ae | 662,766 |
def update_mean(mean, n, x, remove=False):
"""Calculates the updated mean of a collection on adding or removing an element. Returns 0 mean if updated number of elements become 0.
Args:
mean (float): current mean of the collection
n (int): current number of elements in the collection
x (... | 3e4f44638c5b3f393b361241558058b95d377987 | 662,767 |
def rule_nr_to_rule_arr(number, digits, base=2):
"""Given a rule `number`, the number of cells the neighbourhood has
(as `digits`) and the `base` of the cells, this function calculates the
lookup array for computing that rule.
>>> rule_nr_to_rule_arr(110, 3)
[0, 1, 1, 1, 0, 1, 1, 0]
>>> rule_nr... | 6b9bff8b9c038bd8a397b1b99841cde469fe3665 | 662,768 |
def int_enum(cls, val):
"""Get int enum value.
Parameters
----------
cls : `type`
Int enum class.
val : `int` or `str`
Name or value.
Returns
-------
`IntEnum`
Raises
------
ValueError
"""
if isinstance(val, str):
val = val.upper()
t... | d2a53e12a21749589e23b6688241600baed8450e | 662,769 |
def cummulative_sum(x):
"""Returns the cummulative sum of elements of a list."""
# Create a copy of list x.
output = x[:]
for i in range(len(output) - 1):
output[i + 1] += output[i]
return output | 63a571720bf13e9e3ed78b1a94e3527d16f70c55 | 662,770 |
def rivers_with_station(stations):
"""Returns a set with the names of rivers
that have a monitoring station
"""
rivers = set()
for station in stations:
if station.river != None:
rivers.add(station.river)
return rivers | 2efb43270f8401c773eefbf7621fb7355f795848 | 662,771 |
import requests
import os
import logging
def download_file(url, output_path):
""" download a file from a url, save in output_path """
try:
r = requests.get(url, stream=True)
r.raise_for_status()
output_folder = os.path.dirname(output_path)
if not os.path.exists(output_folder):
... | b575fd752a1e1d01aac0dfdbe219d9935c4a895c | 662,772 |
def author_media_location(instance, filename):
"""Return the location of a stored media file for an Author."""
author_id = instance.id
image_type = filename.rpartition(".")[2]
return f"workflow_system/authors/{author_id}/profileImage.{image_type}" | 2484b33cd1535d103bc7f711573a8ca7ff551a8c | 662,773 |
def count_morphemes(X_data):
"""
count the number of morphemes
:param X_data:
:return:
"""
count = 0
for sent in X_data:
for morph in sent:
if morph != 0: #? why 0?
count += 1
return count | abe4c0697be1f74802f75b238628a6679d3d060e | 662,774 |
import numpy
def GaussianRegressionMAE_uniform_bars(self, data, avg_labels):
""" Use the class probabilities to generate a better label
If the computation of the class probabilities were perfect,
(and if the Gaussians were just a delta???), then the output value
minimizes the mean average error
s... | 942ea1d90051a68b6b43757431b64c9eb125ecea | 662,775 |
def get_sub_image_coords(coords, region_size, x_parts, y_parts):
"""
If an image is divided into sub_images, return a list of coordinates
for all the sub-images.
Parameters
==========
coords: list of floats, [long,lat]
region_size: float, size of square image in degrees long,loat
x_part... | 8dbb30a11772e9e62c521f36170e3ddbd4a2c6ab | 662,776 |
import requests
import json
def parse(domains):
"""
This function performs a request to threatcrowd and after having
parsed its output returns a cleaned list of unique domains
Args:
domains -- the list of input domain to query
Returns:
a cleaned list of unique subdomains obtained after q... | 52e58c417236b56654258b4950ed0d304a999f5d | 662,777 |
def nplicar(fator, *args):
"""
-> Multiplica cada argumento pelo fator e retorna cada resultado.
:param fator: É número que vai multiplicar cada argumento, como na tabuada.
:param args: Pode ser um argumento, vários ou uma variável. Se for uma variável
é preciso colocar um '*' antes.Ex.: nplicar(fat... | a3a34e8c5a92f9dd33233cfd754321c87e5f892f | 662,778 |
import re
def remove_extra_whitespace_tabs(text):
"""
Removes extra whitespaces and remove_extra_whitespace_tabs
"""
#pattern = r'^\s+$|\s+$'
pattern = r'^\s*|\s\s*'
return re.sub(pattern, ' ', text).strip() | 1364ef6399d94af68f34f5f2414fdcd093e6ac1e | 662,779 |
from datetime import datetime
def today():
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
labore et dolore magna aliqua. Ut enim ad minim veniam,
nisi ut aliquip ex ea commodo consequat. Duis aute irure
esse cillum dolore eu fugiat nulla pariatur. Excepteur
culpa qui officia dese... | 2383c04a955a4afba971f2543fa9f8483bd5b909 | 662,781 |
def create_dicts_of_connections(set_proj_nodes, set_no_proj_nodes, neighbors_dict):
"""
a function that creates 3 dictionaries:
1. dict_node_node (explained below)
2. dict_node_enode (explained below)
2. dict_enode_enode (explained below)
:param: set_proj_nodes: Set of nodes that are in the embe... | a9728b8ab21b100b0682f7ac2effe3690e0783e1 | 662,782 |
def p() -> float:
"""``p`` in the top-."""
return 0.9 | bb83d4a5793f0322d37a94dc5ee8655d4c035761 | 662,783 |
def validate_attr(attr, table_cols, attr_label, table_label):
"""Check if the attribute exists in the table."""
if attr not in table_cols:
raise AssertionError(attr_label + ' \'' + attr + '\' not found in ' + \
table_label)
return True | 7d9b7d87098908754e4301b42900a8cbd80384cd | 662,784 |
def updated_dict(d, only_existing=True, **updates):
"""
Update dictionary `d` with `updates`, optionally changing `only_existing` keys.
* d: dict
* only_existing: do not add new keys, update existing ones only
* updates: dict
:return: updated dictionary
"""
d = d.copy()
if only_exis... | e33e77cf5cc1b626ea88ed831726265f4f4423b3 | 662,785 |
import re
def remove_empty_line (content):
"""remove multi space """
r = re.compile(r'''^\s+$''', re.M|re.S)
s = r.sub ('', content)
r = re.compile(r'''\n+''',re.M|re.S)
s = r.sub('\n',s)
return s | 01104d8d849bd763a084ed945ab8c95553bee3d1 | 662,786 |
def simple_matrix_print(matrix):
"""Simple string to display a floating point matrix
This should give the same output on multiple systems. This is
needed because a simple "print matrix" uses scientific notation
which varies between platforms.
Only 4 decimal places are used to avoid false test fai... | 8805fb5eccddeb82a72195280b31d81e7469afb6 | 662,787 |
import time
import os
def check_file_dates(folder, creation=True):
"""Returns oldest and newest dates of all files in folder walk.
Dates can be creation dates or modification dates (creation=False).
Returns (oldest, newest) as floating point time in seconds since epoch.
written by Phil Wilmarth, OHSU... | c0c81a8c92f7c5242825a3cf83bcb8d0d19015f3 | 662,788 |
def filter_irr(df, irr_col, low, high, ref_val=None):
"""
Top level filter on irradiance values.
Parameters
----------
df : DataFrame
Dataframe to be filtered.
irr_col : str
String that is the name of the column with the irradiance data.
low : float or int
Minimum va... | 01c631ff14bd35d0377513910542fce907328551 | 662,789 |
def frange(min_val, max_val=None, increment=None):
"""Allows range() with floats
Adapted from http://code.activestate.com/recipes/66472
"""
if max_val == None:
max_val = min_val + 0.0
min_val = 0.0
if increment == None:
increment = 1.0
range_list = []
while 1:
next = min_val + len(range_l... | 3a473d8ec7ad20293c6e27d4e95500565bbd6d93 | 662,790 |
def status(request, response, code):
"""Alter the status code.
:param code: Status code to use for the response."""
response.status = code
return response | aa3a532fc65e0f9ff143b6386e0633cabb56240f | 662,791 |
def plmdca_param_metadata(plmdca_instance):
"""Generates a list of plmDCA metadata that can be added as
an output file header.
Parameters
----------
plmdca_instance : PlmDCA
An instance of PlmDCA class.
Returns
-------
metadata : list
A list of metadata... | c525fdbe221ac483ad5aa057543cf004934ba8b1 | 662,792 |
def break_camelcase_pythonic(string: str) -> str:
"""Breaks camelcase string (pythonic).
Args:
string (str): as string
Examples:
>>> assert break_camelcase_pythonic("helloWorld") == "hello World"
"""
return "".join(f" {item}" if item.isupper() else item for item in string) | 5eb171187ea1b8d7c676e0c8194922e9f545a8bd | 662,793 |
import argparse
import torch
def parse_args():
"""
:return: args: experiment configs, device: use CUDA or cpu
"""
parser = argparse.ArgumentParser(description='Traning a fully connected network to classify speech recording phonemes.')
parser.add_argument('--batch_size', type=int, default=32, met... | 13fe796b70deabebb5d9ba486d91de3d6f6921b7 | 662,794 |
import pickle
def load_results_dict(pickle_filename):
"""
Load results in a dict that have been pickled.
Parameters
----------
pickle_filename : str
DESCRIPTION. String with the filename we are loading results from
Returns
-------
results_dict : dict
DESCRIPTION. Dict... | bdc6c11b8507266a28e7f0562e9bc8155ffdf3e3 | 662,795 |
def get_clean_block(block):
"""Clean up unicode characters and common OCR errors in blocks"""
replacements = {'fi': 'fi',
'fl': 'fi',
'—': '-',
"’": "'",
"‘": "'",
'”': '"',
'“': '"',
... | 7a769ebeb1992070286e1d57bb93421c68c79afc | 662,796 |
def read_diff_file(filename):
"""Read the diff file in its entirety."""
with open(filename) as fd:
content = fd.read()
return content | f2d22ba3e69870e2e588fc1df81cd061253e5663 | 662,797 |
def _cnncfp_avg(data):
"""Global average pool"""
return data.mean((1, 2)) | 29e425799661b38e8aa8f99d141b5255805ad446 | 662,798 |
def remove_multicollinearity_by_coefficient_threshold(df, method = 'spearman', coefficient_threshold = 0.7):
"""
Uses the correlation between features and a specified threshold to
identify and remove collinear/multicollinear features.
Args:
df ([pandas.DataFrame]):
A dataframe tha... | 3de2fcb1ffe2c1d41af5ee62aa2a437e5c7baf41 | 662,799 |
def get_dir_edges_from_c_to_tars(c_to_tars):
"""
Returns tuple of all allowed directed edges (c, t) where c control
and t target.
Parameters
----------
c_to_tars : dict[int, list[int]]
a dictionary mapping j in range(num_qbits) to a list, possibly
empty, of the physically allowe... | 8df730c2b5380989ca19bba9928a7051eead0b60 | 662,801 |
import torch
def initial_state(hparams):
""" Samples a random initial state. """
B = hparams.batch_size
L = hparams.lattice_size
num_particles = round(hparams.concentration * L**2)
# choose sites that get a particle. Bose-Hubbard allows multiple particles per site.
if hparams.potential.starts... | 3b2547e87fe0898692957b426e175e223321f225 | 662,802 |
import os
def handle_img(block):
"""
Extracts information from an image block (from a README doctree).
Args:
block: An image doctree block
Returns: A dictionary with the extracted information
"""
ret = {}
ret['type'] = 'image'
ret['uri'] = '_static/' + os.path.join(*block['ur... | de511cfd6b091050c2051ae8c7303fc4ee311755 | 662,803 |
def seconds_to_str(s: int) -> str:
"""
Returns a string describing the given number of seconds in a human-readable form.
"""
s = abs(s)
result = []
days = s // 86400
if days:
result.append('{} day{}'.format(days, '' if days == 1 else 's'))
hours = s // 3600 % 24
if hours:
... | 0ee56882c80082a8621aeced9ba8364a6addc631 | 662,804 |
import collections
import re
def key_assignments_from_file(file_path):
"""
Return the key assignments found in the given file, as a
collections.OrderedDict mapping each key to its text meaning.
The file syntax and semantics are detailed in
AnnotateShell.do_load_keys().
This function is meant... | 517afa474b8fae53b650b7f48ff392714bd0ff1f | 662,805 |
def get_all_user_ids(tweets, user_mentions):
"""Creates a list of all user_ids in tweets and user_mentions"""
id_set = set()
# the user_id of the target
if tweets: id_set.add(tweets[0].user_id)
id_set |= set([m.user_id for m in user_mentions])
id_set |= set([t.in_reply_to_user_id
for... | 7cd0317e8a7b579802da3eef9e29decf0ab40bca | 662,806 |
def get_service_instance_tag_value(inst, svc_client, svc_info, tag_name):
"""
Retrieve given tag value from the given instance
"""
# Requires another API call
if svc_info['DiscoverTags']:
cmd = 'svc_client.' + svc_info['DiscoverTags']
if svc_info['DiscoverTagsInstParm']:
... | 513c3d34c51813521570f223843fa67ee0bdf86a | 662,807 |
def is_signed_int(num_str):
"""
Args:
num_str (str): The string that is checked to see if it represents a number
Returns:
bool
"""
# if the num_str is a digit, that means that there are no special characters within the num_str
# therefore making it a nonneg int
# to check if... | cbfe96668defea7f4681cbe50edcc7f8e1c0526a | 662,808 |
def _dec_out_formatter(out):
"""Converts PyTorch int sequences (word ids) to Python integers."""
res = []
for seq in out:
tmp = []
for elem in seq:
elem = elem.to('cpu').numpy()
if len(elem.shape) == 0:
elem = elem.item()
tmp.append(elem)
... | 20459c5549426601713374ebbca1fcfe6aa95e27 | 662,809 |
def build_meta_header(host, meta_header):
"""
Progressively build the meta header host by host
:param host: current host to add to meta header
:type host: dict
:param meta_header: meta header to build
:type meta_header: dict
:return:
"""
# If found host doesn't exists in dict, we cr... | 45a1d549f5b9b8577c883d3f58f879d6622b3e7f | 662,810 |
import json
def load_map(map_path):
"""Load map in json format and return a dic
Args:
map_path (str): Path to json file
Returns:
map_dict: Map as dictionary.
"""
with open(map_path) as map_handle:
map_dict = json.load(map_handle)
return map_dict | 208b4380912c832d8742648c5b0169c9b31a26dc | 662,812 |
def max_chunk_size_MB(ds):
"""
Get the max chunk size in a dataset
"""
def size_of_chunk(chunks, itemsize):
"""
Returns size of chunk in MB given dictionary of chunk sizes
"""
N = 1
for value in chunks:
if not isinstance(value, int):
v... | f50494424f896cafb00eacac1dfcf1a74d2e8ce9 | 662,813 |
import re
def __capitalize_hexadecimals(source):
""" Capitalize all hexadecimal strings
:param source: The source CSS string
:return: The CSS string with all hexadecimal values capitalized
"""
def found(match):
return match[0].replace(match[1], match[1].lower())
return re.sub(r'... | 5811aa6347cfe945f5d0b4aa1f841eb7cd5ed16c | 662,814 |
def squash_to_unit_interval(x: float, constant: float) -> float:
"""Scales non-negative x to be in range [0, 1], with a squash."""
if constant <= 0:
raise ValueError('Squash constant must be greater than zero.')
if x < 0:
raise ValueError('Squash can only be performed on a positive value.')
return x / (... | 0a99803cfad0b82f15ebefe1a59ef24cfd8bbd33 | 662,815 |
def _get_es_domains(client):
"""
Get ES domains.
:param client: ES boto client
:return: list of ES domains
"""
data = client.list_domain_names()
domain_names = [d['DomainName'] for d in data.get('DomainNames', [])]
# NOTE describe_elasticsearch_domains takes at most 5 domain names
d... | 351f33d9dce707f93fbd99649e08b4b3242d30b5 | 662,816 |
import argparse
def cli() -> object:
"""Get arguments from command line"""
parser = argparse.ArgumentParser(description="Sudoku solver")
parser.add_argument("-d", "--display", help="Graphical display",
action="store_true")
parser.add_argument("-s", "--scan",
... | 0706357960d5d8fcbd38e87036ec12402ee11bb6 | 662,817 |
import os
def chk_mkdir(dir,warning=False):
"""(chk_mkdir):
This function checks whether a directory exists and if not creates it.
"""
if not os.path.isdir(dir):
tmp_str = "mkdir -p " + dir
os.system(tmp_str)
elif warning:
return False | 04ecddb9ab05929848fe52e38c6d22236251fff2 | 662,818 |
def create_vocabulary_list(data_set):
"""
创建一个包含在所有文档中出现的不重复词的列表
:param data_set:
:return:
"""
# 创建一个空集
vocabulary_set = set([])
for document in data_set:
# 创建两个集合的并集
vocabulary_set = vocabulary_set | set(document)
return list(vocabulary_set) | 75103282de722aa2cf1e805126d6b9effa82a0f5 | 662,819 |
def _extract_phospho_islands(phospho, start, end):
""" phospho = [(3, 4),]; start = [1, ]; end = [5, ] """
last_lo_site = 0
last_hi_site = 0
last_seq_start = 0
last_seq_end = 0
island_id = 0
islands = {}
phospho_sequence_positions = sorted(set(zip(phospho, start, end)))
for phos_site... | aa387781eb61ad83f8e09d7d5e37ee0bb957e908 | 662,820 |
def get_node_vif_ids(task):
"""Get all VIF ids for a node.
This function does not handle multi node operations.
:param task: a TaskManager instance.
:returns: A dict of Node's neutron ports where keys are
'ports' & 'portgroups' and the values are dict of UUIDs
and their associated VIFs... | 7e2675232fdf82072b87fb6fedc06cdb965c689e | 662,821 |
def MinMaxScaler(data, low, high):
"""
@topic: Rescale 2D matrix into given ranges.
@parameters: data (2d matrix), low/high (Scalar).
@return: scaled data (2d matrix).
"""
data_max, data_min = data.max(axis=0), data.min(axis=0)
data_std = (data - data_min) / (data_max - data_min + 0.00001)
... | 6661e9f12edea3f59c9f28e0b9ab7a2583eaaadb | 662,822 |
import random
def uniformFloat(lo, hi):
"""
Return a number chosen uniformly from the range [lo, hi).
"""
return random.uniform(lo, hi) | 5712a90409df6ad269a5e61869d6cadfbf672225 | 662,823 |
def levenshtein(s, t):
"""
Computes the levenschtein distance between two strings of text
This is borrowed code and has been checked, but stay careful
:param s: first string of text
:param t: second string of text
:return: a distance measure, not normalized
"""
if s == "":
return... | 0acfbad0fcbc4bde79bc8d9fc379655c40b6e466 | 662,824 |
def read_file_list(input_file):
"""
:param infer file content:
0 xxx/xxx/a.jpg 1920 1080 0 453 369 473 391 1 588 245 608 268
1 xxx/xxx/b.jpg 1920 1080 1 466 403 485 422 2 793 300 809 320
...
:return image path list
"""
image_file_list = []
with open(input_file, "r") as fs... | 094a5c791c38df922b66508dc480954928495a72 | 662,825 |
from re import findall
import subprocess
def running_proc(daemon):
"""
Takes (str) daemon
Returns (int) proc, which is the number of processes currently running
"""
process = subprocess.run(
["ps", "aux"],
capture_output=True,
check=True,
)
outpu... | 074a22aa82daa04236d7b1ac26001122166ab6e9 | 662,826 |
import random
import time
def get_pick(pick_status):
"""
This function takes one argument of variable type and returns an intger.
It checks to see if it's the first round and randomly chooses a starting player
if it is the first round. Otherwise, it simply returns the argument passed (an integer determining
whose... | f976edae49e76250a996a2647133588ffa728faf | 662,827 |
def main():
""" The idea is to create a dictionary with the following items:
(x, y): {wireID: weight, ...}
for each point (x, y) touched by at least one wire.
The length of the {wireID: weight, ...} dict gives info on overlaps
The weight field can store other useful information to fi... | efb6cb9f3c8da5060573a19a8a954f8845c0d028 | 662,829 |
def split( d ):
"""
divide el dicionario en varios dicionarios
Params
======
d: dict
Results
=======
map: generador con los dicionarios
Examples
========
>>>list( split( { "a": "1", { "b": "2" } } ) )
[ { "a": "1" }, { "b": "2" } ]
"""
return map( lambda x: { x... | cda120479e0b99f9551c3c417ab4503a60e637a9 | 662,830 |
import logging
def getLogger():
"""
Get the default kapture logger.
:return: logger
"""
return logging.getLogger('kapture') | 8d301a64a38e5aba0146394875769fe1866e811a | 662,831 |
def _score_sentences(tf_idf_matrix) -> dict:
"""
score a sentence by its word's TF
Basic algorithm: adding the TF frequency of every non-stop word in a sentence divided by total no of words in a sentence.
:rtype: dict
"""
sentenceValue = {}
for sent, f_table in tf_idf_matrix.items():
... | d95a1d154ca50a696e4c472d4d4b99fb988b825f | 662,832 |
def func_name(func):
"""
Return the name of the function, or None if `func` is None.
"""
return None if func is None else func.__name__ | 4d33cdaf788101de2d5e2dfecde66cebbc589e95 | 662,833 |
def __findAttr(s, i):
"""gone back till a namespace and returns the word in between"""
l = ""
i -= 1
while s[i] != " ":
l = "".join((l, s[i]))
i -= 1
# print(l)
return l[::-1] | ecaa1114d91d270f213e2b66d0be0b40d06f3df8 | 662,834 |
def is_ragged(array, res):
"""Is 'array' ragged?"""
def _len(array):
sz = -1
try:
sz = len(array)
except TypeError:
pass
return sz
if _len(array) <= 0:
return res
elem0_sz = _len(array[0])
for element in array:
if _len(element... | 5856a1ccb66596e740a786f60a878771aa73f8dd | 662,835 |
import hmac
import base64
import hashlib
def sign_hmac(secret, payload):
"""Returns a base64-encoded HMAC-SHA1 signature of a given string.
:param secret: The key used for the signature, base64 encoded.
:type secret: string
:param payload: The payload to sign.
:type payload: string
:rtype: ... | a238733a624fdb73896c2635eb6fc1d5018b4200 | 662,836 |
import math
def homogenize( E, G, NU, D ):
"""
The function takes parameters of a composite material and converts it to
the properties of an isotropic material.
Developer: Christoph Winter ( christoph.winter@tum.de )
:param E: Elastic Modulus. 2D list of floats
:param G: ShearModulus. 2D list... | cc144593ca48ef52246011d9fd928cbf0499e465 | 662,837 |
def attrs_inventory_test():
"""Provide function for high-level attrs Inventory consistency tests."""
def func(inv, source_type):
"""Perform high-level attrs Inventory consistency test.
`inv` is an Inventory instance.
`source_type` is a member of the `soi.inventory.SourceTypes` enum.
... | b0c38a96c2bc15540828aea3d099063b532527e5 | 662,838 |
import subprocess
def sysbench():
"""
get the patch for sysbench so it will work on ubuntu/redhat
"""
output = str(subprocess.check_output(['which','sysbench'])).replace("\n","")
return output | 2e14de90281f28f61ff15ed877cf460496b7d1cb | 662,839 |
def find_short(s):
""" Given a string of words, return the length of the shortest word(s)."""
return min(len(x) for x in s.split()) | 391e4af606f3ce7b1c16d3174b489baac256d7ce | 662,840 |
def traverse_config_get(target, *args):
"""
>>> traverse_set({'level': {'one': 1}}, 'level', 'one', 42)
{'level': {'one': 42}}
"""
current = target
last = target
for level in args:
last = current[level]
current = last["config"]
return last["arg"] | 8d81847ee75821b73d9baa7e3222c8c3fa3af18c | 662,841 |
def arraytize(v):
"""
convenience function that "transforms" its arguments
into a list. If the argument is already a list, returns
it. If the argument is None, returns an empty list.
Otherwise returns [argument].
"""
if v is None:
return []
try :
return list(v)
excep... | 38810e67cc10a14fe27dc4991d736b8a77fe6843 | 662,843 |
def get_object_position(action_manager, arm_name, param):
"""
オブジェクト位置情報を取得
"""
_, data = action_manager.arm_operation(arm_name, "get_object_position", param)
return data["position"] | d88da1d355791a4a9243596fa679172d779df8da | 662,844 |
def sort_freqs(freqs):
"""Sort a word frequency histogram represented as a dictionary.
Parameters
----------
freqs : dict
A dict with string keys and integer values.
Return
------
items : list
A list of (count, word) pairs.
"""
items = freqs.items()
items.sort(key =... | 74962857ba48cfdb19bae2d584212b305be439f8 | 662,845 |
def get_precision(n):
"""
Get precision.
Parameters
----------
n : dict
Confusion matrix which has integer keys 0, ..., nb_classes - 1;
an entry n[i][j] is the count how often class i was classified as
class j.
Returns
-------
float
precision (in [0, 1])... | a671394a7b388f7c47a56e8b8a0f726d143e2351 | 662,846 |
def get_clean_name(name):
"""
A convenience function for naming the output files.
:param name: A name of the target file.
:returns: The name suffixed with "_clean" and the file extension.
"""
name = name.split(".")
name = name[0] + "_clean." + name[1]
return name | d9bd9d1222edb033d3108c4a9365addeaca5aacb | 662,847 |
def add_unary_magic_methods(np_funcs, translate_func):
"""Class decorator to add unary magic methods using NumPy to the class."""
def wrapper(cls):
for fname, np_func in np_funcs:
def magic_func(self, np_func=np_func):
return translate_func(self, np_func)
setatt... | d70f5bc2b619ab5e0fe49cc3855321b3846b0f39 | 662,849 |
def reformat_trademarks(data):
"""
Reformats the trademarks data to global standard.
:param data: unformatted data
:return: Formatted data
"""
for key,val in data.items():
if val == ["-"]:
new_val = []
else:
new_val = [{
"Name": ele[0],
... | 79a17a56800bf41a40bbb5fabaf39188d48e03ba | 662,850 |
import mpmath
def mean(df, nc):
"""
Mean of the noncentral t distribution.
"""
# XXX Require df > 1.
with mpmath.extradps(5):
df = mpmath.mpf(df)
nc = mpmath.mpf(nc)
logm = (mpmath.log(nc)
+ mpmath.log(df/2)/2
+ mpmath.loggamma((df - 1)/2)
... | 0d7975b82387549f85d74565c163b26dea4322fb | 662,851 |
import os
def use_tm():
"""Flag whether transaction manager is used.
"""
return os.environ.get('CONE_SQL_USE_TM') == '1' | 891e30adec0e65316caf39d9b60e3af1e9594845 | 662,852 |
def quality_score_to_string(score: int) -> str:
"""Returns the string representation for the given quality score.
We add 33 to the score because this is how the quality score encoding is
defined. Source:
https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Informatics/BS/QualityScoreEncoding_s... | 631c5742c9c111b3f2da41c77e23b60843121aee | 662,853 |
def news_section(soup):
"""Función que recibe un objeto soup de una categoría determinada,
y devuelve los links de todas las noticias pertenecientes a ella"""
lista_notas =[]
# Get featured article link
featured_article = soup.find('div', attrs={'class': 'featured-article__container'})
if f... | c18db0b0266cd73aea4366f65171d0531a921ebd | 662,854 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.