content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def toCol( v ):
"""
v is a vector
"""
return numpy.matrix( v.reshape(v.size,1) ) | 64deae90f617f223aa42abc98236a49a3032f30b | 21,546 |
import warnings
def _check_for_expected_keys(_dict, expected_keys, place="session", raise_error=False):
""" ensures that all of the expected keys are in place
"""
missing_elements = []
for elem in expected_keys:
if elem not in _dict.keys():
if raise_error:
raise Val... | bc2365a2fd7f6eeac18739a438f8abf821d16173 | 21,547 |
import subprocess
import shlex
import pathlib
def get_gmx_dir():
"""Find absolute location of the gromacs shared library files
This function uses a quick and dirty approach: GROMACS is called and
stdout is parsed for the entries 'Executable' and 'Data prefix'.
"""
call = 'gmx -h'
try:
... | 8f462cd3f506683b9a8146e11da6ce2b1aec38a7 | 21,549 |
def maxintegervalue(input):
"""
Function Docstring
"""
totalsum = 0
totalmult = 1
negative = False
for c in input: # Reading one character at a time
if c == '-': # cheking
negative = True
else:
totalsum += int(c)
totalmult *= int(c)
... | 6522898b3ae567e9560367a88dfdc0fe7d0a3359 | 21,550 |
import re
def word_count(text: str) -> int:
"""
Counts the total words in a string.
Parameters
------------
text: str
The text to count the words of.
Returns
------------
int
The number of words in the text.
"""
list_words = re.split(' |\n|\t', text) #Splits a... | 869afd06172c9ffb61430489804cac20706ca245 | 21,551 |
def tobin(i):
"""
Maps a ray index "i" into a bin index.
"""
#return int(log(3*y+1)/log(2))>>1
return int((3*i+1).bit_length()-1)>>1 | a32bf5895071ac111bbd0c76a3fa8b630feb252d | 21,552 |
def get_model_path(model):
"""Return the qualified path to a model class: 'model_logging.models.LogEntry'."""
return '{}.{}'.format(model.__module__, model.__qualname__) | ab6b631aa4fb3acac0355c587f792441ecf25702 | 21,553 |
from datetime import datetime
import random
def tweet_content():
"""Generate tweet string (140 characters or less)
"""
# potential responses
yes_opts = [
'YEAAAA',
'awwww yea',
'you betcha',
'BOOYAH',
'well, whatdya know?',
'does a giraffe have a long n... | 3121704ab53082263ea541cbc3dde38e371441d6 | 21,554 |
from typing import List
from typing import Tuple
from typing import Optional
import sys
def get_macros() -> List[Tuple[str, Optional[str]]]:
"""
returns list of macros that the extension needs to define
"""
if sys.platform == "win32":
return [("_WIN32", None)]
return [] | 0ec219a40b2a334da79a49d108f6d24d00371685 | 21,557 |
def get_image_data(image):
"""
Return a mapping of Image-related data given an `image`.
"""
exclude = ["base_location", "extracted_to_location", "layers"]
image_data = {
key: value for key, value in image.to_dict().items() if key not in exclude
}
return image_data | 684cd2a358599b161e2311f88c3e84c016ad2fef | 21,558 |
def proceed() -> bool:
"""
Ask to prooceed with extraction or not
"""
while True:
response = input("::Proocced with extraction ([y]/n)?")
if response in ["Y", "y", ""]:
return True
elif response in ["N", "n"]:
return False
else:
continu... | 6d4c93ee7a216d9eb62f565657cf89a2e829dd30 | 21,559 |
def clean_input(text):
"""
Text sanitization function
:param text: User input text
:return: Sanitized text, without non ascii characters
"""
# To keep things simple at the start, let's only keep ASCII characters
return str(text.encode().decode("ascii", errors="ignore")) | 974a24e4d516faac650a9899790b66ebe29fc0a2 | 21,560 |
def ua_mock(ua_mocks):
"""Generate a single ua mock w/o connection to a ctrl."""
return ua_mocks[0] | 0e68c16f7cef444b58704ff30af0c1971112eb31 | 21,562 |
import torch
def normalize_tensor_by_standard_deviation_devision(tensor):
"""Normalize tensor by dividing thorugh its standard deviation.
Args:
tensor (Tensor): Input tensor.
Returns:
Tensor: Normalized input tensor.
"""
mean = torch.std(tensor)
tensor = tensor.div(mean)
... | bdb17853adcc569e04d11e34cffeec1759633111 | 21,563 |
import requests
def get_player_stats_from_pfr(player_url, year):
"""
Function that returns the HTML content for a particular player
in a given NFL year/season.
:param player_url: URL for the player's Pro Football Reference Page
:param year: Year to access the player's stats for
:return: Strin... | d6e4b34de9498dd8dff80bf5e6bd0bdc9f44255b | 21,564 |
def euclidean_rhythm(beats, pulses):
"""Computes Euclidean rhythm of beats/pulses
From: https://kountanis.com/2017/06/13/python-euclidean/
Examples:
euclidean_rhythm(8, 5) -> [1, 0, 1, 0, 1, 0, 1, 1]
euclidean_rhythm(7, 3) -> [1, 0, 0, 1, 0, 1, 0]
Args:
beats (int): Beats of t... | c1ded4891dfc658a4ba1e92db7b736c70f25f4f5 | 21,566 |
def get_bits_from_bytes(int_value, index, size):
"""
:param int_value: The integer from which to extract bits.
:param index: Start index of value to extract from data. Least significant bit of data is index zero.
:param size: Size in bits of the value to extract from data.
:return: The extracted bit... | 4b9c2d51bb509d872f122fbf91966ceadb109a77 | 21,567 |
import csv
def get_device_name(file_name, sys_obj_id, delimiter=":"):
"""Get device name by its SNMP sysObjectID property from the file map.
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str
"""
try:
with open(file_name) as csv_file:
csv_re... | 3074dffc5274d882bb99c13a0e642b05fd68cb9c | 21,568 |
def get_replaces_to_rule(rules):
"""Invert rules dictionary to list of (replace, rule) tuples."""
replaces = []
for rule, rule_replaces in rules.items():
for replace in rule_replaces:
replaces.append((replace, rule))
return replaces | de3fd8235eb8926682544def49de500412ee3084 | 21,569 |
def query_epo_desc_table(src_table: str):
"""
Return the query generating the aggregate table to compute descriptive statistics on the EPO
full text database
:param src_table: str, table path to EPO full-text database on BigQuery e.g.
'project.dataset.table'
:return: str
"""
query = f"""... | 20f114cc4c54e03261362458140b2f7bc7318ea4 | 21,570 |
def _get_metadata_map_from_client_details(client_call_details):
"""Get metadata key->value map from client_call_details"""
metadata = {metadatum[0]: metadatum[1] for metadatum in (client_call_details.metadata or [])}
return metadata | 1d0b843b41f2777685dad13b9269410033086b02 | 21,571 |
def snake_to_camel_case(name: str, initial: bool = False) -> str:
"""Convert a PEP8 style snake_case name to CamelCase."""
chunks = name.split('_')
converted = [s.capitalize() for s in chunks]
if initial:
return ''.join(converted)
else:
return chunks[0].lower() + ''.join(converted[1:... | 1669c0a1065da8133771d83ebbc7ed4c393d4a8f | 21,572 |
def get_mock_mysql_conn_info():
"""mock mysql的连接信息"""
return '{"host": "host.host", "password": "pwd", "port": 3306, "user": "user.user"}' | 4adc01897600118ddbc37876ba5fa524ba2466ff | 21,573 |
def get_detector_information(ifo):
""" Return information on selected detector
------
ifo: str
The two-character detector string, i.e. H1, L1, V1, K1, G1
______
latitude, longitude, elevation, xarm_azimuth, yarm_azimuth, xarm_tilt, yarm_tilt
"""
if ifo=='H1':
... | cf634a806256af3966e28828163743bcd79608bd | 21,575 |
def filter_default(input_dict, params_default):
"""
Filter input parameters with default params.
:param input_dict: input parameters
:type input_dict : dict
:param params_default: default parameters
:type params_default : dict
:return: modified input_dict as dict
"""
for i in params... | 5cae639c2a18c6db7a858ebe4ce939bf551088c2 | 21,577 |
def propose_placements(block, grid, z):
"""
Returns a mapping of a block to each point in the grid.
"""
f = lambda point : block.moveto(point, z)
return list(map(f, grid)) | 489f90a8d1335d08dc43cd9c7d62ba2dc743392c | 21,578 |
def is_even(n):
"""Determines whether `n` is even
"""
# even = n % 2 == 0
even = not(n & 1)
return even | cfb0d961bf456fe84b99ba3dd81ec34b2bdd4f2f | 21,579 |
import time
def minutesTillBus(busTimepoint, nowTime = None):
""" given a bus timepoint record from getTimepointDepartures, return the number of minutes until that bus, as a float. nowTime is the current time since unix epoch, but leave it out to just use the system time. """
t = busTimepoint["DepartureTime"]
if ... | b26f194fd07160a2e7b2d5a059a6242af636d1fe | 21,580 |
import base64
def read_file_as_b64(image_path):
"""
Encode image file or image from zip archive to base64
Args:
image_path (bytes or str): if from a zip archive, it is an image in
bytes;
if from local directory, it should be a
... | 516200ba2c7a129f236c92dbf7952592f449b6e3 | 21,581 |
from typing import Iterable
import functools
def prod(iterable: Iterable[int]) -> int:
""" Calculates the product of an iterable. In Python 3.8 this can be replaced with a call to math.prod """
return functools.reduce(lambda x, y: x * y, iterable) | 219aec67b87fb1b4b16e6d4e70f8d1deca3a4388 | 21,582 |
def vstat(self, **kwargs):
"""Lists the current specifications for the array parameters.
APDL Command: *VSTAT
Notes
-----
Lists the current specifications for the *VABS, *VCOL, *VCUM, *VFACT,
*VLEN, and *VMASK commands.
This command is valid in any processor.
"""
command = f"*VSTA... | 06dbe878cb688b6ac2ccf9fb9f48e3629fa73c09 | 21,583 |
def read_bytes_sync(sock, nbytes):
""" Read number of bytes from a blocking socket
This is not typically used, see IOStream.read_bytes instead
"""
frames = []
while nbytes:
frame = sock.recv(nbytes)
frames.append(frame)
nbytes -= len(frame)
if len(frames) == 1:
... | 5e311824b3a1eb8765b8ac7bda692b35bda59839 | 21,584 |
def return_int(user_input):
"""Function to check and return an integer from user input"""
try:
user_int = int(user_input)
except ValueError:
print("Oops! Not a valid integer format.")
else:
return user_int | 01dccefb92e3b854029ec6100a11d02bc51af240 | 21,585 |
def get_clusterID(filename):
"""given a file name return the cluster id"""
return filename.split(".")[0] | 43de7ab212d41d4e7c1d40e6dadb988c178db1f4 | 21,586 |
def flatten_json(obj: dict) -> dict:
"""
Flatten json obj; doesn't handle lists
"""
out = {}
def flatten(obj, name=""):
if type(obj) is dict:
for key, value in obj.items():
flatten(value, name + key + "_")
else:
out[name[:-1]] = obj
flatt... | 98320015557c7dabc0ab6eecff6013791c2f6b6b | 21,588 |
def postWidth(thread, post):
""":return number of columns to fill"""
return '11' if all(p != thread.op for p in (post, post.parent)) else '12' | a00480d1eb2e34058fc52f3d133c54b13e1eef35 | 21,589 |
def selectionSort(array):
"""returns sorted array"""
length = len(array)
for i in range(length - 1):
unsortedElementIdx = i
minElementIdx = i+1
for j in range(i+1, length):
if array[j] < array[minElementIdx]:
minElementIdx = j
if array[minElementI... | 7da9af1e913411f2f74c904383f55304bf11c4c0 | 21,590 |
def tag_to_string(gallery_tag, simple=False):
"""
Takes gallery tags and converts it to string, returns string
if simple is set to True, returns a CSV string, else a dict-like string
"""
assert isinstance(gallery_tag, dict), "Please provide a dict like this: {'namespace':['tag1']}"
string = ""
... | 654628eee6938adfdd24b261927869b011ee927d | 21,591 |
import os
def scriptdir():
"""
Returns the directory where this script is located.
"""
return os.path.dirname(os.path.realpath(__file__)) | cb9a02188c9ce53b371d60d26ce8ae1f6f9b498f | 21,592 |
import json
def to_json(value):
"""A filter that outputs Python objects as JSON"""
return json.dumps(value) | 386a27290c2f9e1f0a926143bc7e54e2ca98912b | 21,594 |
def apply_gradient(main_image, gradient_img, gradient_alpha):
""" The gradient on the image is overlayed so that text looks visible and clear.
This leaves a good effect on the image.
Args:
main_image (Image): The main image where gradient has to be applied
gradient_img (Image): The gradient ... | 38b164203faa6d82919dc0f3033099babfdec5a7 | 21,596 |
def get_mac_addr_from_dbus_path(path):
"""Return the mac addres from a dev_XX_XX_XX_XX_XX_XX dbus path"""
return path.split("/")[-1].replace("dev_", '').replace("_", ":") | a8603f2f7b6202ab9bafe5f911606efd8dc54358 | 21,599 |
import typing
def compute_parent(
tour_edges: typing.List[int],
) -> typing.List[typing.Optional[int]]:
"""Compute parent from Euler-tour-on-edges.
Args:
tour_edges (typing.List[int]): euler tour on edges.
Returns:
typing.List[typing.Optional[int]]:
parent list.
... | 5887a22faf42fae32b81fab902de9490c5dc4b00 | 21,600 |
import tempfile
import os
def temporary_file(request):
"""Return a temporary file path."""
file_handle, path = tempfile.mkstemp()
os.close(file_handle)
def cleanup():
"""Remove temporary file."""
try:
os.remove(path)
except OSError:
pass
request.ad... | 647eda7ca7f0e8e6c9562df2b9f341359a268403 | 21,601 |
from typing import Optional
def build_netloc(host: str, port: Optional[int] = None) -> str:
"""Create a netloc that can be passed to `url.parse.urlunsplit` while safely handling ipv6 addresses."""
escaped_host = f"[{host}]" if ":" in host else host
return escaped_host if port is None else f"{escaped_host}... | 56e44584b2f5e76142c40b639919951772f75aed | 21,602 |
import numpy
def _gsa_acceleration(total_force, mass):
"""Convert force to acceleration, given mass.
In GSA paper, mass is M_i
"""
return numpy.divide(total_force, mass) | 7b25b72ac04fbb35a7e75effee799782b00be755 | 21,603 |
def Nullable(oftype):
"""Generate a converter that may be None, or :oftype.
field = Nullable(DateConverter) would expect either null or something to convert to date"""
def _(it):
if it is None:
return None
else:
return oftype(it)
return _ | 375e37f7f8ddd41e187e26900d17bfca3b97d788 | 21,604 |
import collections
def entries_dict_ids_argument(entries_dict):
"""Add entries in dictionary."""
entries_dict_ids = collections.defaultdict(dict)
for entry_id, entry_att in entries_dict.items():
entry_identifiers = {}
for label, value in entry_att.items():
if 'bdb' in label:
... | b6d04d4ad0d92e0cc2c645ce5814c088301516a8 | 21,605 |
def _fix_data(cube, var):
"""Specific data fixes for different variables."""
mll_to_mol = ['po4', 'si', 'no3']
if var in mll_to_mol:
cube.data = cube.data / 1000. # Convert from ml/l to mol/m^3
if var == 'o2':
cube.data = cube.data * 44.661 / 1000. # Convert from ml/l to mol/m^3
re... | 4fef0ba57f37cc6f037ef6b7b24f815401f8836d | 21,606 |
def error404(e):
"""
404 error handler.
"""
return ''.join([
'<html><body>',
'<h1>D20 - Page Not Found</h1>',
'<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>',
'<p>For more information including the complete source code, visit <a href="https://gi... | 35ab121b88e84295aaf97e2d60209c17acffd84d | 21,607 |
import torch
def one_cls_dice(output, target, label_idx):
"""
Calculate Dice metrics for one channel
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:param label_idx:
:return:
"""
eps = 0.0001
... | 7a9cb628348571320911e1ec86d222d98751fd4a | 21,608 |
import string
import random
def id_generator(
size=6,
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
):
""" Creates a unique ID consisting of a given number of characters with
a given set of characters """
return ''.join(random.ch... | 9a6bf02c63e5ad933340be70e95c812683a69dee | 21,609 |
import sys
import subprocess
def runTestWithPython(display_name, executable):
""" Runs `$(PYTHON) setup.py test -q` """
cmd = '%s setup.py test -q' % executable
sys.stdout.write(' Running tests against %s ... ' % display_name)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,... | 691599a748acde390dc96ef3570b7b2f977a0bf2 | 21,610 |
def convert_hubs_to_datastores(hubs, datastores):
"""Get filtered subset of datastores as represented by hubs.
:param hubs: represents a sub set of datastore ids
:param datastores: represents all candidate datastores
:returns: that subset of datastores objects that are also present in hubs
"""
... | 14e7231f9c6a1e273c217bf77b8a7d3b3632709c | 21,611 |
import six
def is_number(value):
""":yaql:isNumber
Returns true if value is an integer or floating number, otherwise false.
:signature: isNumber(value)
:arg value: input value
:argType value: any
:returnType: boolean
.. code::
yaql> isNumber(12.0)
true
yaql> isN... | 13c66d47990fc54ccf0843776f0bc83d810f81fe | 21,612 |
def inspect_chain(chain):
"""Return whether a chain is 'GOOD' or 'BAD'."""
next_key = chain.pop('BEGIN')
while True:
try:
next_key = chain.pop(next_key)
if next_key == "END":
break
except KeyError:
return "BAD"
if len(chain) > 0:
... | 083886aa31fa81cc90d4c7bd30149c5575a5a675 | 21,613 |
def _delta_to_str(delta):
"""
Pretty-print timedelta for emails
:param delta: a timedelta object
"""
seconds = abs(int(delta.total_seconds()))
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
parts = []
if days ... | 978196b1cb1e8f19172554bfcc210e086dda417c | 21,614 |
def longuest_sub_array(arr):
"""
This function caculates the longuest sub array in a list
A sub array is an array which doesn't contain any 0
It returns the index of the last element which composes the sub array
and the length of the sub array
"""
sub_arrays = []
last_index = 0
len... | 233ad72b773514b66063e993e2d283b910d52dd1 | 21,615 |
def get_content_type(request):
"""Return the MIME content type giving the request
Return `None` if unknown.
"""
if hasattr(request, 'content_type'):
conttype = request.content_type
else:
header = request.META.get('CONTENT_TYPE', None)
if not header:
return Non... | f355a2bef6cfc130a6ae897701fff6b2f037040d | 21,619 |
import os
def load_npy(ds) -> str:
"""The statement that imports a NumPy NPY file into Veusz.
"""
if os.name == "nt":
fpath = str(ds.path.resolve()).replace('\\', '\\\\')
else:
fpath = str(ds.path.resolve())
return f"ImportFilePlugin(u'Numpy NPY import', u'{fpath}', linked=True, na... | 96a9a725e03b40bb60db24eef7abdc698581674f | 21,620 |
def send_files_sftp(con, filepaths, remote_path):
"""
Send a list of files to the provided remote path via SFTP.
Unspecified (read: all) exceptions result in the remaining files not uploading.
:param con: a connected Paramiko client
:param list filepaths: list of pathlib Path objects
:param st... | 163945d8b62a256bab9100c3d29fa7a75208054c | 21,621 |
def get_seamus_id_from_url(url):
"""
gets seamus ID from URL
"""
if url.startswith('http://www.npr.org') or url.startswith('http://npr.org'):
url_parts = url.split('/')
id = url_parts[-2]
if id.isdigit():
return id
return None | 90aa3bdd7042d3c2badbddd508cf824215917a66 | 21,623 |
def hex(string):
"""
Convert a string to hex.
"""
return string.encode('hex') | 66ff8fe8797c840d5471dbb4693e0ae6ef32fb8e | 21,624 |
import ast
def literal(str_field: str):
"""
converts string of object back to object
example:
$ str_literal('['a','b','c']')
['a', 'b', 'c'] # type is list
"""
return ast.literal_eval(str_field) | 25d23f55e52cdb4727f157a3db13614932bcbec7 | 21,626 |
def tail_logfile(logfile=''):
"""Read n lines of the logfile"""
result = "Can't read logfile: {}".format(logfile)
lines = 40
with open(logfile) as f:
# for line in (f.readlines()[-lines:]):
# print(line)
result = ''.join(f.readlines()[-lines:])
return result | 61a4046d2a7bfb8be907a325253424b2d425b410 | 21,627 |
from typing import Dict
from typing import Any
from typing import Optional
import requests
def request_data(url: str, params: Dict[str, Any]) -> Optional[str]:
"""Request data about energy production from Entsoe API.
Args:
url (str): Entsoe API url.
params (Dict[str, str]): Parameters for the... | 187d134f3457616d830ec5c78b02a11f880c981e | 21,629 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(
description='Evaluate a Faster R-CNN network')
parser.add_argument('--gpu', dest='gpu_id',
help='GPU device id to use [0]',
default=0... | 789a20b362d077dfc8a680acf408fba2f7dfff7c | 21,630 |
def minimum_katcp_version(major, minor=0):
"""Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... | bcaefb29af78400cd283895fef0d4fd94f175112 | 21,631 |
def keep_adding_nums():
"""
047
Ask the user to enter a number and then enter another number. Add these two numbers together and
then ask if they want to add another number. If they enter “y", ask them to enter another number and
keep adding numbers until they do not answer “y”. Once the loop has st... | b1fdd699ed583932c6990694fd93591cbfabd12d | 21,632 |
def newick_to_json(newick_string, namestring = "id", lengthstring = "branch_length", childrenstring = "children", generate_names=False):
"""Parses a newick string (example "((A,B),C)") into JSON format accepted by NetworkX
Args:
newick_string: The newick string to convert to JSON. Names, branch lengths and named
... | b116869f46467390b6dd2463bf2b982f01a95a13 | 21,633 |
def __str2key(_):
"""Make string a valid jinja2 template key e.g. dictionary.key
Ref: https://jinja.palletsprojects.com/en/3.0.x/templates/#variables
"""
return _.replace('.', '') | 7980e8d38576211f9bd02bcedd817c5d0087e415 | 21,635 |
import re
def compile_re(pattern):
""" Compile a regular expression with pattern
Args:
pattern (str): a string representing the pattern
e.g. "NoviPRD-.*" means strings that start with "NoviPRD-"
e.g. ".*\.csv" means strings that end with ".csv"
e.g. ".*xxx.*" means strings that... | f5fa043b9472bf19e350c880bbaf6200739234f5 | 21,636 |
import warnings
def check_args(parsed_args):
""" Function to check for inherent contradictions within parsed arguments.
For example, batch_size < num_gpus
Intended to raise errors prior to backend initialisation.
Args
parsed_args: parser.parse_args()
Returns
parsed_args
"""
... | 160f4bacc40d6187191c6b8ec18e0bc214856d4d | 21,640 |
def email_associated(env, email):
"""Returns whether an authenticated user account with that email address
exists.
"""
for row in env.db_query("""
SELECT value FROM session_attribute
WHERE authenticated=1 AND name='email' AND value=%s
""", (email,)):
return Tr... | 4f5ff9954cf7a73eca17529f74f3004835c6a07d | 21,641 |
import numpy
def int64_to_uint64(as_int64: int):
"""
Returns the uint64 number represented by the same byte representation as the the provided integer if it was understood to
be a int64 value.
"""
return numpy.int64(as_int64).astype(numpy.uint64).item() | 528fab1329dfd4d7f4d741b9d2d899e4cf4667c9 | 21,642 |
def _ListOpToList(listOp):
"""Apply listOp to an empty list, yielding a list."""
return listOp.ApplyOperations([]) if listOp else [] | 1c6aefacdbadc604a2566b85483894d98d116856 | 21,644 |
def format_float(n):
"""Converts the number to int if possible"""
return ('{:n}' if n == int(n) else '{:.8g}').format(n) | 5f117603d0b2f906cfa07e18785feef21e6c4ed3 | 21,645 |
def calc_rectangle_bbox(points, img_h, img_w):
"""
calculate bbox from a rectangle.
Parameters
----------
points : list
a list of two points. E.g. `[[x1, y1], [x2, y2]]`
img_h : int
maximal image height
img_w : int
maximal image width
Returns
-------
dict
corresponding bbox. I.e. `... | 45be9537c80d54e26a54dc4a04ece3759d988feb | 21,646 |
def __en_omelete(soup):
"""
Helper function to get Omelete News
:param soup: the BeautifulSoup object
:return: a list with the most read news from a given Omelete Page
"""
news = []
anchors = soup.find('aside', class_='c-ranking c-ranking--read').find_all('a')
for a in anchors:
... | 3c18168ca3f4656182e09c5dbde98ce1665b425d | 21,647 |
def flatten_columns(columns, sep = '_'):
"""flatten multiple columns to 1-dim columns joined with '_'
"""
l = []
for col in columns:
if not isinstance(col, str):
col = sep.join(col)
l.append(col)
return l | def685043534543ea1284edb915f69f6a7c1f37d | 21,648 |
def display_edit_subjects():
"""
110
Using the Names.txt file you created earlier, display the list of names in Python. Ask the user to type in one
of the names and then save all the names except the one they entered into a new file called Names2.txt.
:return:
"""
with open("docs/names.txt"... | 0d377926acc674f2428920cc100ae03116aaba0d | 21,649 |
def trailing_zeros(n):
"""Count trailing zero bits in an integer."""
if n & 1: return 0
if not n: return 0
if n < 0: n = -n
t = 0
while not n & 0xffffffffffffffff: n >>= 64; t += 64
while not n & 0xff: n >>= 8; t += 8
while not n & 1: n >>= 1; t += 1
return t | dd25d3f855500ae4853130c3b84601c51b64d9f0 | 21,651 |
def extract_node_attribute(graph, name, default=None):
"""
Extract attributes of a networx graph nodes to a dict.
:param graph: target graph
:param name: name of the attribute
:param default: default value (used if node doesn't have the specified attribute)
:return: a dict of attributes in form ... | 5ec1b7124ecbe048107d4d571c18fe66436d0c7b | 21,653 |
import struct
def Rf4ceMakeFCS(data):
"""
Returns a CRC that is the FCS for the frame (CRC-CCITT Kermit 16bit on the data given)
Implemented using pseudocode from: June 1986, Kermit Protocol Manual
https://www.kermitproject.org/kproto.pdf
"""
crc = 0
for i in range(0, len(data)):
c = ord(data[i])
q = (crc ... | 81add4f980ded4e26b78252257933a191be8721c | 21,654 |
def _best_streak(year_of_commits):
"""
Return our longest streak in days, given a yeare of commits.
"""
best = 0
streak = 0
for commits in year_of_commits:
if commits > 0:
streak += 1
if streak > best:
best = streak
else:
streak... | 3d0f042dc9565d5ef7002b6729550a76d01d3b00 | 21,655 |
from pathlib import Path
import os
def _fetch_test_content():
"""Get a local copy of HTML file.
We do some path manipulations so the tests can be run via py.test from any
directory.
"""
this_dir = Path(__file__).resolve().parent
test_html_path = os.path.join(this_dir, "test.html")
with op... | 6d715a6165ecb797d4376b6f6ad8771ec8f5e8cc | 21,657 |
def get_dict_keys(data, files):
"""
filters all the keys out of data
Args:
data: (list of lists of dictionaries)
files: (list)
Returns:
keys: (list) set of keys contained in data
"""
key_list = []
for i in range(len(data)):
data_file = data[i] # iterating o... | c0b556a65892d66ed0881bf4b1c5432b3e4b4daa | 21,659 |
def adds_arguments(**kwargs):
"""A factory for noop decorators. Pylint will inspect kwargs of this
instantiatiosn of this factory to determine what arguments it provides.
"""
def inner(func):
"""Return the original function, so that when adds_arguments is
used as a decorator there is no ... | ed596b28a525195470cfac818d5f45c8a9600a73 | 21,660 |
def labels_to_clusters(X, labels):
"""Utility function for converting labels to clusters.
Args:
X (ndarray[m, n]): input dataset
labels (ndarray[m]): labels of each point
Returns:
clusters (list, ndarray[i, n]): list of clusters (i denotes the size o... | d3e316f8563d0e8c4853754bddb294b51462d724 | 21,661 |
import requests
def get_page(url):
"""
Get a single page of results.
"""
response = requests.get(url)
data = response.json()
return data | d7d31ea8abbaa13523f33aa9eb39fca903d5cb21 | 21,662 |
import argparse
def parse_command_line_args(args):
"""
Parse the arguments passed via the command line.
Parameters
----------
args : str
Raw command line arguments.
Returns
-------
argparse.Namespace
Parsed command line arguments.
"""
parser = argparse.Argumen... | 9b029cf39ebd9c41ac637dab6ea799daf1685647 | 21,663 |
def get_uid():
"""
Authorization function which returns the current user_id for the user.
In our case it always returns 1
"""
return 1 | ac82726e470ba528c57b14b8b2ff994e182fb33f | 21,664 |
def lst_to_ans(ans_lst):
"""
:param ans_lst: list[str], contains correct guesses the user entered and undeciphered character.
:return: str, turns the list into string.
"""
ans = ''
for i in range(len(ans_lst)):
ans += ans_lst[i]
return ans | b1f0c196a53dc88e76967481d573bdff591597b9 | 21,665 |
def augmentCrlStatus(msg):
"""Augment CRL message with status of ``COMPLETE`` or ``INCOMPLETE``.
Check the CRL message for completeness.
Will add a ``status`` field to the message with a value of
``COMPLETE`` or ``INCOMPLETE``.
``COMPLETE`` messages meet the following criteria:
- Doesn't hav... | bd35db88259f2b4e1dad08a98973ef5413829542 | 21,666 |
def check_if_hits(row, column, fleet):
"""
This method checks if the shot of the human player at the square represented by row and column
hits any of the ships of fleet.
:param row: int
:param column: int
:param fleet: list
:returns result: bool - True if so and False otherwise
"""
r... | 2f62285d68c190b63a0934698cc209a59f15d445 | 21,668 |
from typing import Dict
def find_best_proba_success(trajectories_time_and_caught_proba) -> Dict:
"""
Trie la liste des trajectoires, par rapport à leur taux d'echec
Et renvoie le 1er élement, celui qui a le taux d'echec le plus faible
Ajoute également un champs "odds_of_success" au résultat pour indiq... | d980d48576db1831eb65f5878691334e020c62f9 | 21,669 |
def difference_in_ages(ages: list) -> tuple:
""" This function returns 'min', 'max' in ages and calculate the difference between them. """
return (min(ages), max(ages), max(ages) - min(ages)) | 89463494e9497dae510b821a086d9bfce7efde36 | 21,670 |
import hashlib
def encrypt_string(string: str, salt1: str, salt2="") -> str:
"""
Returns an encrypted string for anonymization of groups and names / phones
"""
salt = salt1 + salt2
return hashlib.pbkdf2_hmac('sha256', string.encode(),
salt.encode(), 1).hex() | 7a8f0738655de109e27900efa085d8834b41fb46 | 21,671 |
def get_codon_dictionary(codon_dictionary, string):
""" Returns a dictionary with codon as key and its frequency as value """
# iterates on every 3th item; remove remainders by: len(string) - len(string) % 3
for i in range(0, len(string) - len(string) % 3, 3):
codon = "{first}{second}{third}".f... | 32301f29b580d04f967d3714fae762b680c6049e | 21,672 |
import re
def del_digits(text):
"""Delete words compound only by digits."""
return re.sub('(\s*)\d+(\s*)',' ',text) | 668d369ee384982bf194d06db7f5672836403944 | 21,673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.