content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def XOR(a, b):
""" Returns a XOR b (the 'Exclusive or' gate)
Args:
a (bool): First input
b (bool): Second input
Returns:
bool: The output of the XOR gate
"""
return ( a - b ).abs() | 6f98c5ab8ff5709e3f923163c6bad3e4e96cebdf | 644,823 |
import warnings
def skopt_get_setting(self):
"""Find the next parameters to test.
"""
# params = self._optimizer.ask()
# return params
with warnings.catch_warnings():
warnings.filterwarnings("ignore", module='skopt')
warnings.filterwarnings("ignore", module='sklearn')
meth... | 961b88d7c660852f31034ddb0e9d8bb0206aa4a8 | 644,824 |
import random
def gene_gen(number_of_genes):
"""
Генерирует последовательность из 1 и 0, кратную 9
"""
gene = ''
for i in range(number_of_genes*9):
gene += random.choice('01')
return gene | 0dce0d25839ab9f19d4384c627e4182787904341 | 644,825 |
import os
def secret_filename(dependencies, _maybedeps):
"""
The filename to put the encrypted secrets in.
"""
if 'VOYNICH_FILE' in dependencies['environment']:
return dependencies['environment']['VOYNICH_FILE']
return os.path.join(dependencies['current_directory'], 'voynich.json') | 3dcf5191c5e4e7189afa1c4c0532d226fb180f0a | 644,826 |
def convert_volts(data, places):
"""function to convert data to voltage level,
rounded to specified number of decimal places"""
volts = (3.3*data) / float(1023)
volts = round(volts, places)
return volts | a680247217961eeac8b28285e9a701518624bb9b | 644,827 |
def lorem_ipsum():
"""
Returns 'Lorem ipsum...' text.
See: [lipsum.com](http://www.lipsum.com/)
:return:
>>> lorem_ipsum() #doctest: +ELLIPSIS
'Lorem ipsum dolor sit amet, consectetur ..., hendrerit nulla.'
>>> len(lorem_ipsum())
6877
"""
return '''Lorem ipsum dolor sit amet... | 7edd3e8e8cf9b8dc0f1097ff0302e61008cb37df | 644,828 |
def filter_out_none(dictionary, keys=None):
""" Filter out items whose value is None.
If `keys` specified, only return non-None items with matched key.
"""
ret = {}
if keys is None:
keys = []
for key, value in dictionary.items():
if value is None or key not in keys:
... | c7c1e3894beb55c7e978dd6822e091924dd58a5c | 644,829 |
def read(filename, binary=True):
"""
Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise
"""
with open(filename, 'rb' if binary else 'r') as f:
return f.read() | 8faf5df9bfa326945dce4eec25efb32a12b2cd18 | 644,830 |
from typing import List
def prime_factors(n: int) -> List[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)... | 81ff86ca963f090cbc3d7e470191dca918dc92f7 | 644,831 |
import string
def decrypt(message, key):
"""
>>> decrypt("Tqxxa iadxp",12)
'Hello world'
>>> decrypt("Ck gxk Vktt Yzgzk!!!",6)
'We are Penn State!!!'
>>> decrypt("Bj fwj Ujss Xyfyj!!!",5)
'We are Penn State!!!'
>>> decrypt(5.6,3)
'error'
>>> ... | bdcd281d876fe189e24117c2732ab798796a6834 | 644,832 |
def color_float_to_hex(r, g, b):
"""Convert RGB to hex."""
def clamp(x):
x = round(x*255)
return max(0, min(x, 255))
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b)) | e8e82ecd5f6f418cdc0cd72f0b799d1dd0ad6b1d | 644,834 |
def propeller_navbar(navbar):
"""
Render a navbar.
**Tag name**::
propeller_navbar
**Parameters**:
navbar
The previously defined navbar instance
**Usage**::
{% propeller_navbar navbar_instance %}
"""
return navbar.as_html() | 24a318e7b3803a64f1dab695fcc0346c03e694bb | 644,835 |
def pred_acc(f_pred, prepare_data, options, iterator, verbose=False):
"""
Just compute the accuracy
f_pred: Theano fct computing the prediction
prepare_data: usual prepare_data for that dataset.
"""
valid_acc = 0
n_done = 0
for x1, x2, y in iterator:
n_done += len(x1)
x1... | b8cb205fdf3571d08babd0717b7024d1558030d1 | 644,836 |
def make_conditional_posterior(posterior, settings):
"""
Conditions the posterior on the fixed variables
:param posterior: full posterior distribution
:type posterior: :class:`binf.pdf.posteriors.Posterior`
:param settings: simulation settings as specified in a
config file
... | 1f9d06fb30421540398e93acd8da86dd147c6ebd | 644,837 |
from typing import Dict
from typing import Any
import yaml
def load_data() -> Dict[str, Any]:
"""Mangle the "vision" database fixture into somthing that resembles a Shopify
render context.
We're trying hard to transform input data to match that of the reference
implementation so that we can do a dire... | 352a1952352acd898e48e552f1411c474cccbe5a | 644,838 |
import networkx
def eccentricity(G, v=None, sp=None):
"""Return the eccentricity of nodes in G.
The eccentricity of a node v is the maximum distance from v to
all other nodes in G.
Parameters
----------
G : NetworkX graph
A graph
v : node, optional
Return value of specifie... | 339005ab3f7947b943013a71863fb054ec2595f7 | 644,839 |
def is_placement_possible(y, x, n, board):
"""
Returns whether or not a number can be placed at a provided coordinate
This function uses the following format: board[y][x] == is_placement_possible(n)?
:param x: the provided x coordinate (the column number from left)
:param y: the provided y coordinate (the row num... | ae212ac9aae142a385035bfbc9cd49a9aacb2322 | 644,840 |
import numpy
def fftdeconvolve(image, kernel):
""" Function that deconvolves and image with a kernal using FFT.
Parameters
----------
image: array
a 2D image data.
kernel: array
a 2D kernel.
Returns
-------
out: array
the deconvolved image.
"""
x = num... | 3732ab4cbd1e5c98dfe0e1fe85c68af7cf9b5def | 644,841 |
def moeda(preco=0, valor='R$'):
"""
-> Faz a conversão do número real para moeda R$.
:param preco: preço a ser convertido.
:param valor: definida como padrão para o Real Brasileiro.
:return: retorna o preço formatado no Real Brasileiro.
"""
return f'{valor}{preco:.2f}'.replace('.', ',') | fb1267fd834ac4626fe49ce0aefd36a6dce1f8c2 | 644,842 |
import subprocess
def ls(path = '.', args = ''):
""" Invoke the shell ls command with args on path"""
a = subprocess.Popen(' ls' + ' ' + args + ' ' + path, stdout = subprocess.PIPE, shell = True)
(output, err) = a.communicate()
return output | 913d15ced6e1c4d90bc942151eff1e7d502aacb5 | 644,843 |
def totalCredits (theDictionary):
"""Calculates the total credits student is taking this semester.
:param dict[str, int] theDictionary: The student's class information
with the class as the key and the number or credits as the value
:return: The total credits
:rtype: int
"""
total = 0 ... | 996175a794947d21424d006e95378c537ee37abf | 644,844 |
import os
import io
def open_relative(*path):
"""
Opens files in read-only with a fixed utf-8 encoding.
All locations are relative to this setup.py file.
"""
here = os.path.abspath(os.path.dirname(__file__))
filename = os.path.join(here, *path)
return io.open(filename, mode="r", encoding="... | 988a8443b60ac95f973cb68f51c6e505b55ca1e4 | 644,845 |
def _cap_first(s: str) -> str:
"""Returns string with first character capitalized. Why this isn't in
the Python stdlib is beyond me. The capitalize() function annoyingly
lowercases the rest of the string."""
return s[:1].upper() + s[1:] if s else s | b9f45070cfc0822c6bd498e9a116161095fe66f5 | 644,846 |
def test_temp_album_name_2(photoslib):
""" test _temp_album_name when album name exists """
def make_temp_name_func():
count = 0
def temp_name(*args):
nonlocal count
count += 1
return f"New Album {count}"
return temp_name
old_temp_name = photos... | a9091d20d805ef065c3b1145188ba6ec9e3f0e91 | 644,847 |
import time
import requests
def get_new_token(client_id, client_secret, refresh_token, scope, url):
"""
Get a new access token using a refresh token
"""
creation = time.time()
data = {'client_id':client_id,
'client_secret':client_secret,
'grant_type':'refresh_token',
... | 1ccc95048970977d8edad680ee47407562008b1c | 644,848 |
def angle_brackets(s, fmt_spec):
"""
Surrounds the string with 《 》 characters. Useful when verifying string
truncation i.e. when checking the UI these characters should be visible.
:param s: String to surround
:param fmt_spec: Regex for placeholders.
:returns: String surrounded with 《 》
""... | 9935a85c17dc715ad939d047ac7a42881b21b5ba | 644,849 |
from typing import List
import subprocess
import os
def invoke_command(args: List[str]) -> int:
""" Same as calling Python's subprocess.call() method, but explicitly
raises a different exception when the command length is too long.
See https://github.com/Breakthrough/PySceneDetect/issues/164 for details.... | 69118e27a19c408d7f651d402c9b427afd729079 | 644,850 |
def flatten_list(list_):
""" Returnerar en endimensionell lista [a, b, c, d, e],
givet en tvådimensionell [[a, b], [c], [d, e]]
"""
return [inner
for outer in list_
for inner in outer] | 886f8fa79b16bf5092c0401e32fecde4b38ca004 | 644,851 |
import logging
def initialize_logger(file_dir):
"""Print the results in the log file."""
logger = logging.getLogger()
fhandler = logging.FileHandler(filename=file_dir, mode='a')
formatter = logging.Formatter('%(asctime)s - %(message)s',"%Y-%m-%d %H:%M:%S")
fhandler.setFormatter(formatter)
logg... | 7578c29a062f75316929d345e64c227e0ea0eda1 | 644,852 |
def build_mapbox_geo_data(df_geo, text_col='description', markers=None):
"""Build Mapbox geolocation inner data struct.
:param df_geo: a geolocation DataFrame.
:type df_geo: pd.DataFrame
:param text_col: column name for text.
:type text_col: str
:param markers: markers to be displayed on map.
... | 366a58c7e8bf3da8c903b45ac23917764a28c8a0 | 644,853 |
def calc_radiated_power_nadir(radiance_integrated,
pixel_resolution_along,
pixel_resolution_cross):
"""
Calculate the power radiated from a ground pixel at Nadir.
Returns
-------
double : Watts per Sterradian.
"""
return radiance_... | af81e9eaef7091d3794870fd6bfb89a977f47b1e | 644,854 |
def create_z_matrix(first_atom, second_atom, third_atom, species, genome):
"""Create the z-matrix string for a genome"""
matrix_str = first_atom + "\n"
matrix_str += second_atom + " 1 " + str(genome[0]) + "\n"
matrix_str += third_atom + " 1 " + str(genome[1]) + " 2 " + str(genome[2]) + "\n"
i =... | 8217f60b362b3672e502615b9770696dea4e6257 | 644,855 |
def apply_fs(tmpdir, contents):
"""
Create the directory structure specified in ``contents``.
It's a dict of filenames as keys and the file contents as values. If the
value is another dict, it's a subdirectory.
"""
for filename, content in contents.items():
if hasattr(content, 'items'):... | 69351c2e6a9d950b057d5a0c8af8b3ea00202cfd | 644,856 |
def init_Npad(ROI, compression = 8):
"""Calculate the Npad for padding
can be adjusted with compression parameter
By default, 8 times smaller than ROI
"""
if (ROI[2]-ROI[0])>(ROI[3]-ROI[1]):
Npad = (ROI[2]-ROI[0])//compression
else:
Npad = (ROI[3]-ROI[... | 43044e85ae47202dfeaec09aca750596a5785ab8 | 644,857 |
def auto_capitalize(text, state = None):
"""
Auto-capitalizes text. `state` argument means:
- None: Don't capitalize initial word.
- "sentence start": Capitalize initial word.
- "after newline": Don't capitalize initial word, but we're after a newline.
Used for double-newline detection.
... | 01c0edeea8da059876a4d05cd8b51432cb9c842b | 644,858 |
import os
def get_filenames(root_path,ignore_postfix=[]):
"""
获取指定目录下的文件的完整路径,并过滤指定后缀的文件
文件名为byte格式
"""
filenames=[]
for dirpath, dirs, files in os.walk(root_path):
for file in files:
filename=os.path.join(dirpath,file)
if os.path.splitext(filename)[-1] in ignor... | f0bebe449dc744ac7974e321de9c18105413fd8b | 644,859 |
def get_bearer_token(request):
"""Extracts a Bearer authentication token from the request and returns it if present, None
otherwise."""
auth = request.headers.get("Authorization")
if auth is not None:
try:
method, content = auth.split(" ")
if method == "Bearer":
... | 9e0c1ec830e00b18eae13aea22aab6fe67f469b6 | 644,860 |
import csv
def specification_file_read(spec_file_name):
"""
Returns the input from a CSV file as a dictionary.
Args:
- spec_file_name (String): Path to the CSV file.
Returns:
- (Dictionary(String:String)): Returns a list of Dictionaries mapping
the tables row entrys to the co... | 16d739d2fe1316ebf7d3ad070be7cee8bf05df20 | 644,861 |
import base64
def BinaryEncode(value):
"""If None, returns empty string. Otherwise, encode to a string."""
if value is None:
return ""
return base64.b64encode(value) | 5fdd18e1657f5d3f4ff1673f69f7f830e52c9850 | 644,862 |
import numpy
def adamBashforth2Integration(calculated, actual, timeStep):
"""
Implementation of Adam-Bashforth 2 integration.
"""
output = numpy.zeros((actual.size, ))
summation = 0
output[0] = actual[0]
output[1] = actual[1]
summation += actual[1]
for i in range(2, actual.si... | 0231a37eca143c07d3e3f2851faab992c8917253 | 644,863 |
def checkVals(vs):
"""
check for big values (likely to cause overflow)
"""
bigV = 10000
return all(-1*bigV <= v <= bigV for v in vs) | 341ec6cdc038bd87197eb7c3fb60e5a123576fd6 | 644,864 |
def make_file_name(full_file_path, supported_extensions):
"""Generate a pure file name for the file."""
chunks = full_file_path.split("/")
file_name = chunks[-1]
for ext in supported_extensions:
# Remove all extensions
file_name = file_name.replace(ext, "")
return file_name | 9b7ad177a107a5d260fe9f6839a8a54dd8d6a912 | 644,865 |
import functools
def mobile_template(template):
"""
Mark a function as mobile-ready and pass a mobile template if MOBILE.
@mobile_template('a/{mobile/}/b.html')
def view(request, template=None):
...
if request.MOBILE=True the template will be 'a/mobile/b.html'.
if request.MOBILE=Fals... | 910c09fd3f55d7969f44de97239133c54bd62849 | 644,866 |
def sim_science_fractions():
"""
Elements of the tuple are (priority, numobs, fraction, desitarget_type).
The fractions should add up to 1.0...
"""
return [
(3000, 1, 0.200, "ELG"),
(3200, 1, 0.100, "LRG"),
(3400, 1, 0.500, "QSO"),
(3400, 3, 0.200, "QSO")
] | a776489a472b8215e17a03f6c205e2dc7cd89a47 | 644,867 |
def unify_curves(curves):
"""
"""
# 1. Raise degree to maximum degree
max_degree = max([crv.degree for crv in curves])
knot_vector = curves[0].knot_vector
for crv in curves:
if crv.degree != max_degree:
raise NotImplementedError("Sorry, lofting curves of different degrees is ... | 0831aeb84e50c742bb231efe7f3ce06b709d505d | 644,868 |
import sys
import asyncio
def _asyncio_run(*args, **kvargs):
"""
Cheap backport of asyncio.run of Python 3.7+ to Python 3.6.
For the real deal, see
https://github.com/python/cpython/blob/3.7/Lib/asyncio/runners.py#L8
"""
if sys.version_info[:2] >= (3, 7):
return asyncio.run(*args, **kv... | 5644d9a08fb81cc59495d062cdefbfb0df769499 | 644,869 |
def employee_kwargs(request):
"""Generate kwargs for constructing employees"""
return request.param | f0d9eefb8e4128193f0afb90dd9698a7756f9c81 | 644,870 |
def build_indices(stream):
""" Parses the stream of logs and indexes it.
Args:
stream, list of string, format <metric_name>|<value>|<coma_separated_tags>
Returns:
pair of hashes,
first hash has the format {tag -> set([line_indices])}
second hash has the format {line_i... | fa3ae6ee9de69bb02f16c4a3272822c781973a8d | 644,872 |
def get_crowd_selection(selection_count, selection_map):
"""
Figure out what the crowd actually selected
:param selection_count: number of responses per selection
:type selection_count: dict
:param selection_map: maps selections to output fields
:type selection_map: dict
:return: the respo... | dc21a6c991073485f8fba16c9f0fdf9bd634ae08 | 644,873 |
def fastest_path(nums) :
"""
:param nums:
:return:
"""
for i in range(1, len(nums)):
len_i = len(nums[i])
for j in range(len_i):
if j == 0 :
nums[i][j] = nums[i - 1][j] + nums[i][j]
elif j == len_i-1:
nums[i][j] = nums[i - 1][j ... | 76f096afdb80adc57ae445ba2ca90a926e60428d | 644,874 |
def get_stop_word():
"""
去除停用词,将停用词以集合的形式返回
:return: stop words
"""
stop_word = set()
for line in open('./data/stop_word_list', encoding='UTF-8'):
stop_word.add(line.strip())
return stop_word | bf3da40aa433ae20283b859ba2f7fe58a6bb6ca5 | 644,875 |
from typing import Iterable
def has_intersection(left: Iterable[str], right: Iterable[str]) -> float:
"""Returns 1.0 if there is any overlap between the iterables, else 0.0."""
if len(set(left).intersection(right)) > 0:
return 1.0
return 0.0 | c8f7fb4952490b1ac8ae5214f013effc58b1c29a | 644,876 |
def is_empty_config(host):
"""
Check if any services should to be configured to run on the given host.
"""
return (not host.services.exists()
and not host.interfaces.exists()
and not host.vpn_clients.filter(active=True).exists()
and not host.vpn_servers.exists()) | eb3e90495ae8f1cf28c33b3ee0b4ea96e04d79c9 | 644,877 |
def extract_HBS_learning_curves(runs):
"""
function to get the hyperband learning curves
This is an example function showing the interface to use the
HB_result.get_learning_curves method.
Parameters
----------
runs: list of HB_result.run objects
the performed runs for an unspecifi... | f3f595f6969efdc4773dd680ccadaf8f79f1b54c | 644,878 |
def get_type_str(json):
"""
Recreates json as str
:param json: input json
:return: json string.
"""
type_str = ''
if json.get('type') is not None:
type_str += json['type']
for key, val in json.items():
if key == 'type':
continue
if key == 'typedef':
... | c38e19d865c5452f44062436e69ab52947907e2c | 644,880 |
def shell_sort(array):
"""
Shell Sort algorithm
:param array: the array to be sorted.
:return: sorted array.
>>> import random
>>> array = random.sample(range(-50, 50), 100)
>>> shell_sort(array) == sorted(array)
True
>>> import string
>>> array = random.choices(string.ascii_lett... | 5a4fe0c144d1baf4bf97c333e504e0363e02eea5 | 644,881 |
def pick_and_pop(keys, d: dict) -> dict:
"""
pick all (key, val) pair from dictionary 'd' for all keys in 'keys'
Then, return a new dict with those picked (key, val) pair
"""
values = list(map(lambda key: d.pop(key), keys))
return dict(zip(keys, values)) | 327f89f91f5a37fa0bdcede4cee15c0800db4e2d | 644,882 |
from typing import Any
def vidUnpackedWP(
events: Any, return_columns: bool = True, input_collection: str = "Electron_"
) -> Any:
"""Return dataframe with columns of the cuts in the electron cutBasedID,
e.g. Electron_GsfEleEInverseMinusPInverseCut will be 0 (fail), 1, 2, 3, or 4 (tight)"""
columns = e... | 735734a5deac68956f5b12137b3e609c39ba5e1a | 644,883 |
def hist_wrapper(self, func, x, bins=None, **kwargs):
"""Wraps %(methods)s, enforces that all arguments after `bins` are
keyword-only and sets the default patch linewidth to ``0``."""
kwargs.setdefault('linewidth', 0)
return func(self, x, bins=bins, **kwargs) | 2e507bfdab7f2a4e4ed27a663cafc1fa0d8fc2eb | 644,884 |
def find_double_day(older_birthday, younger_birthday):
"""Takes 2 datetime.date objects representing different days, returns the date when one is
twice as old as the other
Precondition: older_birthday < younger_birthday"""
assert older_birthday < younger_birthday
difference = younger_birthday - olde... | a0becdd53b4d63b1a57a79c88bc3e86332a73812 | 644,885 |
import re
def countMultiStopMarks(text):
""" Count repetitions of stop marks """
return len(re.findall(r"(\.)\1+", text)) | ce7f81317dd5e36863f4d260a6c21930b97ea1af | 644,886 |
def convert_to_string(web3, data):
"""
:param web3:
:param data:
:return:
"""
return web3.toHex(data) | 463651b0ba05b433b790450f40287783f017da01 | 644,887 |
from typing import Any
import subprocess
import contextlib
import time
def check_call(*args: 'Any', **kwargs: 'Any') -> int:
"""Wraps :func:`subprocess.check_call`."""
with open('logs/healthcheck.log', 'at', buffering=1) as file:
if 'stdout' not in kwargs:
kwargs['stdout'] = file
i... | 929ae1b8a58f0d4fab81e454f7dcf46b667104c6 | 644,888 |
def dna_starts_with(dna, pattern):
""" Return True if 'dna' starts with 'pattern' """
# Sanitize input
dna = dna.upper()
pattern = pattern.upper()
if not (set(dna) <= set('CGTA')):
raise ValueError('DNA contains garbage: %s' % set(dna))
if not (set(pattern) <= set('CGTA')):
rais... | d22da625e2970f8297393b44f855b08c9d0268af | 644,890 |
def fit_to_block_size(sequence, block_size, pad_token_id):
""" Adapt the source and target sequences' lengths to the block size.
If the sequence is shorter we append padding token to the right of the sequence.
Args:
sequence (list): sequence to be truncated to padded
block_size (int): lengt... | 6f684e118b7dc2668df347d6c4f88829e00c6700 | 644,893 |
import re
def get_integer(number: str) -> int:
"""
Fetches all numbers and returns an integer
Args:
number: A string of the identified number
Returns:
An integer value of number
"""
return int("".join(re.findall(r"\d+", number))) | 8ae62fe2edf0aaa5972c2a2c90a5747a8f255b21 | 644,896 |
def proposed_cut_off_value(cut_off_value, length):
"""Proposes a cutoff-value if cut_off_value < 0 (=default)
Reynolds and Gutman (1988) recommend using a cut-off level of 3-5 for 50-60 paricipants
--> 4/55: relation cut-off/ladders
Args:
cut_off_value ([int]): [cutoff-value ]
length (... | b8e9ca4e53405ef61eabed44e214b541d5bded65 | 644,897 |
def get_query_statistics(tweets, sentiment_aggregate_list):
"""
Generates basic statistics for a given query set of Tweets.
:param tweets: A query set of Tweets
:param sentiment_aggregate_list: A list with number of positive, negative and neutral Tweets in the query set
:return: Dictionary with tot... | 855c3cda23a0cd47e26f16586c377000dad86586 | 644,898 |
def mean(numbers):
"""Calcular el promedio de un array de numeros"""
return float(sum(numbers)) / max(len(numbers), 1) | 6bcab9105c877b361b1c9eaeec1ae8c358e96f83 | 644,899 |
def position(pos):
"""
When the player put a piece on the board, this function takes mouse position
as an argument and returns the proper point on the square.
"""
pos = list(pos)
for i, ind in enumerate(pos):
if ind <= 100 * (ind // 100) + 40:
pos[i] = 100 * (pos[i] // 100) ... | fdd7101c02fab7004922fc51b821ad828ab07bc6 | 644,900 |
def lines_that_start_with(string, fp):
"""Helper function to lines in a FORC data file that start with a given string
Inputs:
string: string to compare lines to
fp: file identifier
Outputs:
line: string corresponding to data line that meets the above conditions
"""
return [line fo... | a061184aa67138582fabb809b71b561e688b6cf8 | 644,901 |
import math
def power(n,c):
"""return pi*2**n"""
return math.pi*c | 131cf1633029a1f9210a359f98ff1804c3172896 | 644,902 |
def ignore_ctrlc(method):
"""Decorator to make a ProjectKey command ignore Ctrl-C.
- For a commands that runs programs that want to handle
Ctrl-C themselves - ipython for instance."""
method.ignore_ctrlc = True
return method | 9b873ad5818cbc9054d4983ab1671bf7064745bb | 644,903 |
def naive_matrix_multiplication_lists(a, b):
"""
Uses nested loops to calculate AB
:param a: An MxN matrix of numbers.
:param b: An NxP matrix of numbers.
:return: An MxP matrix of numbers which is the product: AB.
"""
M = len(a)
N = len(a[0])
if len(b) != N:
raise ValueError... | 88c980f0ae1361d7f1c33cdb640a640cd79cef08 | 644,904 |
def overrides_method(method_name, obj, base):
"""
Return True if the named base class method is overridden by obj.
Parameters
----------
method_name : str
Name of the method to search for.
obj : object
An object that is assumed to inherit from base.
base : class
The ... | 4631de0cb262737b56b561a954bd31ad0870bd82 | 644,905 |
import requests
def create_account(base_url: str, email: str, password: str, username: str,
firstname: str, lastname: str, secure: bool):
"""
Create an account with the server
:param base_url: base URL of server
:param email: email
:param password: password
:param username: ... | d84876449842b1a3b7cb28bedeb723ae61cc1e00 | 644,907 |
def repeat(self):
"""
Повтор документа.
"""
self.wait_printing()
return self.protocol.command(
0x8C,
self.password
) | 6b886037c615a35958eaeb19838f4dd164378329 | 644,908 |
def parse_value(val):
""" Parse values from html
"""
val = val.replace("%", " ")\
.replace(" ","")\
.replace(",", ".")\
.replace("st","").strip()
missing = ["Ejdeltagit", "N/A"]
if val in missing:
return val
elif val == "":
return None
return float(v... | 89e323e79d302541538e09b1fa62f31ed09abea0 | 644,910 |
def mm_to_dpi(mm):
"""
毫米转换成dpi(web上使用的图片都是72dpi 这存在质疑或过时)
图像每英寸长度内的像素点数。DPI(Dots Per Inch,每英寸点数)
:param mm: 毫米
:return: dpi
"""
cm = mm * 0.1
inch = cm / 2.54 # 1in = 2.54cm
dpi = 72 * inch
return dpi | f61ec4b1febff540675f4abe6d0bfdd90448a6c3 | 644,912 |
import numpy
def get_greenness(series,start,minimum_up):
"""
This function get info about the browness of a cycle.
Reference:
Keyword arguments:
timeseries : numpy.ndarray
Your time series.
start : integer
Position along time series axis
m... | 593c2eefc27253c11d00f99c9e4cee4a6301b2c4 | 644,913 |
def split(path: str):
"""Split path into (head, tail) tuple. Tail is the last path component. Head is all the rest."""
if path == "":
return "", ""
r = path.rsplit("/", 1)
if len(r) == 1:
return "", path
head = "/" if not r[0] else r[0]
return head, r[1] | 4dac0895c42a1b56930e798af717e3ccae03b316 | 644,914 |
import json
def dump(self):
"""Item as a JSON representation."""
return json.dumps(
self.primitive, sort_keys=True, ensure_ascii=False, separators=(",", ":")
) | 5d5d4413e59c86e5d98226685f45fb0d777d671d | 644,915 |
import os
def build_vcvarsall_vs_path(version):
"""
Given the Visual Studio version, returns the default path to the
Microsoft Visual Studio vcvarsall.bat file.
Expected versions are of the form {9.0, 10.0, 12.0, 14.0}
"""
# Set up a load of paths that can be imported from the tests
if 'Pr... | e3dd7ec4d9c1bb849d007e048260744000744ef9 | 644,916 |
import argparse
def get_argument_parser():
"""Define command line arguments and usage."""
parser = argparse.ArgumentParser()
parser.add_argument(
'names',
help=(
'list of name-location pairs '
'(location is two-letter country abbreviations)'))
parser.add_argument(
'--first',
... | 36fa1c017538004bf35e56bf7eecce0db7bf2607 | 644,917 |
from pathlib import Path
import os
def read_file(filepath: Path) -> bytes:
"""Return the contents of a file as bytes.
If the file is a symlink, read its contents instead of its target.
"""
if filepath.is_symlink():
return os.readlink(bytes(filepath)) + b"\n"
return filepath.read_bytes() | 775e95f17a1841af5c083e037d30d271f37af2f4 | 644,918 |
def get_message(msg):
"""Return message."""
return ' '.join([msg[0][1:]] + msg[1:]) | 60dec475696717d86c3a8e3310d56327897ae78e | 644,919 |
def tokenize_grapheme_langid(enhanced_word):
"""
tokenizer the langid of word (For multilingual GBERT)
"""
index_over = enhanced_word.index('}')
lang_id = [enhanced_word[:index_over + 1]]
return lang_id | 6e93ffee2fe1ec4ace77f0c316023ef26c486a85 | 644,920 |
def read_cmd_line(parser):
"""
Parse Command line options.
"""
args = parser.parse_args()
attributes = ['p', 'nstates', 'nconds']
return [getattr(args, p) for p in attributes] | 0575fbbda71b46707b83aa990dd5e4e93dc701f1 | 644,921 |
def match_end(names):
"""
"""
if len(names) == 1:
if names[0]=="END":
return 1
return 0 | 8a28c322b59db1c49ab60f34737572a1d928abf8 | 644,922 |
import io
import hashlib
def get_file_hash(filepath, algorithm):
"""
Get hash of a file.
:param filepath: the path to the file
:type filepath: str
:param algorithm: the desired hashing algorithm
:type algorithm: str
:return: Hash of the file in hex form.
:rtype: str
"""
file =... | 74085bfef322542547692aa4cc069e45fab40f21 | 644,923 |
def func(x):
"""
:type x: object
"""
print(x)
return 1 | 897fa38f002dff96af590345762a40e06f4a2595 | 644,924 |
def get_change_content(children, when):
"""Checks every childrens history recursively to find the content
of the change.
Args:
children: children array of the post dict.
when: Time of change log dict.
Returns:
Content of the change in HTML format.
"""
for child in child... | c3ba570a4823047071ffda439d433f776c6996c6 | 644,925 |
import torch
def top_k_acc(output, target, k=3):
"""
Caculate the accuracy of a modele
output: predictions of the model
target: true label
same function except that we work on a tensor
"""
with torch.no_grad():
pred = torch.topk(output, k, dim=1)[1]
assert pred.shape[0]... | d5c8ce3425146e0d084e52e677a19b7e4207082f | 644,927 |
def extract_topics(topic_rca, spec_thres):
"""Creates a map between topics and their core categories
Args:
topic_rca: specialisation topic
spec_thres: threshold to assess specialisation
"""
# Identify specialised topics
spec_topics = topic_rca.max().mask(topic_rca.max() < spec_thres... | 4c67fca370d61bcfe377f8547f7362147eb76864 | 644,928 |
def GetAlleleString(allele):
"""Get string representation of allele
If it is a sequence, return upper case sequence
If _SV type, return string representation
Parameters
----------
allele : ALT allele from vcf.Record
Returns
-------
str_allele : str
String representa... | 53fb7b3e41c41f125fdcdaea216e49b37f005bf8 | 644,930 |
from typing import Dict
import os
import json
def _read_json_file(jsonfile: str) -> Dict[int, Dict[str, float]]:
"""Return Python dictionary from json file
Args:
jsonfile: path to JSON file
Returns:
jsondict: python dictionary
"""
if not os.path.exists(jsonfile):
raise Fil... | 447ea8e2613ce706b529fd059cfe9e59599ff835 | 644,931 |
def derive_config_dict(config_obj):
"""Get the config dict from the obj
:param config_obj: The config object
:type config_obj:
:return:
:rtype:
"""
if config_obj:
config_dict = dict(config_obj.__dict__)
config_dict.pop("_sa_instance_state")
return config_dict
els... | ad8721a36d06e0739dad8a5cef54f3dc4605706c | 644,932 |
import lzma
import json
import sys
def convert_json(infile, provision):
"""
Convert clusters JSON file from main branch format to EpiCov format.
:param infile: open file stream ('r') to clusters JSON
:param provision: str, path to GISAID provision file
:return: dict, revised clusters to seriali... | f86292c7b73ea5bce6c7c19a50a2b99d2a76bf97 | 644,933 |
import six
def _GetUnicodeFromIpaSymbolHexCode(hex_code):
"""Converts the codepoints to a Unicode string.
Args:
hex_code: string representing hex-code of a codepoint.
Returns:
string (empty if no success).
"""
return six.unichr(int(hex_code, 16)) | 1cc167b92957b0359375a48c201d85bc6e3f15cb | 644,934 |
def enum_metaclass(enum_param, return_name=False, start=0):
"""
Returns a ``type`` subclass that may be used as a metaclass for
an enum.
Paremeters:
:enum_param: the name of class attribute that defines enum values.
The metaclass will add a class attribute for each value i... | 315713063e4e0df321999c4296775a4a92d63698 | 644,935 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.