content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def strip_html_whitespace(html_text):
"""
Whitespace in the HTML obtained is a pain when scanning for next_sibling
Clean up
"""
html_text = re.sub(">\s*", ">", html_text)
html_text = re.sub("\s*<", "<", html_text)
return html_text | 97c8c0edd70750a2e951e99a19e25a65d43e3713 | 631,949 |
import csv
def get_file_entry_names(path):
"""Get the names of all entries in the food dictionary or a log file.
:param path: A string of the food dictionary or log file pathname.
:returns: A list of the entry names associated with each entry in the food dictionary or a log file.
"""
entry_names... | de75a82755c7a93b5a94a266ee149d544bc40973 | 631,950 |
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters
Output: tuple (dist, idx1, idx2) where dist is distance between
cluster_l... | ef2275a741b40befc19065bee5568d3e13eea319 | 631,952 |
def solution(num):
"""Find the maximal sequence of consecutive ones"""
try:
num = int(num)
count = 0
if(num > 0):
while(num != 0):
num = (num & (num << 1))
count += 1
return count
except ValueError:
return 'Invalid input.' | eac3c9040e0a2eeb72eb9fded7cea12dc356ab69 | 631,953 |
def get_fn_pos_by_rules(pos, token):
"""
Rules for mapping NLTK part of speech tags into FrameNet tags, based on co-occurrence
statistics, since there is not a one-to-one mapping.
"""
if pos[0] == "v" or pos in ["rp", "ex", "md"]: # Verbs
rule_pos = "v"
elif pos[0] == "n" or pos in ["$"... | 705e39d129463ece3dae75a56d1fda72d260a196 | 631,954 |
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x += cropLeft
y += cropTop
w ... | e3532c0a9a2d031843a322d5f071ba371574bbcf | 631,955 |
def all_keys(key_possible_bytes, key_part=(), offset=0):
"""
Produce all combinations of possible key chars
"""
keys = []
if offset >= len(key_possible_bytes):
return [bytes(key_part)]
for c in key_possible_bytes[offset]:
keys += all_keys(key_possible_bytes, key_part + (c,), offs... | c4e38e17a6f02436ad70998eb53f88d067cbc8bc | 631,956 |
def utf_jungle(sym1, sym2):
"""
Input:
sym1, sym2: symbols, str() type
Output:
summ of all symnols in range
"""
code1 = ord(sym1)
code2 = ord(sym2)
hi_code = max(code1, code2)
low_code = min(code1, code2)
sum = 0
for i in range(low_code, hi_code + 1):
s... | 7432d207ad6670c5d189f5cd67da580d69267602 | 631,957 |
import typing
def fortran_test_generator() -> typing.Dict[str, str]:
"""
provides simple code block elements to test compiler feature level
"""
tests = {
"minimal": "end",
"f2008rank15": "integer :: a(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1); print*,rank(a);end",
"f2008contiguous": "pri... | 440147e2fb4f30dc2c53c6c86f4cfc67460354d7 | 631,958 |
def Rels_attach(self, rel):
"""
Inserts *rel* into *self*, performing additional necessary bindings.
Return value: *rel.target_part* (or *rel.target_ref*, if *rel.is_external*).
"""
self[rel.rId] = rel
if rel.is_external:
return rel.target_ref
target = rel.target_part
self._target_parts_by_rId[rel... | 329b6e748384b8859fefcdbc398b398937aa0acb | 631,959 |
def set_legend(ax, lines, loc=0, ncol=1):
"""set legend
Function generating a custom legend, see [1] for more options
Refs:
[1] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.legend.html
Args:
ax (object): figure part for which the legend is intended
lines (list): list o... | ccd1b705631283e0cf5f5b469da2c937b15ff99b | 631,960 |
def get_columns_to_drop(year):
"""
Returns a list of strings indicating which columns to drop for the data
in the given year
:param year: the year of the data
:return: a list of which columns to drop for the given year; "us" is always
dropped
"""
cols_to_drop = ["us"] # Always drop "us"... | 58c5e0916768355a77c245e9e7a93e5edc9d540d | 631,961 |
def process_string(input_str, offset=37):
"""Pretty Print stings too long for mouse-over.
Parameters
----------
input_str : str
The sting to-reformat
offset : int
The number of characters used as spacing for a new line.
Returns
-------
string re-formatted to fit in spec... | 199c9b6e003a501891fd093d32b673215edae068 | 631,962 |
from typing import Any
def is_chars(obj: Any) -> bool:
"""Check if an object is one of the built-in character types.
The built-in data types representing characters in Python 3 are:
str, bytes, bytearray
Arguments:
obj: object to be checked
Returns:
True if the object is an ... | d501a8326205896893f14a8a381e8f4579f36e69 | 631,963 |
def invert(x,n):
""" Inverts the bits of a positive integer. """
return x ^ ((1 << n) - 1) | 2bfdb96b47c7f8b6989381444dcd9a9f0869b5f4 | 631,964 |
def is_top_down(lines):
"""
Return `True` if dates in the given lines go in an ascending order, or `False` if they go in a descending order. If
no order can be determined, return `None`. The given `lines` must be a list of lines, ie.
:class:`~taxi.timesheet.lines.TextLine`, :class:`taxi.timesheet.lines.... | 7251ad73478cd85e0faaa229e84060bbc9c649e8 | 631,966 |
def merge_dicts(d1, d2):
"""merges/reduces two dictionaries"""
d1.update(d2)
return d1 | dff8df9f25e80fab812022e46cd89eaf90f9bbe4 | 631,968 |
def ogimage(url, html):
"""Finds the property="og:image" in the html for the preview"""
og_image = html.find_all(property="og:image")
for image in og_image:
return image.get('content')
return | 8c6605cf184d2de6cfe173f0eb63f5dfbe528469 | 631,969 |
def cleanfield(value):
"""
remove spaces
"""
if not value:
return None
value = str(value)
value = value.strip()
return value | 3f0c24da7739fdfefce9102640fff46cb76def5f | 631,970 |
def union(*graphs):
"""Return a graph having all edges from the argument graphs."""
out = {}
for G in graphs:
for v in G:
out.setdefault(v, set()).update(list(G[v]))
return out | aff9e8300df885d0249745b0bf917010f60fd8ee | 631,971 |
from typing import List
def combinationSum4(nums: List[int], target: int) -> int:
"""
Time: O(n * target)
Space: O(target)
"""
dp = [0 for _ in range(target + 1)]
dp[0] = 1
for i in range(target):
for num in nums:
if i + num <= target:
dp[i + n... | d1b6f2c0f9263a230d3320ac5bec2f6e3afbca5d | 631,973 |
import os
import textwrap
import stat
def executable_factory(monkeypatch, tmpdir):
""" Factory for creating executable files from contents. Also dedents the contents. """
monkeypatch.setenv('PATH', tmpdir, prepend=':')
def factory(name, contents='', dedent=True):
test_cmd_path = os.path.join(st... | 1e4f39587e530c2a2373feb6f459b405f8bddc12 | 631,974 |
def my_pow(m: int, n: int) -> float:
"""Binary Exponentiation
Args:
m:int,
n:float
Returns:pww
"""
res = 1.0
i = abs(n)
while i:
if i & 1:
res *= m
m *= m
i = i >> 1
if n < 0:
return 1.0 / res
return int(res) | 089606aa2db421a664539352d107bb86cf765726 | 631,975 |
import argparse
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
argv = argv[1:]
# initialize the parser object:
parser = argparse.ArgumentParser(
description="Search a path for t... | 2c2220cab1094a17aa05a30989b9666aa9c41e53 | 631,976 |
def _get_quote_indices(line, escaped):
"""
Provides the indices of the next two quotes in the given content.
:param str line: content to be parsed
:param bool escaped: unescapes the string
:returns: **tuple** of two ints, indices being -1 if a quote doesn't exist
"""
indices, quote_index = [], -1
fo... | 7bc8019af99730de306062389ad6c24b582f3ebf | 631,977 |
def import_from(module, name):
""" Try to import a module and class directly instead of the typical
Python method. Allows for dynamic imports. """
module = __import__(module, fromlist=[name])
return getattr(module, name) | 2d39de8111afd8f2ab7171f01476a448ca8effc9 | 631,979 |
import random
import itertools
def random_tuple_list(lst1, lst2, lb=1):
"""
Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2
"""
len_lst1 = len(lst1)
len_lst2 = len(lst2)
k = random.randint(lb,max(len_lst1,len_lst2))
return random.sample(list(itertools.product... | bb70477ba997694f464ad1757067be1f5815d18a | 631,980 |
from datetime import datetime
def timestamp():
""" Generates an ISO 8601 timestamp for the current UTC time.
Returns:
str: ISO 8601 timestamp
"""
return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') | a631a88f026bad3e7b0e11138ae5fa9de0dbea73 | 631,981 |
def create_email_field_dict(field_name,
field_type,
field_value,
field_displayed_text,
is_allow_create_indicator,
is_href,
is_editable,
... | fd7844bd040f61703d4f36d572ee097f60009090 | 631,982 |
def inflate(size, margin, mul=1):
"""
Increase size (a size or rect) by mul multiples of margin
margin's items are interpreted as those of a CSS margin. If size is a
4-tuple, its "sides" are moved outwards by the corresponding items of
margin; if it is a 2-tuple, it is treated as if it were a rect ... | 709cc5d4e2609e5f5a49e78656117278e8812ae4 | 631,983 |
def Cindex (i,j,k,Nx,Ny,Nz):
"""z changes fastest """
return i*Nz*Ny+j*Nz+k | 86e92deb1d0fe6e1ec4f0d40219ef93e8b5c1970 | 631,984 |
from typing import TextIO
import csv
def parse_chanjo_sexcheck(handle: TextIO):
"""Parse Chanjo sex-check output."""
samples = csv.DictReader(handle, delimiter='\t')
for sample in samples:
return {
'predicted_sex': sample['sex'],
'x_coverage': float(sample['#X_coverage']),
... | 5d0360aa41fa01cfb550ea6cdcfd16d623d03401 | 631,987 |
from pkg_resources import parse_version
from setuptools import __version__
def have_environment_marker_support():
"""
Check whether setuptools has support for PEP-426 environment markers.
Based on the ``setup.py`` script of the ``pytest`` package:
https://bitbucket.org/pytest-dev/pytest/src/default/s... | 2a5306d6371c59f1e68cbe4ee63adb3afed9c1ff | 631,988 |
import socket
def bind(port, socket_type, socket_proto):
"""Try to bind to a socket of the specified type, protocol, and port.
This is primarily a helper function for PickUnusedPort, used to see
if a particular port number is available.
For the port to be considered available, the kernel must support ... | b2700e7589bff8ae4b51c309fd90b119478e7ce0 | 631,989 |
def count_occurances(comment, word):
"""
A helper function to get the number of words in a comment.
"""
comment = comment.replace('?', ' ')
comment = comment.replace('.', ' ')
comment = comment.replace('-', ' ')
comment = comment.replace('/', ' ')
a = comment.split(" ")
count = 0
... | b4c5c5e0a7792e29811937a1e77161196bd9856c | 631,990 |
import random
def choose_random_elements(_list, num_elements=5000):
"""
Choose a certain number of elements from given list randomly and return the
original list without the chosen elements as well as a list of the chosen
elements.
:param _list: list with elements to be chosen from
:param num_... | 1ebe29cc7d4a784d4805c762feca523d8ee4c293 | 631,991 |
def hybridmc_new_files(pref):
"""file formats for HybridMC output and the following zcombine output"""
pref = pref.strip()
mcmc = pref + '.mcmc'
mcscrn = mcmc + '.scrn'
mczc = mcmc + '.zc'
return (mcmc, mcscrn, mczc) | d9edcada07bcf78c8f48b9751d988b7b5fa82bc5 | 631,992 |
def clip_by_value(t, clip_value_min, clip_value_max):
"""
Clips tensor values to a specified min and max.
Parameters
----------
t : tensor
A Tensor or IndexedSlices
clip_value_min : tensor
A 0-D (scalar) Tensor, or a Tensor with the same shape as t. The minimum value to clip by
... | acf241cfd27fea3d093df7feaa177118e1e7f6b3 | 631,993 |
from typing import List
import argparse
def parse_args(args: List[str]) -> argparse.Namespace:
"""Parse arguments from the cli"""
parser = argparse.ArgumentParser(prog="publish-shared-event", description="List the content of a folder")
parser.add_argument("-r", "-region", dest="region", help="Set AWS Regi... | 9a589c2062add0a675010dabe23fbe515d59a46f | 631,994 |
import json
def get_secret_dict(service_client, arn, stage, token=None):
"""Gets the secret dictionary corresponding for the secret arn, stage, and token
This helper function gets credentials for the arn and stage passed in and returns the dictionary by parsing the JSON string
Args:
service_clie... | 330c5ccb70e5c117d14efb6908865fdf4dcc3a26 | 631,995 |
def assertVolumesEqual(test, first, second):
"""
Assert that two filesystems have the same contents.
:param TestCase test: A ``TestCase`` that will be the context for this
operation.
:param Volume first: First volume.
:param Volume second: Second volume.
"""
first = first.get_filesy... | 34b21ff42a350e151e6a7b824d24a5897eec7073 | 631,996 |
import pickle
def read_pkl(pkl_filename):
"""Loads pickle file."""
with open(pkl_filename, "rb") as pkl_file:
return pickle.load(pkl_file) | 4c62d14e47ebb78c9aefe23c0f0bc488f21d5500 | 631,997 |
import math
def AMS(s, b, br=10.0):
""" Approximate Median Significance defined as:
AMS = sqrt(
2 { (s + b + b_r) log[1 + (s/(b+b_r))] - s}
)
where b_r = 10, b = background, s = signal, log is natural logarithm """
radicand = 2 *( (s+b+br) * math.log (1.0... | a8ff6697d0e3ffc83ce1b74b289c291c96e47dd5 | 631,998 |
def conteo_buenas_notas(notas: dict) -> int:
""" Materias Excepcionales
Parámetros:
notas (dict): Diccionario con las notas del estudiante
Retorno:
int: Número de materias excepcionales
"""
excepcionales = 0
if notas["Matematica"] > 4:
excepcionales += 1
if notas["Ingles"... | ec00fa2490e4733e36c3faac0103623a6d2be78a | 631,999 |
def time_to_iso(time_struct):
"""
time to iso format
"""
#return '%(hour)s:%(minute)s' % time_struct
hour = int(time_struct['hour'])
if not hour:
hour = '00'
return '%s:%s' % (hour, time_struct['minute']) | ba469d87335a9074317937c513fd2e6c6a36e2f1 | 632,000 |
from pathlib import Path
def relative_path_for(provided_path: Path, root_path: Path) -> Path:
"""
Return relative path to root is provided path is on root_path, If not return the provided path
Parameters
----------
provided_path : Path
absolute or relative path
root_path : Path
... | 363939399830c507a292247c45f611cdf8e6dccb | 632,001 |
def download_file(s, url, data_dir):
"""
Download the provided file and place it in data_dir
"""
local_filename = data_dir + url.split('/')[-1]
# NOTE the stream=True parameter
req = s.get(url, stream=True)
with open(local_filename, 'wb') as local_f:
for chunk in req.iter_content(chu... | 1dc6de0cab26d9bb603888e8c7ed0730a4ba941b | 632,003 |
import os
import re
import subprocess
def _pdf_to_txt(file_path, dst_dir, file_name):
"""
Uses the pdftotxt unix util, with --layout option, to convert file_name
to .txt and save in dst_dir
Notes
-----
Download and install Xpdf from http://www.foolabs.com/xpdf/download.html
Follow the ins... | c8b770fe8caddb0dff7417dc0f3fb5cb7b3438bc | 632,004 |
def vsstd(a, s=0.1):
"""Normalize the image range for visualization."""
return (a - a.mean()) / max(a.std(), 1e-4) * s + 0.5 | 46cb71073d743d43ce29d1eca75cfa03be1fa33b | 632,005 |
def has_file(conn, path, mirror_id):
"""check if file 'path' exists on mirror 'mirror_id'
by looking at the database.
path can contain wildcards, which will result in a LIKE match.
"""
if path.find('*') >= 0 or path.find('%') >= 0:
oprtr = 'like'
path = path.replace('*', '%')
... | ae68cd1adfad092b554e2df3dfcad622983d4e93 | 632,006 |
import random
def get_random_block_from_data(data, batch_size):
"""Randomly select batch_size number of contiguous samples."""
start_index = random.randint(0, data.shape[0] - batch_size)
return data[start_index:(start_index + batch_size)] | 36281d986c24a83eb19af65367d8bd652879e1d0 | 632,007 |
import torch
def l2_loss(input, target, size_average=True):
""" L2 Loss without reduce flag.
Args:
input (FloatTensor): Input tensor
target (FloatTensor): Output tensor
Returns:
[FloatTensor]: L2 distance between input and output
"""
if size_average:
return torch.me... | eb23f6013ce8ac92aa1f00bdd675d30a0b94d7f9 | 632,008 |
def GetNextQtnodeBounds(qtnode, x, y, size):
"""Calculate next level boundary for qtnode.
If the qtnode has further precision, call this routine
recursively.
Args:
qtnode: The remaining string of the qtnode.
x: Current left of the qtnode (degrees).
y: Current bottom of the qtnode (degrees).
si... | f3b1bea59f68ad4d3e7b05ad65fe856172547f44 | 632,009 |
from typing import Any
from typing import Dict
from typing import List
def get_data_list_from_timeseries(data: Any) -> Dict[str, List[float]]:
"""Constructs a Dict as keys are the container names and
values are a list of data taken from given timeseries data."""
if data['status'] != 'success':
rai... | 6084188f57e5dc9bd85c36ac3e38c853e45b0584 | 632,010 |
import yaml
def test_dataset_serialization(client, dataset, data_file):
"""Test Dataset serialization."""
def load_dataset(name):
with open(str(client.get_dataset_path(name))) as f:
return yaml.safe_load(f)
d_dict = load_dataset('dataset')
expected_fields = [
'_id', '_la... | 67826fdb061b0189d6232c6da247c281265ab7e3 | 632,011 |
from typing import OrderedDict
def find_overlaps(orfs_found):
"""Associates overlapping ORFs based on their start-stop intervals"""
# initialize dictionary to store associations for each ORF
overlaps_found = { i : [] for i in range(1, len(orfs_found)+1) }
processed_orfs = []
# sort ORFs by asce... | c638e9896dda1015ef3ff22d3fcf76fb91280e6b | 632,012 |
def divisibleBy3And5(num):
"""assumes num is a number
returns True is num is divisible by 3 and 5, else 5
"""
return num % 3 == 0 and num % 5 == 0 | 8d1fbf13b300ce7b53cc66ba9bcfd16959ae33c3 | 632,013 |
def conflicted(path_to_file):
"""Whether there are any conflict markers in that file"""
for line in open(path_to_file, 'r'):
for marker in '>="<':
if line.startswith(marker * 8):
return True
return False | 96eb92f437cd4acfe8b16c79b6fc7cd961a58742 | 632,014 |
from typing import Dict
from typing import Any
def _get_client_ip_from_meta(meta: Dict[str, Any]) -> str:
"""Attempt to get the client's IP by checking common HTTP Headers.
Returns none if no IP Could be found"""
headers = (
"HTTP_X_FORWARDED_FOR",
"HTTP_X_REAL_IP",
"REMOTE_ADDR",
... | 251e7ce47c13ceb4ee2e11009dd9addcaa1e5cf0 | 632,015 |
def getDate(year, month, day):
""" Get date string from year month and day"""
return str(year)+'%02d' %month+'%02d' %day | a10f17f6fcec17adb259ad170479db8cb15bb013 | 632,016 |
def mutate_individual(logger, ind):
"""
Simply calls the mutate function of the given individual.
Args:
logger (:obj:`logging.Logger`): A logger to log with
ind (:obj:`actions.strategy.Strategy`): A strategy individual to mutate
Returns:
:obj:`actions.strategy.Strategy`: Mutate... | a2d3fdc6f04549c81777cf8a45f0ea799b58dc76 | 632,017 |
def boolean_bitarray_get(integer, index):
"""The index-th-lowest bit of the integer, as a boolean."""
return bool((integer >> index) & 0x01) | 0504743080583bc03fc75214d1ffb01f0f6371cf | 632,019 |
import os
def file_readable (fn, **kwargs):
"""Check if the file is readable"""
return os.path.isfile (fn) and os.access (fn, os.R_OK) | 70d32b7a347a0c9797cbfbc0df948d9815eadd72 | 632,020 |
def ExtractUnits(hf,k):
"""
Returns all the data for a single key (column) in a given HDF5 file.
Parameters
----------
hf : File
The HDF5 where the data is stored.
Example:
HDF5_File = h5py.File(filename, 'r')
k : str
the name of the column that is to be extr... | 94d4533710b8dd35b3f26b52accf9d89fe074b22 | 632,021 |
def _get_columns(x):
""" retrieve the columns of something if it exists """
if hasattr(x, "columns"):
return list(x.columns)
else:
return None | 9b62a7fb4856c35ff8f6a2ce6d948c01b47a6871 | 632,022 |
import sys
def main():
"""
Set high so can never break a solvable algorithm if not entered
"""
number_of_solutions = 1000
print("Welcome to our case Chips and Circuits! By De Mandarijntjes \n --------------------------")
net_option = input("Please enter a integer from 1 to 6 to choose a netlis... | b346514408fdeb15e6ee4fec4a8cd3f779fc3543 | 632,023 |
def step1(all_voronois, structure, radius, anions, min_neighbors):
"""
Remove sites with Voronoi points that have fewer than 4 neighboring anions
:param all_voronois: (List of Sites) list of all sites in structure1 containing Voronoi points
:param structure: (Structure) target structure
:param radi... | fe515da7311eb99cc42d959f6f1fb62715e99c43 | 632,024 |
import hashlib
def branch_hash_worktree_path_builder(branch):
"""Returns a relative path for a worktree based on the hash of the branch
name.
"""
return hashlib.md5(branch.encode("utf-8")).hexdigest() | 7b01cba489cd58e87459c8fc33a06193c1bafdd0 | 632,025 |
def from_gca_linestring(gca_obj):
"""
Converts LineString GCA to an EGF string.
Returns
-------
egf_str : str
LineString GCA as an EGF string
"""
if gca_obj.geometry_type != "LS":
raise ValueError(f"Expected geometry type to be 'LS' and got '{gca_obj.geometry_type}' instea... | 976b59d1cfd8d3ae4620416fcddf5104f8de83ba | 632,026 |
def rm_additional_rots_and_trans(results):
"""
Removes the first 6 rotations and translations, to leave
the required 3N vibrations.
"""
for key, value in results.items():
results[key] = value[6:]
return results | 64974127141dbbae44056d25c1ca0042b97a3fb6 | 632,027 |
from typing import Sequence
from typing import Any
from typing import Callable
def _transform_args(
args: Sequence[Any],
varnames: Sequence[str],
transform_func: Callable[[Any], Any],
conditional: Callable[[str], bool] = lambda _: True,
) -> Sequence[Any]:
"""Transform given args if condition is m... | a7ded48f8ae23d7c357cacc3a691856873e37948 | 632,028 |
def get_tableau_values(data):
"""
Tableau's data lists all the values used throughout the view in a single
place, and the display information about each chart references these values
by data type (int, cstring, etc.) and index.
Return a simplified version of this: a dict mapping data types to lists... | c2f0f4c501a95e42add883ff7de63df28162ee93 | 632,029 |
from typing import Tuple
def generate_command_parameters(command: str) -> Tuple[str, int]:
"""Helper function to generate parameters from commands passed as string.
A command string is converted to a (action: str, step: int) tuple.
Pattern is:
command is an "action step" string than we can split ... | d30664e808ec03f29e8835698145dcf75072d1d9 | 632,030 |
def find_peak(f, xmin, xmax):
"""Find integer peak of f(x) for x \in [xmin, xmax]. T = O(log(n)).
The frist derivative of f(x) must be monotonic. (by YL)
+---------------+----------------+
| xmax - xmin | # calls of f |
+---------------+----------------+
| 50 | 23 |
... | 3f0a3c4d399a6df5b541cd8cb479e0259283a79b | 632,031 |
def intToRoman(n: int) -> str:
"""Converts an integer to Roman form
Args:
n (int): Integer to convert
Returns:
str: Integer in Roman form
"""
return 'M' + intToRoman(n - 1000) if n >= 1000 \
else ('CM' + intToRoman(n - 900) if n >= 900 \
else 'D' + intToRoman(n ... | 94e6a740a4a58c28187193f661d2e225d0034015 | 632,032 |
import torch
def out_binary_weighting(tr_out, n_qubits, trans_type='mean'):
""" Returns two numbers of mu and sig for training the output. The input is soething that has been transformed
to lie between 0 and 1 """
weights = torch.tensor([2 ** (n_qubits - i - 1) for i in range(n_qubits)])
if len(t... | 145bb802e5634fd7fa2d37ac179bbdded68e0b87 | 632,033 |
def usable_decode(text: bytes) -> str:
"""Decode the text so it can be used.
vars:
:param text: a string of bytes that needs decoding
:returns: string
"""
try:
decoded_text = text.decode("utf8")
except:
decoded_text = text.decode("latin1", errors="replace"... | e238c6f082349cc0409bce26045dfa1de2e03bd8 | 632,034 |
def get_adjusted_price(price, currency, currency_data):
"""Return adjusted price and name of company the label is referring to.
If a user wants the price value in a currency different from the dollar
this function computes the stock value in such currency.
:param price: The price of the stock of the c... | bb7cd9b0180a77415329959a6f4178cf6448a507 | 632,035 |
import os
def __return_file_path(file_path, app):
"""
Expands the ~/ into current users home directory
"""
return os.path.expanduser(file_path.format(app)) | 5607484c212dba3f5f9b933512a2015bf4789256 | 632,038 |
def wrapTex(tex):
""" Wrap string in the Tex delimeter `$` """
return r"$ %s $" % tex | d85184194746b7806f2fe5b4ee214b6f5ea67dbc | 632,039 |
def split_geolocation_string(config, geolocation_string):
"""Fields of type 'geolocation' are represented in the CSV file using a
structured string, specifically lat,lng, e.g. "49.16667, -123.93333".
This function takes one of those strings (optionally with a multivalue
subdelimiter) and return... | d3b50c2a9a6d26f1e65ea5245d576bbcd65e104d | 632,040 |
def lift(rho, v, S, C_l):
"""
>>> lift(1.225, 17, 0.78, 1.2)
165.68370000000002
"""
return rho * v**2 * S * C_l / 2 | 95800f06cfce1371db0d9f47aaae301973e596b0 | 632,041 |
import random
def raffle(tickets, lots):
"""Run a raffle, producing a list of randomly selected winners.
Arguments:
tickets -- a list containing (name, number of tickets purchased) tuples
lots -- a list of lots available to be won
Each ticket can only win once, but people purchasing multiple tic... | 25a6254e6e74a208874d946579798eb7c89d2b8c | 632,042 |
def fix_projection(shape, axes, limits):
"""Fix the axes and limits for data with dimension sizes of 1.
If the shape contains dimensions of size 1, they need to be added
back to the list of axis dimensions and slice limits before calling
the original NXdata 'project' function.
Parameters
... | b2308c7f398a19b5caf3f853ba47c1d254a5332d | 632,043 |
def macaddr_pack(data, bytes = bytes):
"""
Pack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c, and PGSQL Manual types
"""
# Accept all possible PGSQL Macaddr formats as in manual
# Oh for sscanf() as we could just copy PGSQL C in src/util/adt/mac.c
colon_parts = data.split(':')
dash_parts = d... | 3a2cb426e0f86516cc34feb52e4e13f9227127e2 | 632,045 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Head pose estimation for images using the Hopenet network.')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use. Default: 0',
default=0, type=int)
pa... | d2f7662159e1ae6fdbfc9cb98fa07620ea36139e | 632,047 |
import sys
def trace_function(funcobj, *args, **kwargs):
"""Call a function, and return its locals"""
funclocals = {}
def _tracefunc(frame, event, arg):
# Activate local trace for first call only
if frame.f_back.f_locals.get('_tracefunc') == _tracefunc:
if event == 'return':
... | a31ef9b5e7b2a3c1a067369db03edd888b9ee2ab | 632,048 |
import os
def _read_content_or_path(content_or_path):
"""
If `content_or_path` contains ``\\n``, return it. Else assume, that it is
path and read file at that path.
Args:
content_or_path (str): Content or path to the file.
Returns:
str: Content.
Raises:
IOError: whhe... | fa0ba11c8766d96cbd4ce38bfc05337cb607b8ba | 632,050 |
def constraint_class(kind):
"""
The convention is that name of the class implementing the constraint
has a simple relationship to the constraint kind, namely that
a constraint whose kind is 'this_kind' is implemented by a class
called ThisKindConstraint.
So:
``min`` --> ``MinConst... | d4542f2a4ec6bb86efe26139ab513e0f0930181c | 632,051 |
import os
import re
def get_snr(ppath, name):
"""
read and return sampling rate (SR) from file $ppath/$name/info.txt
"""
fid = open(os.path.join(ppath, name, 'info.txt'), newline=None)
lines = fid.readlines()
fid.close()
values = []
for l in lines :
a = re.search("^" + 'SR' + ... | 3558884d616ad773698b95121532c628753dc20e | 632,052 |
def coerce_int(obj):
"""Return string converted to integer.
.. Usage::
>>> coerce_int(49)
49
>>> coerce_int('49')
49
>>> coerce_int(43.22)
43
"""
try:
return int(obj) if obj else obj
except ValueError:
return 0 | 47ff1a15c78786e9b29a7e9eb80bd1cbe8b0be45 | 632,053 |
def taux_boost(cote, boost_selon_cote=True, boost=1):
"""
Calcul du taux de boost pour promotion Betclic
"""
if not boost_selon_cote:
return boost
if cote < 2:
return 0
if cote < 2.51:
return 0.25
if cote < 3.51:
return 0.5
return 1 | a861295332469c5a68a2dcb3a24989d64a66e543 | 632,054 |
import argparse
def parse_arguments():
"""
Parse user arguments
Output: list with all the user arguments
"""
# All the docstrings are very provisional and some of them are old, they would be changed in further steps!!
parser = argparse.ArgumentParser(description="""""")
... | 4d7960466773019fd8e63c146233415e0f2c49af | 632,055 |
def cal_outlet_year(df):
""" Calculating the Outlet Year
"""
#Years:
df['Outlet_Years'] = 2013 - df['Outlet_Establishment_Year']
return df | b182e58df13e0994732455981aeddc9abeb12494 | 632,056 |
def part1(entries: dict) -> int:
"""part1 solver"""
mem = dict()
mask_set0s = 0
mask_set1s = 0
for entry in entries:
if entry['type'] == 'mask':
mask = entry['value']
mask_set0s = int(mask.replace('X', '1'), 2)
mask_set1s = int(mask.replace('X', '0'), 2)
... | cd4539679aa1bb1a5d251e1209008e0a6937dc09 | 632,057 |
from typing import Tuple
from typing import Optional
def split_module(path: str) -> Tuple[Optional[str], Optional[str]]:
"""Split module and system path."""
if not path.startswith('@'):
return None, path
index = path.find('/')
if index == -1:
return path[1:], None
else:
re... | 7e3a1c127c41e428fe118d2e024e2a21eeba29cf | 632,059 |
import itertools
def vertex_color_qubo(G, colors):
"""Return the QUBO with ground states corresponding to a vertex coloring.
If `V` is the set of nodes, `E` is the set of edges and `C` is the set of
colors the resulting qubo will have:
* :math:`|V|*|C|` variables/nodes
* :math:`|V|*|C|*(|C| - 1)... | 2e672d8a816d05aa9067cadc738c91d86be7ecbd | 632,060 |
import copy
def swap_ele(mat, pos1, pos2):
"""
Definition
---
Method to swap elements of a node from pos1 to pos2
Parameters
---
mat : Node of which the elements are to be swapped
pos1, pos2: Positions of the elements to be swapped
Returns
---
mat1 : New node after swappi... | 38634d94c527363cfb96808f5b95b5313873b616 | 632,061 |
def expand(pos, s, offset=False):
"""find a palindrome by expanding around the center
>>> expand(1, 'abc')
'b'
>>> expand(1, 'aaa')
'aaa'
>>> expand(0, 'bb', True)
'bb'
"""
if offset: # shift right pos by 1
right = pos + 1
left = pos
else:
left = right =... | 294c60975097ded2411d61bd730cb26d6f137821 | 632,062 |
def get_user_conhap_json_list(user_conhaps):
"""
Make json objects of the user conhaps and add them to a list.
:param user_conhaps: conhap
:return:
"""
conhaps = []
for user_conhap in user_conhaps:
conhaps.append(user_conhap.json())
return conhaps | ba5836a79ea8a77243464baec56aeef90f1ab581 | 632,063 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.