content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import readline
def ask(text: str = '') -> str:
"""接受使用者輸入"""
readline.parse_and_bind("tab: complete")
if text:
print(f'\033[0;1m{text}\033[0m')
try:
select = input(' ❯ ')
except KeyboardInterrupt as e:
print()
print()
print("Cancelled by user")
... | f3e8c9a2578095bbef676a3ab8794b7d02384a51 | 632,778 |
from typing import List
from typing import Any
def get_combinators(tp) -> List[Any]:
"""
Assume that constructor is annotated union.
Returns list of types
"""
return [
combinator
for combinator in tp.__args__[0].__args__
] | b276d4578e8da09574d0ef1587cd1c8970b3182c | 632,779 |
def get_standard_openings(power_name):
""" Returns a list of standard openings for a given power"""
return {
'AUSTRIA': (
['A BUD - SER', 'F TRI - ALB', 'A VIE - GAL'],
['A BUD - SER', 'F TRI - ALB', 'A VIE - TRI'],
['A BUD - SER', 'F TRI - ALB', 'A VIE - BUD'],
... | e843367a226865bb0daaf399b5b4cd4273605955 | 632,780 |
def rapl_timeline():
"""
Timeline of procfs report for the tests
"""
return [{ "timestamp": "2021-10-05T09:14:58.226", "sensor": "toto", "target": "all", "groups": { "rapl": { "0": { "7": { "RAPL_ENERGY_PKG": 5558763520.0, "time_enabled": 1000770053.0, "time_running": 1000770053.0 } } } } },
... | c70abb9e28f954f869a18a9a3ef55a6d80a9c73d | 632,782 |
def to_hyper_timestamp(dss_date):
"""
Format a date object from DSS to Tableau Hyper
:param dss_date: A DSS date value
:return: Tableau Hyper date value
"""
return dss_date | fa5120cda21414ca69ad1dd0f2a8db0178a7ff4b | 632,784 |
def tx_capacity_cost_rule(mod, g, p):
"""
Capacity cost for new builds in each period (sum over all vintages
operational in current period).
"""
return sum(
mod.TxNewLin_Build_MW[g, v]
* mod.tx_new_lin_annualized_real_cost_per_mw_yr[g, v]
for (gen, v) in mod.TX_NEW_LIN_VNTS_O... | b973293d05f4113d215a545a3815b3d825b75e22 | 632,785 |
from typing import Tuple
def get_int_bounds(type_str: str) -> Tuple[int, int]:
"""Returns the lower and upper bound for an integer type."""
size = int(type_str.strip("uint") or 256)
if size < 8 or size > 256 or size % 8:
raise ValueError(f"Invalid type: {type_str}")
if type_str.startswith("u")... | a749ae63c278e74dac818dc387618d5003326d53 | 632,786 |
def tf_to_10(x):
"""
Maps true/false to 1/0
"""
if x == True:
return 1
elif x == False:
return 0
return x | 8cec080002f6c6c41ba64a40fcea324658df1701 | 632,787 |
def _is_unpoly(self) -> bool:
"""Request is triggered by Unpoly"""
return (
'HTTP_X_UP_VERSION' in self.META
or 'HTTP_X_UP_MODE' in self.META
or 'HTTP_X_UP_TARGET' in self.META
or 'HTTP_X_UP_VALIDATE' in self.META
) | b203678a4fe0cadef120c8cb259d9287418e54d8 | 632,789 |
def get_directed_and_undirected_edges(adjacency_matrix):
"""
Given an adjacency matrix, which contains both directed and undirected edges,
this function returns two adjancy matrices containing directed and undirected edges separately.
Useful for plotting the difference causal graph.
Parameters
... | 01ba23d40ddf0866332163583f9aa16cc6bd95d9 | 632,790 |
def ignore_some_combinations(testcase, clock_domains, ft_clock, fifo_clock, data_width):
"""Special function to ignore some fixtures combinations"""
if (('SINGLE' in clock_domains) and ('48' not in fifo_clock)):
# no need to use multiple fifo clock values in the single domain mode
return True | 7ab366989778bd33540baaf0995cd1dcb950b8e2 | 632,791 |
import argparse
def parse_args():
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--analytics-project',
help='Project id where model will be run.',
required=True,
)
parser.add_argument(
'--training-iterations',
... | f1501dc552a18df5d2b547e9ae88fce780b4d0e1 | 632,792 |
import itertools
def sort_and_groupby(l, key=None):
"""Returns a generator of (key, list), sorting and grouping list by key."""
l.sort(key=key)
return ((k, list(g)) for k, g in itertools.groupby(l, key)) | 54640d9d6bd7828ac938298db3d0328d2b70f895 | 632,793 |
def objVal(c, v, s, l, Q, order, demand, objType):
""" calculate the objective value given the sample probability of each demand
:param c: purchase cost
:param v: salvage value
:param s: selling price
:param l: cost of lost sale
:param Q: true distribution of demand scenarios
:param order: ... | 740740c7ca4f6179a6fda94bf7b5fa86054606a1 | 632,794 |
def is_query(parsed_sql):
"""
Determine if the input SQL statement is a query.
Parameters
----------
parsed_sql: sqlparse.sql.Statement
SQL statement that has been parsed with ``sqlparse.parse()``.
Returns
-------
bool
True if statement type is SELECT and the second non... | 315baa60fa49a612c1f828135b3eab9c57e6c5ef | 632,795 |
import os
def get_string(name, default):
"""
Get an environment variable as a string.
Args:
name (str): An environment variable name
default (str): The default value to use if the environment variable doesn't exist.
Returns:
str:
The environment variable value, or... | cb9970edfb68613f109bd77066246fbc4bd35153 | 632,797 |
import re
def is_float(str_number: str):
"""
判断字符串是否浮点
:param str_number:
:return:
"""
if isinstance(str_number, float):
return True
value = re.compile(r'^[-+]?[0-9]+\.[0-9]+$') # 定义正则表达式
return value.match(str_number) | 2732f2f3b620f6402a63f7f53be57b14d6567e55 | 632,798 |
def BitStringToByteString(bs):
"""Convert a pyasn1.type.univ.BitString object to a string of bytes."""
def BitsToInt(bits):
return sum(v * (2 ** (7 - j)) for j, v in enumerate(bits))
return bytes(
bytearray([BitsToInt(bs[i:i + 8]) for i in range(0, len(bs), 8)])) | 2434b9546fb3227266c64a1ac8e5171d42f38001 | 632,799 |
def singleton_representer(dumper, data):
"""Converts openmm.app.internal.Singleton object into a yaml string."""
return dumper.represent_scalar('!openmm', data.__class__.__name__) | 15e87e012af926f1b5a6393aa1824317c156012e | 632,800 |
import sys
def redirect_std():
"""
Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu.
"""
stdin = sys.stdin
stdout = sys.stdout
if not sys.stdin.isatty():
sys.stdin = open("/dev/tty", "rb"... | ad7c7237f042c9c191d1dbb1ad2005893f2aea14 | 632,801 |
def getTransientStates(m):
"""Returns a list with the indices of the non-absorbing states of the matrix m"""
t= list(range(len(m)))
for r in range(len(m)):
if(sum(m[r])==0): t.remove(r)
return t | 6e824bc1815bd2e4682b49daa3c1aaaddff4544b | 632,802 |
import re
def email_validation_check(email):
"""
for email, valid syntax returns True, else False.
:param email:
:return:
"""
return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email)) | 0c40bf56ba023c2d309dc98922cdd56c24fe6ec1 | 632,803 |
def run_search(engine_list):
""" Run search in engine
@param engine_list List with engine, query and category
@retval False if any exceptions occurred
@retval True otherwise
"""
engine, what, cat = engine_list
try:
engine = engine()
# avoid exceptions due to in... | 92e5f24ccee6e297c8ff1429a13c0c1d72d594ea | 632,804 |
import operator
def docs_with_high_error_rate(corpus_statistics, min_error_rate=.2):
"""
References:
:func:`process_directory` or :func:`overview_report`
Args:
corpus_statistics (dict):
min_error_rate (int): default of .2. Values must be greater than `min_error_rate` for doc t... | 6f45068eb602d7a8a4b1ee571b5743577bd2ff86 | 632,805 |
def lerp(a, b, t):
""" blend the value from start to end based on the weight
:param a: start value
:type a: float
:param b: end value
:type b: float
:param t: the weight
:type t: float
:return: the value in between
:rtype: float
"""
return a * (1 - t) + b * t | 127ff551f81423c299e4434841dd141d449d57d1 | 632,806 |
from glob import glob
def insensitive_glob(pattern_glob, recursive=False):
"""
This function is the glob.glob() function that is insensitive to the case
Args:
pattern_glob: sensitive-to-the-case pattern
recursive: recursive parameter for glob.glob()
Returns:
insensitive-to-the... | 568855b0259321128b5c3219b6efbcbcd3861c30 | 632,808 |
from asyncio import iscoroutine
def make_repr(_class):
"""Create a user-friendly represention of an object."""
# Standard Library
def _process_attrs(_dir):
for attr in _dir:
if not attr.startswith("_"):
attr_val = getattr(_class, attr)
if callable(attr... | b8bf7b0596068007a126ba253a9fa3accf3a7dcc | 632,810 |
def randstrs(randstr):
"""Generate n unique random strings"""
def _get_randstrs(n):
return [randstr() for i in range(n)]
return _get_randstrs | dd919ce301b2605a73414a1ef223b4aba1ef0e95 | 632,811 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"line": integer,
"c... | 55725a2475190b393de90c2ec5acbcf51e63af15 | 632,812 |
def format_slack_message(table_name, metric, avg_time, increase, stddev, stddev_old):
""" Formats slack message using slack emojis.
:param table_name: BigQuery table name that was analysed.
:param metric: string with metric name.
:param avg_time: calculated average time for recent data of given metric.... | 67a188c48eb10790b5f36de3ffa914c5ee195e87 | 632,814 |
def comp_radius(self):
"""Compute the radius of the two circle that contains all the ventilation
ducts
Parameters
----------
self : VentilationPolar
A VentilationPolar object
Returns
-------
(Rmin, Rmax): tuple
Tuple of circle radius [m]
"""
self.check()
... | 1eb79db6409bf76db3e5c91d9c4d68b02d0a62fd | 632,815 |
def frequency_table(text, k):
"""returns frequency table for k_mers of length k in the text"""
d = {}
i = 0
while i <= len(text)-k:
pattern = text[i:i+k]
d[pattern] = d.get(pattern, 0) + 1
i = i+1
return d | 2e95d338a716345504245e52f377691c1c1d1b40 | 632,816 |
import sqlite3
def connect_db():
"""Connect to database funciton"""
sql = sqlite3.connect(
"/home/t/trainingWorkspace/flask_ultimate_orelly/database/data.db"
)
sql.row_factory = sqlite3.Row
return sql | 6fde6a1c8eb62115d9a29b89c67bdb38c7d2e6c1 | 632,817 |
def process_data(employee_list):
"""
Takes the employee list built by read_employees() and does a count of the Department data
"""
department_list = []
for employee_data in employee_list:
department_list.append(employee_data['Department'])
department_data = {}
for department_name ... | a7196226729a349d465e17334de66dadce42a6d4 | 632,818 |
import os
def get_schema_files(schemas_dirpath):
""" get list of js / json files resided in dirpath param. """
res = []
for fname in os.listdir(schemas_dirpath):
if fname.endswith('json') or fname.endswith('js'):
res.append(fname)
res.sort()
return res | ed2670fc0449fbebd7300dbf5dff32da3ce2a0b7 | 632,819 |
def CountOccurrences(pattern, bwt, starts, occ_counts_before):
"""
Compute the number of occurrences of string pattern in the text
given only Burrows-Wheeler Transform bwt of the text and additional
information we get from the preprocessing stage - starts and occ_counts_before.
"""
# Implement this function... | a8aa8a91d11e186c517f532c863b46ee11e9091f | 632,820 |
def is_tribe(parcels):
"""
Dummy for tribal areas.
"""
tribal_mpas = ['AK', 'FM', 'GR', 'SA', 'SN', 'TC']
return parcels['mpa'].isin(tribal_mpas).astype(int) | bc8074a881e196d2c5c8134a22da9eec1f2cf64d | 632,821 |
import os
def check_ext_mem(ext_mem_dir):
"""
Compute recursively the memory occupation on disk of ::ext_mem_dir::
directory.
Args:
ext_mem_dir (str): path to the directory.
Returns:
ext_mem (float): Occupation size in Megabytes
"""
ext_mem = sum(
... | e3c5416b990a8bdcf00b0e6a8102d77d03306a4c | 632,822 |
import copy
def merge(d1, d2):
""" Will merge dictionary d2 into dictionary d1.
On the case of finding the same key, the one in d1 will be used.
:param d1: Dictionary object
:param s2: Dictionary object
"""
d3 = copy.deepcopy(d1)
for key in d2:
if key in d3:
if isinstan... | 34cb18f3ad6ca3e732df6cd2422d01e7a71621b1 | 632,823 |
import re
def find_version():
"""Read version from db.py."""
regex = r"^ATRAM_VERSION = ['\"]v?([^'\"]*)['\"]"
with open("./lib/db.py", 'r') as f:
match = re.search(regex, f.read(), re.M)
if match:
return match.group(1)
raise RuntimeError("Unable to find version string.") | 04cc68e781e4e5d8b598b0b5bb8b4d5a8fbc230b | 632,824 |
from typing import List
import textwrap
def generate_build_file_contents(name: str, dependencies: List[str]) -> str:
"""Generate a BUILD file for an unzipped Wheel
Args:
name: the target name of the py_library
dependencies: a list of Bazel labels pointing to dependencies of the library
R... | 6714a8e214eb4d89614702643f5d900d864cbe53 | 632,825 |
def str_or_none(v, default=None):
"""Check if str."""
return default if v is None else str(v) | 0949163c3f4f72a67428f8cfbf574f07f2239c96 | 632,826 |
def get_list_of_active_skills(utterances):
"""
Extract list of active skills names
Args:
utterances: utterances, the first one is user's reply
Returns:
list of string skill names
"""
result = []
for uttr in utterances:
if "active_skill" in uttr:
result.... | 129902a69a387fbf4601737dee67db28d8cf856a | 632,827 |
def make_prediction(training_set, model):
"""to get y_pred"""
pred = model.predict(training_set)
return pred | 4ca42c9bb505f566ae52d23d4ab0830d55592295 | 632,828 |
import csv
import os
def split_data(inputfile_shuf, ip_type, blacklist):
"""
ipfile_shuf: Lists with ip's to split
ip_type: Type of IP address used.
blacklist: File with IP addresses that should not be scanned
Function:
Removes the port from... | 07e086ae1da01e7e8dd404cd44a514195038c332 | 632,830 |
import math
def switchSymmetry(mlist, upperToLower=True):
"""
A symmetric 2-d NxN array can be stored in memory as a list of (N*(N+1)/2) numbers. The order depends
on whether the upper-diagonal or lower-diagonal portion of the array is being stored. This method switches
between the two representation... | f749690f3b2e5144833771d9cd1bd5481c08b321 | 632,831 |
import re
def cheapo_gnatchop(lines):
"""Performs a cheapo gnatchop on the given text.
lines is a list of strings
Returns a list of tuples of the form (basename, contents)
"""
results = []
current_basename = 'invalid.ads'
current_contents = []
body = re.compile("^(procedure|package bo... | c45326ca6ce4874a22c8c7d97d0d26519e539819 | 632,832 |
import time
def timestamp_datetime(timestamp, format='%Y-%m-%d %H:%M:%S'):
""" 将时间戳(10位)转换为可读性的时间 """
# timestamp为传入的值为时间戳(10位整数),如:1332888820
timestamp = time.localtime(timestamp)
# 经过localtime转换后变成
## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2... | ea55e78a40cb941c78d8f6f13eaf460ecc20ce2b | 632,833 |
def org_empty_payload(org_default_payload):
"""Provide an organization payload with no action."""
empty_payload = org_default_payload
empty_payload["action"] = ""
return empty_payload | a5a2227eb217596dfb70e655bcc416dc3aed8d7e | 632,835 |
def scrape_overflow(query, sources, answers):
"""
{
"title": "string",
"votes": int,
"answers": [
{
"text": "string",
"votes": int,
"author": "string",
"date": "string" or datetime
}
],
... | 967bed7c57dc660f91575f7cf650e6721d445c11 | 632,836 |
def get_and_update_or_create(model, filter_params, defaults):
""" get or create with default values applied to existing instances
{model}.objects.get_or_create(*{filter_params}, defaults={defaults})
Arguments:
model {django.db.models.Model} -- The model the queryset gets applied to
fil... | 3bea14911f6a690606813aa29caa8a463918564a | 632,838 |
def get_locations_by_country(df,country):
"""
Return locations in the country
Args:
df (pandas Dataframe) : dataframe containing locations and corresponding countries
country (str) : name of the country
Returns:
str: Name of the country the location is in.
"""
l... | aa7f8f2e61d3fb7adac01c4b063520f9a267dcd7 | 632,839 |
import time
def get_time_between_txn(transactions, address):
"""
Process time related Transaction data and perform aggregation
:param transactions: list of Transactions
:param address: Address being explored
:return:
"""
sent_timestamps = []
received_timestamps = []
all_... | d969c75ad596a10cb3e9654e433022bbdb3b6b50 | 632,841 |
def byte_to_int16(lsb, msb):
"""
Converts two bytes (lsb, msb) to an int16
:param lsb: Least significant bit
:param msb: Most significant bit
:return: the 16 bit integer from the two bytes
"""
return (msb << 8) | lsb | 483a7205e57d615bf0122b437a5c000d9e859620 | 632,842 |
import numpy
import sys
def decode_byte_string(value):
"""Convert (arrays of) byte-strings to (list of) unicode strings.
Due to limitations of HDF5, all strings are saved as byte-strings or arrays
of byte-stings, so they must be converted back to unicode. All other typed
objects pass unchanged.
... | 805ccbaf6d153dbcd5033f188cfa61f2ba387dca | 632,843 |
import time
def _wait_for_spot_request_fulfillment(conn, requests, fulfilled_requests = []):
"""
Wait until all spot requests are fulfilled.
Once all spot requests are fulfilled, return a list of corresponding spot instances.
"""
if len(requests) == 0:
reservations = conn.get_all_instance... | 60e82df2603f23a130f6db51cdb1e1aa5527f480 | 632,844 |
import random
def cross_individuals(ind_1, ind_2):
"""
"""
crossed_individual_1, crossed_individual_2 = ind_1, ind_2
#cut point: index from where we cut the individual cromosomes.
cut_point = int(random.uniform(1,len(ind_1)))
cut_point_conjugate = len(ind_1) - cut_point
#bulid the new (cr... | a9a9748140284303519926a34c0a2e4e600942b8 | 632,846 |
def generate_number_lines(number_of_lines=6, start=0, end=20):
"""
Generates number lines as a tool for practicing mathematics such as addition or subtraction.
:param number_of_lines: Specify the number of lines to have on the page
:param start: start value for the number line as an integer
:param e... | 173aae03162e5d5717078e872051bc11e1e56057 | 632,848 |
import re
def get_indentation(keyword, search_str):
"""
In a multi-line string with new line characters, find the indentation of a
search string. Currently assumes that spaces are used for indentation and
the search string directly follows the indent.
Args:
keyword (string): The keyword t... | 1e645bbb0d23b39d0e4a2f1545c80fa458a19683 | 632,849 |
def cron_str2int(str):
""" Convert day name to digit. """
days = [ "sun", "mon", "tue", "wed", "thu", "fri", "sat" ]
try:
pos = days.index(str)
if pos != ValueError:
return pos
except:
try:
value = int(str)
return value
except:
... | 48eabd4f6b79c212b205a0cf81d4f6cba39e7f2c | 632,850 |
def charge_gen(item, atom_number, charge_list):
"""
Returns a float that represents the charge on a single bead.
"""
if atom_number in charge_list:
return float(item['charge_max'])
else:
return 0.0
# use dictionary for complicated things
#
#
# : {'style' : 'ra... | f1b076fd921ed35f8357b3a3276f5ea58bd03923 | 632,851 |
def simp_str(str):
"""Return a integer list to count: upper-, lowercase, numbers, and spec. ch.
input = string
output = list of integers, to count
ex: if input is "*'&ABCDabcde12345"), output: [4,5,5,3].
the order is: uppercase letters, lowercase, numbers and special characters.
"""
len_str... | 4f10f68b060e3e4b28de7e223606123f7bed3f3c | 632,852 |
import os
import re
def findReplicatesBams(folder, sep='', filetypes=['.bam'], namings='-r([0-9])', namepos=0):
"""
creates a dict of name and replicate files given a regexp naming scheme
Args:
-----
folder: str the folderpath containing the bam files
sep: str how to separate each filename (to extract the na... | 949659b77c82f54eebce953187deb0a345e419c9 | 632,853 |
def url_replace(request, field, value):
"""Used by pagination to add GET param."""
dict_ = request.GET.copy()
dict_[field] = value
return dict_.urlencode() | b7354599f9e77464acf938bd0c0e3421ee5ea151 | 632,854 |
def generate_importer_base_name(dependent_task_name: str,
input_name: str) -> str:
"""Generates the base name of an importer node.
The base name is formed by connecting the dependent task name and the input
artifact name. It's used to form task name, component ref, and executor la... | 4839b99d38f6073275e1e6091b602e6d61f91ce6 | 632,855 |
from typing import Any
def toBoolean(value: Any) -> bool:
"""
Coerces the input value to a boolean.
Null values and empty strings are mapped to null.
"""
return bool(value) | 83c84e4d96c93d22448e60ccc0f8c03f0256b16e | 632,856 |
def smart_split(line):
"""
split string like:
"C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'"
in the list like:
['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4']
"""
flag_in = False
l_val, val = [], []
for hh in line.s... | 7249b6598f93c93ba17f668e5d0554ebae31a100 | 632,857 |
import random
def method_1(num_chars: int):
"""
Hand Implemented Method to generate a random password
of num_chars long
Args:
num_chars (int): Number of Characters the password will be
Returns:
string: The generated password
"""
lower = "abcdefghijklmnopqrstuvwxyz"
up... | a13d317eed5e85957b173ca07df190a8038f05d5 | 632,858 |
def service_token():
"""
Generate a service token that will be used in machine-to-machine auth
"""
return 'abc' | ee34a2a514f3da18952d877781b7fc65d001fdeb | 632,859 |
def clip_boxes_opr(boxes, im_info):
""" Clip the boxes into the image region."""
w = im_info[1] - 1
h = im_info[0] - 1
boxes[:, 0::4] = boxes[:, 0::4].clamp(min=0, max=w)
boxes[:, 1::4] = boxes[:, 1::4].clamp(min=0, max=h)
boxes[:, 2::4] = boxes[:, 2::4].clamp(min=0, max=w)
boxes[:, 3::4] = ... | dd8161e0265778b60473ab3edef0c76c866e7f0b | 632,860 |
def parse_mappings(mapping_list):
"""Parse mapping devices list
parses mapping device list in the form:
physnet:pci_dev_1,pci_dev_2 or
function:pci_dev_1,pci_dev_2
:param mapping_list: list of string pairs in "key:value" format
the key part represents the physnet or function nam... | 8be2105255bad7e7b9a1923c0ec92677753fd5e6 | 632,861 |
def find_min_pdop(comb_anch_last):
"""
Finds the minimum PDOP value
Return: min_pdop
Type : float
"""
min_pdop = min(comb_anch_last[:, 13])
return min_pdop | e436cb6848254c5af9c205e8a72625d2be3df25a | 632,862 |
import random
def interkey_interval():
"""in milliseconds"""
# return 0 # makes testing faster
return (random.lognormvariate(0.0, 0.5) * 30.0) / 1000.0
return float(random.randrange(10, 50)) / 1000.0 | a38aed86ce8ee34d32f05bc221ed74b072023716 | 632,863 |
def half_adder(a,b):
"""Single bit addition"""
return (a+b)%2 | 61a61c0c71d6c0573eeca9f2595fe401664d7315 | 632,864 |
import math
def part2(data):
"""Return least fuel to move all submarines to same position.
Fuel to go from current to desired position is 1 + 2 + ... + abs(d - c).
"""
numbers = list(map(int, data.split(',')))
# puzzle has 100s of numbers in a range of 1000, so brute-force is OK
min_fuel = ma... | 95c07b37171c2e71258cdb3f02ff6e726cf999c1 | 632,865 |
import math
def compute_distance(loc1, loc2):
"""
params:
- loc1 (location of start vertex)
- loc2 (location of destination vertex)
output:
euclidean distance between the two vertices
"""
distance = math.sqrt(math.pow((loc1[0]-loc2[0]),2) + math.pow((loc1[1]-loc2[1]),2))
... | f624c2967d78162d3f65f046f6e938d813009eb9 | 632,866 |
def extract_document_size(block_data):
"""
Args:
block_data(str): A data block with an entanglement header
Returns:
int: The size of the original document
"""
if not block_data or not isinstance(block_data, str):
raise ValueError("argument block_data must be a non-empty seque... | bbb056923d53ce852612ee50af49db2e28ad4b3a | 632,867 |
import requests
def aggregate_urns(urnlist):
"""Sum up word frequencies across urns"""
if isinstance(urnlist[0], list):
urnlist = [u[0] for u in urnlist]
r = requests.post("https://api.nb.no/ngram/book_aggregates", json={'urns':urnlist})
return r.json() | 632dcc1bf912546322dde079dc77d6ef638e686b | 632,868 |
def handle_response(root):
"""
:param root: Root element of XML payload.
:return: XML payload for Openpay API.
"""
final_response = {}
for value in root:
if value.text is not None:
final_response[value.tag] = value.text
return final_response | 776970c53299c38014440857a12276d7db870bf1 | 632,869 |
def create_dict(keys_list):
""" Creates a dictionary from a given list of keys """
dict_ = {}
for key_ in keys_list:
dict_[key_] = []
return dict_ | 33c4d0fbf389d4b968e68ad76406a169010b3db6 | 632,870 |
def get_app_instances_ids(instances):
"""
Accepts a dictionary of id: AppInstance and returns a set of keys
"""
return set(instances.keys()) | 6dde1bd996782b8a2ae897cb10851080c0ee4a22 | 632,871 |
def flatten_lists(list_of_lists):
"""
Parameters
----------
list_of_lists: list[list[Any]]
Returns
-------
list[Any]
"""
return [elem for lst in list_of_lists for elem in lst] | 55cc7047b20388e07dca88ded48d779dd8fcc9e5 | 632,872 |
def layer_output(model, layer_name=None):
"""Output tensor of a specific layer in a model.
"""
conv_index = -1
for i in range(len(model.layers) - 1, -1, -1):
layer = model.layers[i]
if layer_name in layer.name:
conv_index = i
break
if conv_index < 0:
print('Error: could not find the interested layer... | e3f693d8d5759f1ec1d6aab84e5cc85e9764cebc | 632,873 |
import os
def get_home_dir():
"""
Return user home directory
"""
try:
path = os.path.expanduser('~')
except:
path = ''
for env_var in ('HOME', 'USERPROFILE', 'TMP'):
if os.path.isdir(path):
break
path = os.environ.get(env_var, '')
if path:
... | fb702e427628f43985a1447175abc7bd3ff50bf5 | 632,874 |
import subprocess
def get_duration(vid):
"""[summary]
Args:
vid ([type]): [description]
Returns:
[type]: [description]
"""
cmd1 = 'ffprobe -i \"{}\" -show_entries \
format=duration -v quiet -of csv="p=0"'.format(vid)
duration = subprocess.check_output(cmd1, shell=Tru... | 900c437875827ee1ffa576c1b6445b9d9aa60dc8 | 632,875 |
from typing import List
def remove_duplicates(jobs_comb: List) -> List:
"""
remove the combinations that are included in other one.
To keep only the most complete combinations of jobs
[(456),(456,12)] -> [(456,12)]
(456) is already in the second tuple so we don't need
to count it as unique val... | 10bd0530314a82972e7c7edc0eae1d5074e390aa | 632,876 |
import numpy
def grdsf(nu):
"""Calculate PSWF using an old SDE routine re-written in Python
Find Spheroidal function with M = 6, alpha = 1 using the rational
approximations discussed by Fred Schwab in 'Indirect Imaging'.
This routine was checked against Fred's SPHFN routine, and agreed
to about t... | 9b769ad821dc216db744fb38d4571077898f367d | 632,877 |
import random
def truncation_select(data, score):
"""
:param data: list of dict containg each ranks' model data as well as
rank itself.
:return a dict that contains all the selected rank's model data, or an
empty dict if no selection
"""
# e.g. data: [{'acc': 0.87916666666666665, 'loss... | ae072ff0d77152590880e5f33361021ff4f7fbaa | 632,878 |
import numpy
def stouffer(z_scores, weights):
"""
Meta-analyze z_scores using Stouffer's method.
See https://doi.org/10.15363/thinklab.d43#5
"""
assert len(z_scores) == len(weights)
z_scores = numpy.array(z_scores)
weights = numpy.array(weights)
return numpy.sum(z_scores * weights) / n... | 1103b3f35cdbbb564a9767491dc6778540f85d54 | 632,879 |
def _log_capacity(state):
"""
Produces a dictionary containing the active capacity, pending capacity, and
desired capacity (which is what the user requested, not active + pending),
to be used for logging.
This exists because the current_desired presented to users is active +
pending, and we wan... | 04422183eabcda4022e8cdda36857174a19e9eb2 | 632,880 |
def unpack_lemma_batch(batch, use_cuda):
""" Unpack a batch from the data loader. """
if use_cuda:
inputs = [b.cuda() if b is not None else None for b in batch[:6]]
else:
inputs = [b if b is not None else None for b in batch[:6]]
orig_idx = batch[6]
return inputs, orig_idx | c0d95e2dbccfefaaf0468e106fd4fc7ed753d444 | 632,881 |
def load_data(fileName):
"""
Desc:
该函数读取一个以 tab 键为分隔符的文件,然后将每行的内容保存成一组浮点数
Args:
fileName 文件名
Returns:
dataMat 每一行的数据集array类型
Raises:
"""
# 假定最后一列是结果值
dataMat = []
fr = open(fileName)
for line in fr.readlines():
curLine = line.strip().split('\t')
... | 57f7234b9883f5f6667c43fbb76c29db9a5a15fb | 632,882 |
import os
import codecs
def read(filepath):
"""
Reads the file at the filepath
Args:
filepath (str): Path to the file to read
Returns:
str: File contents as a string
"""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, filepath), encod... | 26693541f739b2fd7324e099afbc1d030f7096f8 | 632,883 |
import subprocess
def path_changed(paths, commit_range):
"""Have the path(s) changed during the given commit range?"""
if isinstance(paths, str):
paths = [paths]
return subprocess.check_output([
'git', 'diff', '--name-only', commit_range, '--',
] + paths).decode('utf-8').strip() != '' | 2952bc80d81978ec5fbfb8809b472c386e1673c1 | 632,884 |
from typing import List
import argparse
def parse_args(args: List[str]) -> argparse.Namespace:
"""argument parser for backfill CLI"""
parser = argparse.ArgumentParser(
description="utility to backfill success file notifications "
"or run the cloud function locally in concurrent threads.")
... | 92b87ff3594f527efba29557968079e17beb65e9 | 632,885 |
def fillNaToMode(data):
"""Iterates through NA values and changes them to the mode
Parameters:
dataset (pd.Dataset): Both datasets
Returns:
data (pd.Dataset) : Dataset with any NA values in the columns listed changed to the mode
"""
columns = ["MSZoning", "Functional", "Electrical", "Kitch... | 6d8ec04da66b7463e69fdda3ff6665b3ce2bbde8 | 632,886 |
def root_to_dict_question_grid(root):
"""
Part of parse xml, item_type = Question Grid
"""
info = {}
info['QuestionGridURN'] = root.find('.//URN').text
info['QuestionGridUserID'] = root.find('.//UserID').text
info['QuestionGridLabel'] = root.find(".//UserAttributePair/AttributeValue").text
... | 67015fa6eb2596301c10dcfb48b5e75eb9e92153 | 632,887 |
def _csize(counter):
"""
Computes the size of (number of elements in) a given Counter.
Parameters
----------
counter : Counter
The counter to get the size of.
Returns
-------
int
"""
return len(list(counter.elements())) | 7a2857011ded59790e3f5bfd40b6230f2dfc1324 | 632,888 |
import os
def get_key_for_video_imgs(x):
"""
x: "calendar/0000.png"
"""
clip, name = x.split("/")
name, _ = os.path.splitext(name)
return (clip, int(name)) | 4c0a5e11d2e99b45ebfd976421cc924dfff23963 | 632,889 |
def list_to_hp(li: list) -> str:
"""
Converts a list (used for toolz get_in, assoc_in, update_in) to a hp
(hierarchy path).
Input: ['root', 0, 'thing',2]
Output: /root/0/thing/2
"""
assert isinstance(li, list), "The input type for li must be a list."
assert "/" not in li, "Can't have ... | 02c50a4aad7bfe5a3b403b6805f729b824d8e43b | 632,890 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.