content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _convert_str_to_html(string):
"""Helper function to insert <br> at line endings etc."""
if not string: return ""
lines = string.splitlines()
for index, line in enumerate(lines):
for char in line:
if char == '\t':
lines[index] = line.replace(char, " &nbs... | b357d04f28a08f6b65d98ee381dcaef8969f6ff0 | 701,969 |
def _parseLinks(response, rel):
"""
Parses an HTTP response's ``Link`` headers of a given relation, according
to the Corelight API specification.
response (requests.Response): The response to parse the ``Link`` headers
out of.
rel (str): The link relation type to parse; all other relations are... | 73a4f2a7e981b335aa511e5e311ef7290a7695e3 | 701,970 |
def find_min_max(data):
"""Solution to exercise C-4.9.
Write a short recursive Python function that finds the minimum and
maximum values in a sequence without using any loops.
"""
n = len(data)
min_val = data[0]
max_val = data[0]
def recurse_minmax(idx):
nonlocal min_val, max_v... | b8f50d1dafa0f66ab61db8d4974c8d201cd4dc3c | 701,971 |
import torch
from functools import reduce
def mask_with_tokens(t, token_ids):
"""
用记号遮掩
"""
init_no_mask = torch.full_like(t, False, dtype=torch.bool)
mask = reduce(lambda acc, el: acc | (t == el), token_ids, init_no_mask)
# print("mask",mask)
return mask | f233f2e2111e02919ff3795820f024b0e5b850a1 | 701,972 |
def isStandard(descriptorType):
"""
>>> isStandard(0x0a)
True
>>> isStandard(0x22)
False
>>> isStandard(0x61)
False
>>> isStandard(0x1a)
True
"""
# See USB Common Class Specification s. 3.11 for this field's structure
# Bit 7: reserved
# Bits 6..5: descriptor type
... | a4e002e58c07638cb14d1a13a27ac7232af140cf | 701,973 |
def cell_content_to_str(v):
"""
Convert the value of a cell to string
:param v: Value of a cell
:return:
"""
if v:
if isinstance(v, float) or isinstance(v, int):
return str(int(v))
else:
return str(v).strip()
else:
return None | b73746d735ed155d387512704b91fc92c0c93560 | 701,975 |
import os
def enter_file(file_type, file_path=""):
"""Request file path from user until path
exists.
Parameters
----------
file_type: str
Type of file to display in input line
file_path: str (optional)
Initial file path to try
"""
while not os.path.exists(file_path):
... | 7470761a3b41eedd7a6d98f088b7a693bfd7428a | 701,976 |
def __hamming_distance_with_hash(dhash1, dhash2):
"""
*Private method*
根据dHash值计算hamming distance
:param dhash1: str
:param dhash2: str
:return: 汉明距离(int)
"""
difference = (int(dhash1, 16)) ^ (int(dhash2, 16))
return bin(difference).count("1") | c8a28a3f20a037fe9e96bfe82cb522caf6600337 | 701,977 |
def _min_to_sec(minutes):
"""converts minutes to seconds,
assuming that input is a number representing minutes"""
return minutes*60 | dff3330038c7e8cd1abda2c8a0a4433979fedf58 | 701,978 |
def get_ip(request) -> str:
"""
获取当前请求的ip地址
:param request:
:return:
"""
if request.META.get('HTTP_X_FORWARDED_FOR', None):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
return ip | eb084135920231aa176e6099d70ed3954b407070 | 701,979 |
def get_file_data_old(archivo):
"""
Separa del nombre del archivo y extrae nombre de Centroide (ctrd)
y cultivo (clt)
"""
diccionario = {}
listado = archivo.split('-')
diccionario['ctrd'] = listado[0]
condicion = 'TS(S2)' in listado[1] or\
'TS(TC)' in listado[1] or\
... | 4d02b5b77aaf0abfc768c898534493d3723ef54e | 701,980 |
from typing import Dict
def dict_squares(n: int) -> Dict[int, int]:
"""Generates a dictionary with numbers from 0 to n as keys
which are mapped to their squares using dictionary comprehension.
doctests:
>>> dict_squares(2)
{0: 0, 1: 1, 2: 4}
>>> dict_squares(5)
{0: 0, 1: 1, 2: 4, 3: 9,... | 4101d0256069c07da6c3d5a8d1e40783a4b26eea | 701,981 |
import argparse
def parse_args():
"""
Initializes command line arguments and
parses them on startup returning the parsed
args namespace.
"""
parser = argparse.ArgumentParser()
bot = parser.add_argument_group('Discord Bot')
bot.add_argument(
'--token', '-t', required=True, type... | 3f8ae0e284c9b917b76bac48a4f9bd254e76403d | 701,982 |
def wrap_coro(coro, unpack, *args, **kwargs):
""" building a coroutine receiving one argument and call it curried
with *args and **kwargs and unpack it (if unpack is set)
"""
if unpack:
async def _coro(value):
return await coro(*args, *value, **kwargs)
else:
async def _co... | 2e1916f5f34be5878a3af64ea28b5ffb56f6b350 | 701,983 |
from typing import Any
import typing
def hint_is_specialized(hint: Any, target: Any) -> bool:
"""Checks if a type hint is a specialized version of target.
E.g., hint_is_specialized(ClassVar[int], ClassVar) is True.
isinstance will invoke type-checking, which this methods sidesteps.
Behavior is undef... | b651fc05290de82ab5a5833d10ca68d6a96f2d7a | 701,984 |
def build_spc_queue(rxn_lst):
""" Build spc queue from the reaction lst for the drivers
:return spc_queue: all the species and corresponding models in rxn
:rtype: list[(species, model),...]
"""
if 'all' in rxn_lst:
# First check if rxn_lst is a bunch of species
spc_queue = r... | 0dbe4e2bc3db16dc5dc83a55f0f802d4dfae853f | 701,985 |
def patch_telomeres(bands_by_chr):
"""Account for special case with Drosophila melanogaster
"""
for chr in bands_by_chr:
first_band = bands_by_chr[chr][0]
start = first_band[1]
if start != '1':
stop = str(int(start) - 1)
pter_band = ['pter', '1', stop, '1', st... | 23057227c526bb3837fd0c02233ddac4671c6956 | 701,986 |
from typing import List
def smallest_positive_integer_not_in_array(arr: List[int]) -> int:
"""
[1..N] can cover everything from 1 to (N * (N+1) / 2)
"""
res = 1
for num in arr:
if num > res:
return res
else:
res += num
return res | 9d01e051c278beab40aefa6618a4a5f4934e451a | 701,987 |
def module_enclosing_func(offset):
""" Test function to see if module-level enclosures are detected """
def module_closure_func(self):
"""
Actual closure function, should be reported as:
putil.tests.my_module.module_enclosing_func.module_closure_func
"""
self._exobj.add_e... | 399212d5cc04479639cdb5cacb50b167327f2445 | 701,988 |
def get_ini_conf(fname):
""" Very simple one-lined .ini file reader, with no error checking """
with open(fname, "r") as handle:
return {i.split("=")[0].strip(): i.split("=")[-1].strip() for i in handle.readlines() if i.strip()} | 180c3106bb40c26b6628ff19dcb2c233a7f6a8d7 | 701,989 |
import socket
def whois(ip_address):
"""Whois client for Python"""
whois_ip = str(ip_address)
try:
query = socket.gethostbyname(whois_ip)
except Exception:
query = whois_ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ripe.net", 43))
s.send(query.... | 7440f936ca866bc74ccd4e0d81bff56e46b82f60 | 701,990 |
import json
import logging
def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram. Both parameters are json
serializations of histograms."""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, ma... | ac346f7d2e132b8577c957f89cd7fb6150207bf1 | 701,992 |
def _front_left_tire_pressure_supported(data):
"""Determine if front left tire pressure is supported."""
return data["status"]["tirePressure"]["frontLeftTirePressurePsi"] is not None | b59ab6f4a9b3d0801c1c5c8798e7da2fab0b580d | 701,993 |
def count_missing_doc_types(articles):
"""
:param articles A PyMongo collection of articles
:return: int: Number or articles without a a 'doc_type' property or having
it equal to the empty string ('')
"""
return articles.count_documents(
{"$or": [{"doc_type": {"$exists": False}}, {"doc_t... | b0e734590c4b74572382e377f9cd861fa5162af7 | 701,994 |
import argparse
def parse_args():
""" Parses the arguments of the command line """
parser = argparse.ArgumentParser(
description="Checks a file for british and american spellings")
parser.add_argument('files', metavar="files", type=str, nargs='+',
help='file where to check the spe... | 1ea6d692eedbd2c448138cf0adc3a85cf2a85283 | 701,995 |
from datetime import datetime
def now_int():
"""
Returns the current POSIX time as an integer.
:return: integer POSIX time
"""
now = datetime.now() - datetime(1970, 1, 1)
return int(now.total_seconds()) | 3c70a3324b549d24aaac01f49a2ed7ef480a8eb7 | 701,996 |
def module_loaded(module):
"""
Checks if the specified kernel-module has been loaded.
:param module: Name of the module to check
:return: True if the module is loaded, False if not.
"""
return any(s.startswith(module) for s in open("/proc/modules").readlines()) | f09e719acba7f8e2aed59816d3b99bd9575edcfd | 701,998 |
def IsMonophyleticForTaxa(tree,
taxa,
support=None):
"""check if a tree is monophyletic for a list of taxa.
Arguments
---------
tree : :class:`Tree`
Tree to analyse
taxa : list
List of taxa
support : float
Minimum bo... | fcb0066c4083183cc7b81195a0845897d95b1cde | 701,999 |
def year_range(entry):
"""Show an interval of employment in years."""
val = ""
if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None:
val = "unknown"
else:
val = entry["start_date"]["year"]["value"]
val += "-"
if entry.get("end_date") is None or ent... | 92f7f0bcb450303161b7f766148a9feac62f98d1 | 702,002 |
def extract_BIO_tagged_tokens(text, source_spans, tokenizer):
""" Разобьем на bio-токены по безпробельной разметке """
tokens_w_tags = []
for span in source_spans:
s,e,tag = span
tokens = tokenizer(text[s:e])
if tag == 'Other':
tokens_w_tags += [(token,ta... | 7b56295f36040b68a3ba7d6f8c817d9f9b4c5094 | 702,003 |
def format_duration(dur: float) -> str:
"""Formats duration (from minutes) into a readable format"""
if float(dur) >= 1.0:
return "{} min".format(int(dur))
else:
return "{} sec".format(int(round(dur * 60))) | 02393e051b751001af9c8092ff64ebcef7596d6f | 702,004 |
import struct
def unpack(structure, data):
"""
Unpack little endian hexlified binary string into a list.
"""
return struct.unpack('<' + structure, bytes.fromhex(data)) | 530cf57b74be1e171a6f0c7ba148bdf73e8a7612 | 702,005 |
def get_recall(indices, targets):
""" Calculates the recall score for the given predictions and targets
Args:
indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
targets (B): torch.LongTensor. actual target indices.
Returns:
recall (float): the recall score
"... | 63f4d7f36f63d3110c33989b03f264e1fa4aa4ff | 702,007 |
def get_collection_no(row):
"""Get the collection number from an expedition row."""
if row.get('collector_number'):
return row.collector_number
num = row.get('collector_number_numeric_only', '')
verb = row.get('collector_number_verbatim', '')
if verb and len(num) < 2:
return row.coll... | a3e92e24a6a5a95651b7ccde183ecc6b083a649a | 702,008 |
def _get_versioned_config(config, version = ""):
"""select version from config
Args:
config: config
version: specified version, default is "".
Returns:
updated config with specified version
"""
versioned_config = {}
versioned_config.update(config)
used_version = co... | 70528e14148358613d2561c90e741b3f49569136 | 702,009 |
import configparser
from typing import Union
def _prompt_for_option_name (ARG_config_object: configparser.ConfigParser, ARG_section: str) -> Union[str, None]:
"""Prompts the user to enter a valid option name. Checks that option name exists.
Parameters
----------
ARG_config_object : configparser.Confi... | b9aea1ba8a19d0c3a104a4e661a4043e9ad33889 | 702,010 |
def find_direct_conflicts(pull_ops, unversioned_ops):
"""
Detect conflicts where there's both unversioned and pulled
operations, update or delete ones, referering to the same tracked
object. This procedure relies on the uniqueness of the primary
keys through time.
"""
return [
(pull_... | 5832a41b81cffd7e5c7d1f79472f9c44eaa3127a | 702,011 |
def unknown_id_to_symbol(unknown_id, header="X"):
"""Get the symbol of unknown whose id is |unknown_id|.
:type unknown_id: int
:type header: str
:param unknown_id: The ID of the unknown.
:param header: The symbol header.
:rtype : str
:return: A string that contains the symbol.
"""
... | 53081447eb0c5daf70d1af936337b35bffe4caf0 | 702,012 |
import subprocess
def _get_git_revision_hash():
""" ref: https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script """
return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() | 368d8873df7b06ecdc5cbddb04cfe7fa57e553a2 | 702,013 |
import re
def markdown_to_doxygen(string):
"""Markdown to Doxygen equations"""
long_equations = re.sub(
r"(?<!\\)\$\$(.*?)(?<!\\)\$\$", r"\\f[\g<1>\\f]", string, flags=re.DOTALL
)
inline_equations = re.sub(r"(?<!(\\|\$))\$(?!\$)", r"\\f$", long_equations)
return inline_equations | 2cae07ccb661ef22fab518d4fae4a0cc22868d84 | 702,014 |
import click
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expe... | fb8e3f79e46cd046737de4d001357eafb9a1ef5c | 702,016 |
def init(input_mgr, user_data, logger):
"""Initialize the example source tool."""
# Get the selected value from the GUI and save it for later use in the user_data
user_data.val = float(input_mgr.workflow_config["Value"])
# Display info on the selected value
logger.display_info_msg(f"The value selec... | dd922eea66b61e152675f9a27f6732cb8bd56209 | 702,017 |
from typing import List
def assert_single_whitespace_after_second_semicolon(docstring: List[str]) -> List[str]:
"""
Find the lines conaining prefixes = [":param", ":return", ":raises"].
For those lines make sure that there is only one whitespace after the second semicolon.
:param docstring: list of l... | 8e3f1a2f67782774e52b424e025e5a2cea1ebfca | 702,018 |
from typing import Dict
def is_graph_equal(lhs_workbench: Dict, rhs_workbench: Dict) -> bool:
"""Checks whether both workbench contain the same graph
Two graphs are the same when the same topology (i.e. nodes and edges)
and the ports at each node have same values/connections
"""
try:
if n... | 02c327cfb364e01f206458a87d6c4561985b42d6 | 702,019 |
import copy
def combine(to_merge, extend_by):
"""Merge nested dictionaries."""
def _combine(to_merge, extend_by):
for key, value in extend_by.items():
if key in to_merge:
if isinstance(to_merge[key], dict):
_combine(to_merge[key], value)
... | 69a5713e65bace724370c722155a2677cd50c317 | 702,020 |
def chr22XY(c):
"""Reformats chromosome to be of the form Chr1, ..., Chr22, ChrX, ChrY, etc.
Args:
c (str or int): A chromosome.
Returns:
str: The reformatted chromosome.
Examples:
>>> chr22XY('1')
'chr1'
>>> chr22XY(1)
'chr1'
>>> c... | 13677f728ce8221e9a6966951353deba703f3294 | 702,021 |
import re
def searchLiteral(a_string, patterns):
"""assumes a_string is a string, being searched in
assumes patterns is a list of strings, to be search for in a_string
returns a re span object, representing the found literal if it exists,
else None"""
results = []
for pattern in patterns:
... | fcbbbdb61474e441b5fe0a0d207b0c2c7a0b7da5 | 702,022 |
def get_tourn_golfer_id(tourn_golfers_list, tourn_id, golfer_id):
"""
Helper function to get the tourn_golfer_id
based on the specified tourn_id and golfer_id
"""
for tourn_golfer in tourn_golfers_list:
if tourn_golfer.get_golfer_id() == golfer_id:
if tourn_golfer.get_tourn_id()... | ead84142f91289a8786aa57da6c64cc512309ff8 | 702,025 |
import re
def verify_raw_google_hash_header(google_hash: str) -> bool:
"""Verify the format of the raw value of the "x-goog-hash" header.
Note: For now this method is used for tests only.
:param str google_hash: the raw value of the "x-goog-hash" header
:rtype: bool
"""
return bool(re.match... | 187c903c23e0c860e983b2e9b70890a36823c63f | 702,026 |
def stack_operations():
"""Solution to exercise R-6.1.
What values are returned during the following series of stack operations,
if executed upon an initially empty stack? push(5), push(3), pop(),
push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6),
pop(), pop(), push(4), pop(... | d3acdcdd38cf86cf2d94a9c35dec9994a649ef4e | 702,027 |
import hashlib
def get_SHA1(variant_rec):
"""Calculate the SHA1 digest from the ref, study, contig, start, ref, and alt attributes of the variant"""
h = hashlib.sha1()
keys = ['seq', 'study', 'contig', 'start', 'ref', 'alt']
h.update('_'.join([str(variant_rec[key]) for key in keys]).encode())
retu... | 45e1aca002dc2ae972ee0e61c11441c11714c793 | 702,028 |
def reverse_list(head):
"""Fantasic code!"""
new_head = None # ptr on previous item
while head:
head.next, head, new_head = new_head, head.next, head # look Ma, no temp vars!
return new_head | a9a09f30083549aeaeaa4750f66efaf869fce44d | 702,029 |
def mult_vector(vector, coeff):
""" multiplies a 2D vector by a coefficient """
return [coeff * element for element in vector] | 4f404b23ef4f11b162b352735275498811cc6821 | 702,030 |
def get_date_whereclause(date_colname, startdate, enddate):
"""This is to change the date format function to use on the actual queries
sqlite and mysql use different methodnames to do their date arithmetic"""
ret = " %s > '%s' AND %s < '%s' " % (date_colname,startdate.strftime('%Y-%m-%d'),
... | f02d033f3f89eac5ac4d496d5995e87b6d9d0301 | 702,031 |
def newton_rhapson(f, df, x0, epsilon=1e-5):
"""Găsește o soluție a funcției f cu derivata df, aplicând
metoda lui Newton, pornind din punctul x0.
"""
# Primul punct este cel primit ca parametru
prev_x = x0
# Aplicăm prima iterație
x = x0 - f(x0) / df(x0)
# Continuăm să calculăm până av... | 5cd4d3b201d5e0cfd441df494b4203b523f39171 | 702,032 |
def appendToFile(fileName: str, content: str):
"""Writes content to the given file."""
with open(fileName, "a") as f:
f.write(content)
return None | a9e4604fa9404f3c304a40e18ead42a70d99e956 | 702,033 |
import re
def _apply_regex(regex, full_version):
"""
Applies a regular expression to the given full_version and tries to capture
a group
:param regex: the regular expression to apply
:param full_version: the string that the regex will apply
:return: None if the regex doesn't match or the res... | 0a053fd716844f4ec1ad166f414e4d1b931434ec | 702,035 |
def indices(a, func):
"""
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
... | 8c1855cfdbbc11f7b88b23971f03717fc78be27a | 702,036 |
def my_decorated_function(name, value): # ...check_value(fix_name(negate_value(my_decorated_function)))
"""my original function."""
print("name:", name, "value:", value)
return value | fec8ea3f49f4561bdf63245bf5cb9ec284352704 | 702,037 |
import platform
def get_architecture_string():
"""Return a string representing the operating system and the python
architecture on which this python installation is operating (which may be
different than the native processor architecture.."""
return '%s%s' % (platform.system().lower(),
platfor... | 1af6d3b0a713dad26a372389d583f7f7e44679e3 | 702,038 |
import re
import html
def escape_text(txt):
"""
Escape text, replacing leading spaces to non-breaking ones and newlines to <br> tag
"""
lines = []
for line in txt.splitlines():
lead_spaces = re.match(r'^\s+', line)
if lead_spaces: # Replace leading spaces with non-breaking ones
... | 6c750fc9f0862a6b8a5739362918bb54ec73ea98 | 702,039 |
import json
def _clean_output_json(output_json: str) -> str:
"""Make JSON output deterministic and nicer to read."""
try:
output = json.loads(output_json)
except json.JSONDecodeError:
raise ValueError(
f"Instead of JSON, output was:\n--- output start ---\n{output_json}\n--- out... | 0952ed8f8cc34ca2c18aa3d09ca0c81607066332 | 702,040 |
async def get_default_playing(in_guild):
"""Search for a suitable waiting channel on new guild entry
Parameters
----------
in_guild :
Discord Guild to determine default channel for
"""
channels = in_guild.voice_channels
words = ["active","play","stream"]
chans = [c for c in ch... | ffd8418f1b3f5a32933a67459ab94d3960dd68d6 | 702,041 |
import socket
def check_connection(server, port):
""" Checks connection to server on given port """
try:
sock = socket.create_connection((server, port), timeout=5)
except socket.error:
return False
else:
sock.close()
return True | 7b0b7174e7351c87a907d94012e65898cc38a713 | 702,042 |
def empirical_cdf(values, v):
"""
Returns the proportion of values in ``values`` <= ``v``.
"""
count = 0.0
for idx, v0 in enumerate(values):
if v0 < v:
count += 1
return count / len(values) | 65de22130e87ede7dc637e4140f324bdad6dc31b | 702,043 |
def centerpoint(s):
"""
s is 2-d integer-valued (float or int) array shape
return is a (2-tuple floats)
correct for Jinc, hex transform, 'ff' fringes to place peak in
central pixel (odd array)
pixel corner (even array)
"""
return (0.5*s[0] - 0.5, 0.5*s[1] -... | ab79301294f59b88e6005f175671d86fb6201534 | 702,044 |
def _calculate_compliance(results):
"""
Calculate compliance numbers given the results of audits
"""
success = len(results.get('Success', []))
failure = len(results.get('Failure', []))
control = len(results.get('Controlled', []))
total_audits = success + failure + control
if total_audit... | d0855cd88a0ec88a1b9de2c1ba0372a854f2a9c6 | 702,045 |
def good_turing(corpus, words):
"""
:param corpus:
:param words:
:return:
"""
for w in words:
if w in corpus:
raise ValueError('未登录词有误!')
r_dict = {}
for w in corpus:
if r_dict.get(w) is None:
r_dict[w] = 1
else:
r_dict[w] += ... | af35ba996d0f0d2236fc8ef4f6f0466a5204520e | 702,046 |
def datatype_percent(times, series):
"""
returns series converted to datatype percent
ever value is calculated as percentage of max value in series
parameters:
series <tuple> of <float>
returns:
<tuple> of <float> percent between 0.0 and 1.0
"""
max_value = max(series)
try:
... | 8973829f6ea3425351373097fa90b7d4762a880e | 702,047 |
def lame(E=None, v=None, u=None, K=None, Vp=None, Vs=None, rho=None):
"""
Compute the first Lame's parameter of a material given other moduli.
:param: E: Young's modulus (combine with v, u, or K)
:param v: Poisson's ratio (combine with E, u, or K)
:param u: shear modulus (combine with E, v, or K)
... | b8f1d52bac3130b69f75903091d00ce49ba553f8 | 702,048 |
import os
import codecs
def initialize_vocabulary(vocabulary_path):
"""
initialize vocabulary from file.
assume the vocabulary is stored one-item-per-line
"""
characters_class = 9999
if os.path.exists(vocabulary_path):
with codecs.open(vocabulary_path, 'r', encoding='utf-8') as voc_fi... | c63f57299c42914986a17935ca57ccd995500cfe | 702,049 |
from typing import Dict
from typing import Any
import requests
def get_local_status() -> Dict[str, Any]:
"""
Returns a running status if localhost:4040/api/v1/applications is reachable; othe
:return: Dict[str, Any]
"""
idle_cluster_state = {
"url" : "spark://simulated-local-mode-cluster:70... | 06f79d95e513cf91634345c96334f6af7f385fdf | 702,051 |
def total_points(min_x, max_x, points_per_mz):
"""
Calculate the number of points for the regular grid based on the full width at half maximum.
:param min_x: the lowest m/z value
:param max_x: the highest m/z value
:param points_per_mz: number of points per fwhm
:return: total number of points
... | e0680e386559a9603b3b23b9627bd8648b23e65a | 702,052 |
from functools import reduce
def core_count():
""" count number of cores in the local machine """
with open("/proc/cpuinfo","r") as procinfo:
return reduce(lambda a, b: a + b.startswith("processor"), procinfo, 0) | a9adc9ed3f88d5a8dd0175ffb7508adc14f4717e | 702,053 |
def time_text_to_float(time_string):
"""Convert tramscript time from text to float format."""
hours, minutes, seconds = time_string.split(':')
seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds)
return seconds | 96d84804aad2cd094901e61373855604d4768894 | 702,054 |
from typing import List
from typing import Dict
def incremental_build(new_content: str, lines: List, metadata: Dict) -> List:
"""Takes the original lines and updates with new_content.
The metadata holds information enough to remove the old unreleased and
where to place the new content
Args:
... | 7bb44732e278b4dd41ef4796b08b3e39548be4ef | 702,055 |
from typing import Tuple
from typing import List
from datetime import datetime
def read_tides(path: str) -> Tuple[List, List]:
"""Read a CO-OPS tide data CSV file and return
a list of times and elevations."""
data = [line.strip() for line in open(path)]
time = []
elevation = []
for line in dat... | fcbe79a5ddedbaccd0bc0a9c317324881a774a78 | 702,057 |
import requests
def get_lovelive_info():
"""
从土味情话中获取每日一句
:return: str,土味情话
"""
print('获取土味情话...')
try:
resp = requests.get('https://api.lovelive.tools/api/SweetNothings')
if resp.status_code == 200:
return resp.text
print('土味情话获取失败。')
except requests.ex... | daf73060c1caae261408b817a90ba81d25731f5a | 702,058 |
from typing import Any
import json
def read_json_file(filename: str) -> Any:
"""Read a json file
Parameters
----------
filename : str
The json file
Returns
-------
A json object
Example
-------
>>> import allyoucanuse as aycu
>>> content = aycu.read_json_file... | e1afe013da96adfa5dd0e3ea998dce1323efe231 | 702,059 |
def combine_loss_components(critic_loss_val, actor_loss_val, entropy_val,
actor_loss_weight, entropy_bonus):
"""Combine the components in the combined AWR loss."""
return critic_loss_val + (actor_loss_val * actor_loss_weight) - (
entropy_val * entropy_bonus) | 1a060140aa3e08944d2e3f4cf1e4603c88e16921 | 702,061 |
import json
import logging
def country_filter() -> str:
""" find selected country to gather news from from config.json """
with open('config.json') as config_file:
data = json.load(config_file)
logging.info('Countries for news briefing located')
return data['news_briefing'][0]['country'] | 35cfee9c0239dfef7ad352f2c17c2d3a4d140eb9 | 702,062 |
def filter_in_out_by_column_values (column, values, data, in_out):
"""Include rows only for given values in specified column.
column - column name.
values - list of acceptable values.
"""
if in_out == 'in':
data = data.loc[data[column].isin (values)]
else:
data = data.loc... | 191fa20edae7f67b245ad31658297d4a114f59fe | 702,063 |
def intersection(set_1, set_2):
"""realisation of two sets intersection(simple set generator inside)"""
return {i for i in set_1 if i in set_2} | d46a206e6c202343615c3b045a8885d8efd56607 | 702,064 |
def pointer_scope(func):
"""The FDB format has a lot of pointers to structures, so this decorator automatically reads the pointer, seeks to the pointer position, calls the function, and seeks back."""
def wrapper(self, *args, **kwargs):
pointer = kwargs.get("pointer")
if pointer == None:
pointer = self._read_... | a83abfcd0cb9b641aec3125fb267cc6c6f134884 | 702,066 |
def waitfor(css_selector, text=None, classes=None):
"""
Decorator for specifying elements (selected by a CSS-style selector) to
explicitly wait for before taking a screenshot. If text is set, wait for the
element to contain that text before taking the screenshot. If classes is
present, wait until th... | 13130146441f20cfd424e52e46f2f2e3a7e33d3f | 702,067 |
import argparse
def parse_arguments():
""" Parse arguments passed to the script """
parser = argparse.ArgumentParser(description='File uploader to Firebase Storage.')
parser.add_argument('config', help='Path of Firebase configuration file.')
parser.add_argument('--filetoken', dest='filetoken', default... | 1ce3117c64667aa5d50a88bfb64d03bce8b14995 | 702,068 |
def get_requested_countries(countries, country_names):
"""
gets requested countries for visualization and info
:param countries: list of all available countries for research
:param country_names: list
:return: (list, str)
"""
print(country_names)
# gather the requested information
c... | b96f3b001e5a421c333c366f3cdca656d97fe933 | 702,069 |
def retrieve_plain(monitor, object_string):
"""Retrieves the request object as-is (doesn't apply any modification). This
is valid only for objects which are single values (items from a tensor)
:param monitor: either a training or evaluation monitor
:param object_string: string to identify the object to... | 7fc5042422ae70933691202718036703554cff3e | 702,070 |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
# LIST COMPREHENSIO... | 2a393a9e3606022d945454da55fd68543e59476b | 702,071 |
def memsizeformat(size):
"""Returns memory size in human readable (rounded) form.
"""
if size > 1048576: # 1024**2
return "{0} GB".format(size / 1048576)
elif size > 1024:
return "{0} MB".format(size / 1024)
else:
return "{0} KB".format(size) | 0cd812d83bd85b1e2690e0404a4eb833e2e9824f | 702,072 |
def flip_dataframe(df, new_colname='index'):
"""Flips table such that first row becomes columns
Args:
df (DataFrame): Data frame to be flipped.
new_colname (str): Name of new column. Defaults to 'index'.
Returns:
DataFrame: flipped data frame.
"""
colnames = [new_... | 3a7c733644e2c67398a511c9dea7fa80845bbecf | 702,073 |
def ca65_bytearray(s):
"""Convert a byteslike into ca65 constant byte statements"""
s = [' .byt ' + ','.join("%3d" % ch for ch in s[i:i + 16])
for i in range(0, len(s), 16)]
return '\n'.join(s) | 8bdc868cc659e6b99f01449c6bf41884c0635c14 | 702,074 |
import os
def convert_to_pdf(input_path):
"""
Use external tools to convert the powerpoint file to a pdf.
Returns:
path of converted file
"""
path, extension = os.path.splitext(input_path)
if extension not in ['.ppt', '.pptx']:
raise ValueError("{0} not a valid powerpoint extension".format(exten... | aef761b559d32d6f75790cf41d07f80fb7933308 | 702,075 |
def is_response_paginated(response_data):
"""Checks if the response data dict has expected paginated results keys
Returns True if it finds all the paginated keys, False otherwise
"""
try:
keys = list(response_data.keys())
except AttributeError:
# If we can't get keys, wer'e certainl... | 521c28c1d6e29e5785b3bcbd5d2604210b3a3874 | 702,076 |
def create_metadata_dict():
"""A Python dictionary will be created to hold the relevant metadata.
:return: dictionary with keys for the relevant metadata
:rtype: dict
"""
metadata = {'Directory': None,
'Filename': None,
'Extension': None,
'ImageType'... | 1cb7a42e21df76c13eed3fe905030bd55c7f4af9 | 702,077 |
def compute_power(rawvolts, rawamps):
"""
Compute the power. Looks trivial, but I'm gonna implement
smoothing later.
"""
power = rawvolts * 1.58
power_low = rawvolts * 1.51
power_high = rawvolts * 1.648
return power, power_low, power_high | 9202e456d4655de12ec5608011e80647cf62f7ab | 702,078 |
import argparse
def arguments():
""" Builds a generic argparse
:return: parser
"""
workdir = '/opt/nuvlabox/installation'
parser = argparse.ArgumentParser(description='NuvlaBox Agent')
parser.add_argument('--nuvlabox-installation-trigger-json', dest='nb_trigger_content', default=None, metav... | 70c4a81131c5e19a43271905e4f7b5623715cfd4 | 702,079 |
import csv
def read_aa_losses(filename):
"""
Read AA losses from data file. (assume fixed structure...)
"""
aa_losses = {}
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=',')
next(reader) # skip headers
for line in reader:
if len(line) == 0:
... | b1ba8349d01d43112ef67436fa2bb09d3bed768c | 702,080 |
def add(M1, M2):
"""
Returns a matrix Q, where Q[i][j] = M1[i][j] + M2[i][j].
M2 is replaced by Q.
"""
m = len(M1)
n = len(M1[0])
for p in range(m):
for q in range(n):
M2[p][q] = M2[p][q] + M1[p][q]
return M2 | ac86e9109f6287cde062392992bf64dbf49614f5 | 702,081 |
import sys
def azure_pipelines_broken():
"""Azure pipelines has multiple major versions of python that are broken.
The fixes for this will take a month since the regression was
first noted since they have to rebuild thier images and roll them
out which apparently takes a while (which makes me wonder ... | 1550835cf548c97fd46f6faf5f00444a46f22649 | 702,082 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.