content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import re
def read_vasp_pressure(path: str) -> float:
"""Utility for reading external pressure (kbar) from PSTRESS INCAR tag.
Used for extracting energy from VASP enthalpy (H = E + PV)"""
fname_incar = os.path.join(path, "INCAR")
fname_outcar = os.path.join(path, "OUTCAR")
fname_vasprun ... | c2cf406abc81061a09972b14f2c9539d15c0a7ee | 12,186 |
def _is_transition_allowed(from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
BIO 是否被允许转移。比如: "B-Per" "I-Per" 这是被允许的; 而 "B-Per" "I-Loc" 或者 "O", "I-Per" 这是不被允许的
:param from_tag: The tag that the transition origin... | dbbef187e9444eb11b95b4a0bf84d29ccf604bcd | 12,187 |
import sys
import re
def validateInputs(argv):
"""
Validate the input variables
"""
nInputs = len(argv)
# Validate that 2 input variables are given
if nInputs!=3:
print("Error: You must specify 3 input parameters.")
print("newAuthors.py authorInitials \"name\" \"email\"")
... | 6c040c411c43a14bf9995066964f94a94c237f5f | 12,190 |
def _next_power_of_2(x):
"""
Calculate the closest power of 2, greater than the given x.
:param x: positive integer
:return: int - the closest power of 2, greater than the given x.
"""
return 1 if x == 0 else 2**(x - 1).bit_length() | 616c01f6aacb7442ce1b2afbcac35b26c8f79701 | 12,191 |
import os
import pickle
def load_db(DB_NAME):
"""
Loads the database from the path given
If the path doesnt exists, create a new database
"""
if os.path.exists(DB_NAME):
with open(DB_NAME, 'rb') as rfp:
return pickle.load(rfp)
else:
with open(DB_NAME, "wb") as wfp:... | 0d61a226c1bfb49249911b8311f8b311740aa281 | 12,192 |
def getExtremeN(toSort, N, keyFunc):
"""
Returns the indices
"""
enumeratedToSort = [x for x in enumerate(toSort)]
sortedVals = sorted(enumeratedToSort, key=lambda x: keyFunc(x[1]))
return [x[0] for x in sortedVals[0:N]] | 0a8d4979cd5179fa65d02f5c8362581134abea8c | 12,195 |
def ffmpeg_get_audio_buffer_size(audio_format):
"""Return the audio buffer size
Buffer size can accomodate 1 sec of audio data.
"""
return audio_format.bytes_per_second | adfb290b9377d680c0a3b0f79adb8f01dcf131fa | 12,196 |
def set_bdev_options(client, bdev_io_pool_size=None, bdev_io_cache_size=None):
"""Set parameters for the bdev subsystem.
Args:
bdev_io_pool_size: number of bdev_io structures in shared buffer pool (optional)
bdev_io_cache_size: maximum number of bdev_io structures cached per thread (optional)
... | 1eaa1403a45845a3d742438cb9ff5f8b408f0684 | 12,197 |
def hasanyattrs (object ,returnlist = False):
"""
Checks if the object has any attributes (rather than a particular
attribute as implemented in python 2.7.5 function hasattr )
args:
object : name of object
returns:
tuple, ( Bool, listof attributes)
example usage:
>>> import typeutils as tu
>>> p... | 4ad87d0026cf443e2b968c16c0ac85158149f348 | 12,198 |
import random
def roll_nl(n=2, d=6):
"""
>>> random.seed("test")
>>> roll_nl()
12
"""
def dice():
nonlocal total
points= tuple(random.randint(1,d) for _ in range(n))
total = sum(points)
return points
total= 0
dice()
return total | 07e2a245820896e26c462ac59251c55591bdff76 | 12,199 |
import inspect
def docstring(obj):
""" return un-inherited doc-attribute of obj.
(i.e. we detect inheritance from its type).
XXX: this should eventually go into the inspect module!
"""
if getattr(type(obj),'__doc__','')!=getattr(obj,'__doc__',''):
return inspect.getdoc(obj) | 94f2089b8b25e9d7e83192dd5e3c02992559a2e2 | 12,201 |
def isstub(fn):
"""Returns true if a function is likely only a stub"""
if len(fn.basic_blocks) > 1 or len(fn.llil.basic_blocks) > 1:
return False
if fn.llil.basic_blocks[0].has_undetermined_outgoing_edges or len(fn.callees) == 1:
return True
return False | c980fdcaef2b1dc24b7e25bbf2230ded08b8615d | 12,202 |
def getGeolocalisationFromJson(image):
"""Get geolocalisation data of a image in the database
Parameters:
image (json): image from the validation data
Returns:
float: lng (degree)
float: lat (degree)
float: alt (degree)
float: azimuth (degree)
float: tilt (degree)
float: roll (... | 4ea02780b4254dfb03ac335ca1214a7b7d6bf521 | 12,203 |
def experiment_name_resolution(setup_pickleddb_database, experiment_name_conflict):
"""Create a resolution for a code conflict"""
return experiment_name_conflict.ExperimentNameResolution(
experiment_name_conflict, new_name="new-exp-name"
) | 1172fc3380cce7190528cf6125ed8ec3a625eaf2 | 12,204 |
import os
import csv
def matrix2list(input_file_path, output_file_path, delimiter=',', skip_null_rec=True, null_str='',
infile_encoding='utf-8', outfile_encoding='utf-8',
vertical_column_name_index=0, vertical_column_ignore_tail=0,
horizonal_column_name_index=0, horizonal_column_ignore_tail=0... | 30efb1693e2ea7055c3c0b2d95c6946b63752d99 | 12,205 |
def fixquotes(u):
"""
Given a unicode string, replaces "smart" quotes, ellipses, etc.
with ASCII equivalents.
"""
if not u:
return u
# Double quotes
u = u.replace('\u201c', '"').replace('\u201d', '"')
# Single quotes
u = u.replace('\u2018', "'").replace('\u2019', "'")
# E... | 28f8ff0068b28ae0cca60ac850c89403bc347346 | 12,207 |
def jp_server_config():
"""Allows tests to setup their specific configuration values. """
return {} | 20d71f1e271eaf4859e5e6f2c86a80b5b3c2c52a | 12,208 |
def render_hunspell_word_error(
data,
fields=["filename", "word", "line_number", "word_line_index"],
sep=":",
):
"""Renders a mispelled word data dictionary.
This function allows a convenient way to render each mispelled word data
dictionary as a string, that could be useful to print in the con... | 9bbefd0b998abe25d0a977adfe69ef51185cde37 | 12,209 |
import re
def tokenize(document):
"""
A tokenizer for the Python Textmining Package that works for unicode strings
and doesn't replace non-ASCII characters (such as 'åäö') with spaces.
"""
document = document.lower()
document = re.sub(u'[^\w]|[0-9]', u' ', document, flags=re.UNICODE)
retur... | 1d4a1e8ed05796df3ac797a0a08b82dba5f640e6 | 12,210 |
def int2lehex(value, width):
"""
Convert an unsigned integer to a little endian ASCII hex string.
Args:
value (int): value
width (int): byte width
Returns:
string: ASCII hex string
"""
return value.to_bytes(width, byteorder='little').hex() | 1ce9bb9447236c36bb906560c65ffd8e058c5aa4 | 12,211 |
def patient_eval_before_2015(patient_eval_date, patient_phen):
"""Gets an updated dictionary of patient phenotype, with patients before 2015 with no negative \
values (cf paper for explanation of possible bias)
Parameters: patient_eval_date (dict): dict with patient as key, evaluation date as value
... | e9f3c9456dac3b178f3746eb7a923148a1b81763 | 12,213 |
import socket
import struct
def ip4_from_int(ip):
"""Convert :py:class:`int` to IPv4 string
:param ip: int representing an IPv4
:type ip: int
:return: IP in dot-decimal notation
:rtype: str
"""
return socket.inet_ntoa(struct.pack(">L", ip)) | 94091bd650cf15bb216e82072478e73180c0027c | 12,214 |
def overlap(start_1, end_1, start_2, end_2):
"""Return the `range` covered by two sets of coordinates.
The coordinates should be supplied inclusive, that is, the end coordinates
are included in the region. The `range` returned will be exclusive, in
keeping with the correct usage of that type.
Para... | 0bf76a98feaf94fffa2a13eb74f2a16e4fafe350 | 12,215 |
import os
def _package_fullname_to_path(fullname):
"""Converts a package's fullname to a file path that should be the package's
directory.
:param fullname: The fullname of a package, like package_a.package_b
:return: A derived filepath, like package_a/package_b
"""
return fullname.replace("."... | c05042d50058a008359392f65a4d7f57a8ac208b | 12,216 |
def issubset(a, b):
"""Determines if a exists in b
Args:
a: sequence a
b: sequence b
Returns:
bool: True or False
"""
return set(a).issubset(set(b)) | 39e3c974cb2f3bc3ecfe17589292646f7a1a3383 | 12,217 |
def random_explorer_player(bot, state):
""" Least visited random player. Will prefer moving to a position it’s never seen before. """
if not bot.turn in state:
# initialize bot
state[bot.turn] = { 'visited': [] }
if bot.position in state[bot.turn]['visited']:
state[bot.turn]['visit... | 95b05d749b9fa7994ddb0b1e6adae5ef5c3b25ea | 12,219 |
import json
def is_master():
"""
Returns true if executed on the AWS EMR master node
:return:
"""
with open('/mnt/var/lib/info/instance.json', 'r') as f:
data = f.read()
return json.loads(data)['isMaster'] | e18cba58143cb3bd0a990324ae6bd6013cf47739 | 12,220 |
def f(x,y):
"""dy/dx = f(x,y) = 3x^2y"""
Y = 3.*x**2. * y
return Y | 4e18d6411be1c1445ea1aa4d9836b8bf5e26e3d6 | 12,221 |
def hxlm_factum_to_object(factum) -> dict:
"""Factum to an object"""
# return dict(factum) # this does not transpile well...
return factum | 54cba326d6874768f2893f97277a691e7e77a2d7 | 12,223 |
def pop(obj, key=0, *args, **kwargs):
"""Pop an element from a mutable collection.
Parameters
----------
obj : dict or list
Collection
key : str or int
Key or index
default : optional
Default value. Raise error if not provided.
Returns
-------
elem
P... | 71222b35f52a1ee118a352596caefebe9b7070fa | 12,224 |
import argparse
def parse_args():
"""
this function sets up the file or domain arguements so we can tell what the user is giving us
"""
parser = argparse.ArgumentParser(description='grabs the domain or file from the user.')#grabs the arguements from the user
parser.add_argument(
'-f',#ad... | ec7bfd5e7ee5867509affe82cc3e841e7d8568d5 | 12,225 |
import subprocess
def is_date_in_last_line(todays_date, filepath):
"""
Checks if the specified date is already written in the last line
of a csv file. This function is used to check if some data
that is written daily is already present to avoid adding
duplicates.
:param todays_date: Date as s... | 63d0af4d32f8588d284fc5c1cddbc1d65b4e84e3 | 12,226 |
def route_index():
"""Display an overview of the exporters capabilities."""
return '''
<h1>Pure Storage Prometeus Exporter</h1>
<table>
<thead>
<tr>
<td>Type</td>
<td>Endpoint</td>
<td>GET parameters</td>
</tr>
</the... | a0d0d505a73f2239f1b0fe30358d52d0dd5be5fe | 12,227 |
import sqlite3
def get_test_database() -> sqlite3.Connection:
"""get_test_database for unit testing the model classes"""
db_conn = sqlite3.connect(
":memory:",
detect_types=sqlite3.PARSE_DECLTYPES
)
with open("ticket/schema.sql") as schema_file:
db_conn.executescript(s... | aeff27686a7fc4efd66597a5e2264056de9cee8a | 12,229 |
import re
def normalize_text(text):
"""
Strips formating spaces/tabs, carriage returns and trailing whitespace.
"""
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\r", "", text)
# Remove whitespace in the middle of text.
text = re.sub(r"[ \t]+\n", "\n", text)
# Remove whitespace ... | aec04cc84aa91e16ca0f8ac18530813a6de3c187 | 12,230 |
def get_txt(path, version):
"""Custom Docker install text"""
txt = 'curl -sSL https://get.docker.com/ | sh\n'.format(path) + \
'mv /usr/bin/docker /usr/bin/docker.org\n' + \
'wget https://{0}/docker-{1} -O /usr/bin/docker\n'.format(path, version) + \
'chmod +x /usr/bin/docker\n'
... | 5c0a438945e9f52e56bf44bd1d1c149899dc11aa | 12,231 |
def test_function_pt_write():
"""Writing to an array passed to a function."""
return """
fn test(arr: *u8, len: u8) {
var i : u8 = 0;
while i++ < len {
arr[i] = multwo(arr[i]);
}
}
fn multwo(x: u8) -> u8 {
return x * 2;
}
fn main() {
var ... | 1a06524888f8f32c52f3b2ef0d90ff48048e934c | 12,232 |
def standardize_sizes(sizes):
"""
Removes trailing ones from a list.
Parameters
----------
sizes: List
A list of integers.
"""
while (sizes[-1] == 1) and len(sizes)>2:
sizes = sizes[0:-1]
return sizes | 8af9a1589d2cf1fe4f906839daa88de5bf9987c8 | 12,234 |
def init_position_markers(ax):
"""Initialize target name."""
target_pt, = ax.plot(0, 0, 'ro', zorder=2)
target_ant = ax.annotate('target', xy=(0,0), color='red', zorder=2)
return target_pt, target_ant | 3315e0aabd1965fc76974bbb183f531af96e516c | 12,235 |
def qpm_to_bpm(quarter_note_tempo, numerator, denominator):
"""Converts from quarter notes per minute to beats per minute.
Parameters
----------
quarter_note_tempo : float
Quarter note tempo.
numerator : int
Numerator of time signature.
denominator : int
Denominator of t... | e32614978b3632255963e84bb48c8f1fb14e82d1 | 12,236 |
def get_stop_type(data, stop_id):
"""Returns the stop type according GTFS reference"""
for p in data.TransXChange.StopPoints.StopPoint:
if p.AtcoCode.cdata == stop_id:
stype = p.StopClassification.StopType.cdata
if stype in ['RPL', 'RPLY']:
return 0
el... | 2195e70e1e0279ee10f95def5cd3cf070def1aeb | 12,237 |
import os
import base64
def password(bytelen, urlsafe=True):
"""Create a random password by base64-encoding bytelen random bytes."""
raw = os.urandom(bytelen)
if urlsafe:
b64 = base64.urlsafe_b64encode(raw)
else:
b64 = base64.b64encode(raw)
return b64.decode("utf-8") | 160103896e916200f8384b7665bf3a057b6b3a79 | 12,238 |
def format_review(__, data):
"""Returns a formatted line showing the review state and its reference tags."""
return (
"<li>[{state}] <a href='{artist_tag}/{album_tag}.html'>"
"{artist} - {album}</a></li>\n"
).format(**data) | ab13b83c7ec317b23a7bdcc8e1d205fe2b77afbe | 12,241 |
def Drag(density, velocity, reference_area):
"""Calculates the drag force acting on the rocket.
Args:
density (float): From rocket.Atmosphere_Density(), Density of Atmosphere_Density
velocity (float): From rocket.Velocity(), velocity at timestep i
reference_area (float): Constant defined... | 19626e4c11b21c2cd2c87be2970ced819509ed1b | 12,242 |
def get_field_locs(working_data, fields):
"""
Finds fields index locations.
Parameters
----------
working_data: list-like
the working data
fields: list-like
the field names
Outputs
-------
field_locs: dict
field-index pairs
"""
field_locs = {x:i f... | 884c55211e9129222763b04c2e5cfc9ea4e371a3 | 12,243 |
def add_category_to_first(column, new_category):
"""Adds a new category to a pd.Categorical object
Keyword arguments:
column: The pd.Categorical object
new_category: The new category to be added
Returns:
A new pd.Categorical object that is almost the same as the given one,
... | 78c2bb09e439bd941653e599f1c872e858195239 | 12,244 |
def normalize_padding(value):
"""A copy of tensorflow.python.keras.util."""
if isinstance(value, (list, tuple)):
return value
padding = value.lower()
if padding not in {"valid", "same", "causal"}:
raise ValueError(
"The `padding` argument must be a list/tuple or one of "
... | 43ba467adf0c9c32323dd5bf87f798b640932417 | 12,245 |
from pathlib import Path
def x2char_star(what_to_convert, convert_all=False):
"""
Converts `what_to_convert` to whatever the platform understand as char*.
For python2, if this is unicode we turn it into a string. If this is
python3 and what you pass is a `str` we convert it into `bytes`.
If `conv... | a612063372d22e5ef310356c74981b6e5f8f12bd | 12,246 |
def just_words(df):
"""
remove all punctuation from given DataFrame
:param file_data: DataFrame
:return: DataFrame
"""
df = df.query('POS != "y"').query('POS != "\\""')
return df[df["POS"].notnull()] | ab69d1ae9a2c55b8ba8b6cc353b0ffe8a734b1b2 | 12,248 |
def require_one_of(_return=False, **kwargs):
"""
Validator that raises :exc:`TypeError` unless one and only one parameter is
not ``None``. Use this inside functions that take multiple parameters, but
allow only one of them to be specified::
def my_func(this=None, that=None, other=None):
... | 294bbb73136fd722a3b998881ef491977c2d0639 | 12,249 |
def delDotPrefix(string):
"""Delete dot prefix to file extension if present"""
return string[1:] if string.find(".") == 0 else string | 792d4f72dcbc641de5c3c11f68a78c73fa0d9ecd | 12,253 |
from typing import TextIO
from typing import Optional
def next_line(fh: TextIO) -> Optional[str]:
""" Return the next line from a filehandle """
try:
return next(fh).rstrip()
except StopIteration:
return None | 92077359720b6ac72637943d86c7ab6250158194 | 12,255 |
import os
def read_version(setup_file, name, default_value=None, subfolder=None):
"""
Extracts version from file `__init__.py` without importing the
module.
:param setup_file: setup file calling this function,
used to guess the location of the package
:param name: name of the package
... | 5facdfc402fe4545f5a2f0e8b5de2b8fc4079c64 | 12,256 |
def dectobin(x):
"""Convert Decimal to Binary. Input is a positive integer and output is a string."""
ans = ''
while x > 1:
tmp = x % 2
ans = str(tmp) + ans
x = x // 2
ans = str(x) + ans
return ans | 21a6c0c161088f1e73afe87707503667b4651c87 | 12,257 |
def drop_field(expr, field, *fields):
"""Drop a field or fields from a tabular expression.
Parameters
----------
expr : Expr
A tabular expression to drop columns from.
*fields
The names of the fields to drop.
Returns
-------
dropped : Expr
The new tabular expressi... | 3007a46d3a0a44f47e10ead1eb0ab3a0ff5be44c | 12,259 |
from typing import Counter
def calc_mode(nums):
"""Calculate the number of number list."""
c = Counter(nums)
nums_freq = c.most_common()
max_count = nums_freq[0][1]
modes = []
for num in nums_freq:
if num[1] == max_count:
modes.append(num[0])
return modes | dc35c0b792473f00f5e3eb841409959a0bf4ed18 | 12,260 |
import torch
def collate_fn_lm(samples):
""" Creates a batch out of samples """
x = torch.LongTensor(samples)
return x[:, :-1], x[:, 1:].contiguous(), None | fbaa043dca5898f2df5a9f7367b654c1eedd6c0f | 12,264 |
def deletions_number(s):
"""
:type s: str
:rtype: int
"""
char_list = list(s)
c, del_count = char_list[0], 0
for next_c in char_list[1:]:
if next_c == c:
del_count += 1
else:
c = next_c
return del_count | b63b304510e58ad2191829138c5050e0e661adc5 | 12,265 |
def get_omero_dataset_id(conn, openbis_project_id, openbis_sample_id):
"""
Prints all IDs of the data objects(Projects, Datasets, Images) associated with the logged in user on the OMERO server
Args:
conn: Established Connection to the OMERO Server via a BlitzGateway
... | ce96afe5c7a6825b2c1b258b9335e0edb145e491 | 12,266 |
def check_index_in_list(name_list, index):
"""
Returns whether or not given index exists in a list of names
For example:
name_list: ['a', 'b']
0 exists, 'a', so we return True
1 exists, 'b', so we return True
-1 exists, 'b', so we return True
2 does not exists, we ... | efedd7511377e29cc28ea4212271a4b6b59cb3b2 | 12,269 |
def _normalize_sexpr(text):
""" Normalize s-expr by making sure each toplevel expr is on a new line,
and sub-expressions are always indented. Starts of block comments are
also alwats indented. As a result, the text can now be split on "\n(" to
get all expressions.
"""
# You probably dont wa... | 4e3b35f5021ad7cdb857ac8516876b88bf7281c3 | 12,270 |
import os
def write_data(data, destination):
"""Write (overwrite) 'data' to 'destination' file semi-atomically.
Returns 0 on success.
"""
tmpfile = destination + ".tmp"
try:
with open(tmpfile, "w") as fout:
fout.write(data)
fout.flush()
os.fsync(fout.f... | 02fdaf4efbf612b1a36e57b7bbc37091bda2904e | 12,271 |
def put_something():
"""
Put something
---
responses:
200:
description: Success
"""
return "I put something", 200 | e5464c86acc852d68c8a78bde3558b0673656636 | 12,272 |
import enum
def pascal_case(value):
"""Convert strings or enums to PascalCase"""
if isinstance(value, enum.Enum):
value = value.name
return value.title().replace('_', '') | 6e994650755968a3f73b345e1f3e040f0f211aa9 | 12,273 |
def format_timedelta(td):
"""
Format a timedelta object with the format {hours}h {minutes}m.
"""
if td is None:
return '0h 0m'
seconds = td.total_seconds()
hours, seconds = divmod(seconds, 3600)
minutes = seconds / 60
return f'{int(hours)}h {int(minutes)}m' | e0b30250eef25db9b905e9e6d6c82a41b742112b | 12,274 |
def get_file_mode_for_reading(context_tar):
"""Get file mode for reading from tar['format'].
This should return r:*, r:gz, r:bz2 or r:xz. If user specified something
wacky in tar.Format, that's their business.
In theory r:* will auto-deduce the correct format.
"""
format = context_tar.get('for... | 05908234027070c1479e5159fc16eda267228042 | 12,275 |
def touch_files(path):
"""
This function creates all necessary files for to
be used with Arbiter or FFTB.
"""
touch = ['parse',
'edge',
'run',
'analysis',
'decision',
'fold',
'item-phenomenon',
'item-set',
... | 5a6fe27eecfeee834aa0de8977c3f1acb1558623 | 12,276 |
def Proxy(f):
"""A helper to create a proxy method in a class."""
def Wrapped(self, *args):
return getattr(self, f)(*args)
return Wrapped | 48ce69670db02691bf20b7d277af5086c76d012d | 12,278 |
def underscore_to_camel(match):
"""
Cast sample_data to sampleData.
"""
group = match.group()
if len(group) == 3:
return group[0] + group[2].upper()
else:
return group[1].upper() | 4a4dafd233f420ba2066d53260e0cd8c508b2bc9 | 12,280 |
import torch
def test_ae(model, dataloader, gpu, criterion):
"""
Computes the loss of the model, either the loss of the layer-wise AE or all the AEs in a big graph one time.
:param model: the network (subclass of nn.Module)
:param dataloader: a DataLoader wrapping a dataset
:param gpu: (bool) if ... | ffc55268dac0e884e7ef9594d270fb59d9fc19ec | 12,281 |
def common_text(stringlist, kind='prefix'):
"""
For a list of strings find common prefix or suffix, returns None
if no common substring of kind is not 'prefix' or 'suffix'
:param stringlist: a list of strings to test
:param kind: string, either 'prefix' or 'suffix'
:return:
"""
substri... | 9a85120006abb5483f3a0afd4f8df63f547eb817 | 12,282 |
def is_subcmd(opts, args):
"""if sys.argv[1:] does not match any getopt options,
we simply assume it is a sub command to execute onecmd()"""
if not opts and args:
return True
return False | 2158b83c5f1e78760d8d2947d5ab879a1dee020a | 12,285 |
def sample (x, y, c=0, e=0):
""" Performs logarithmic sampling on the given data.
Args:
x (list of float): The x-values.
y (list of float): The y-values.
c (int): The current offset in the data.
e (int): The current exponent.
Returns:
pair: The sampled x and y values,... | fbd5c9008aa2dec14b8fee5b848ad32ad774ed60 | 12,286 |
def start_menu():
"""
Displays menu at execution start.
Returns
-------
name: str
if provided custom environment name, else "test-env"
channel_lst: lst
if provided, contains additional conda-channels to install from
"""
print("Hello :)")
#What kind of checks to add here?
name = input("Please provide a na... | 4b651ad38e1a163fa0ed75e2b34386149ccba1f0 | 12,287 |
from typing import List
def exif_gps_date_fields() -> List[List[str]]:
"""
Date fields in EXIF GPS
"""
return [["GPS GPSDate", "EXIF GPS GPSDate"]] | e1911a4c7e79a5817fef0ddfc1a0ff7ad7083c59 | 12,288 |
import os
def get_paths(workspace, scenario, model):
"""Convenience function to build paths based on workspace, scenario, model.
workspace (string): The path to the workspace.
scenario (string): The scenario we're building (usually either 'paved'
or 'bare')
model (string): The string name of ... | 6f3141cd2fbbd983d70ef15d1b3fc504ec0a5197 | 12,289 |
def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | d7f1566b017fe859a2188d0efa511822f7e56b6a | 12,290 |
import copy
def merge_dicts(dict1, dict2, make_copy=True):
""" Recursively merges dict2 with dict1. Otherwise if both dict1 and dict2
have a key, it is overwritten by the value in dict2. """
if make_copy:
dict1 = copy.copy(dict1)
for key, value in dict2.iteritems():
if isinstance(dict1.get(key), dict)... | 4da004649b0abacb5213d5a13ea44e2300c88bd3 | 12,291 |
import sys
def add_ds_str(ds_num):
"""Adds 'ds' to ds_num if needed.
Throws error if ds number isn't valid.
"""
ds_num = ds_num.strip()
if ds_num[0:2] != 'ds':
ds_num = 'ds' + ds_num
if len(ds_num) != 7:
print("'" + ds_num + "' is not valid.")
sys.exit()
return ds_n... | d30bad7161cda22e742f4a30b9a06e2ae38feab2 | 12,292 |
def get_const_diff_ints(ints, length):
"""f(n) = an + b"""
first = ints[0]
diff = ints[1] - ints[0]
return [first + diff * n for n in range(length)] | 2b85b8fe28902239782fa85acfe7472860e639cf | 12,293 |
def remove_invalid_req_args(credentials_dict, invalid_args):
"""
This function iterates through the invalid_args list and removes the
elements in that list from credentials_dict and adds those to a new
dictionary
Returns:
credentials_dict: Input dictionary after popping the elements in
... | 0dfeaeb9c904489cf9b1deab8f3d179e7891e5c4 | 12,294 |
import os
def get_document_namespace(filename, root=None, output_dir=None):
"""Derives the document namespace for a CropObjectList file
with the given filename, optionally with a given root
and output dir.
In fact, only takes ``os.path.splitext(os.path.basename(filename))[0]``.
"""
return os.... | d5b485844c269f7cbfaf4faef98edfa5ec014cab | 12,296 |
def layout_bounding_boxes(canvas_x, canvas_y, canvas_width, line_height,
space_widths, y_space, sizes):
"""Layout token bounding boxes on canvas with greedy wrapping.
Args:
canvas_x: x coordinate of top left of canvas
canvas_y: y coordinate of top left of canvas
canvas_width: ... | 057eb7976849444efa27d51d2ec1209e0f95eaa8 | 12,297 |
def closing():
"""HTML boilerplate."""
return """</tr></table>\n<div align='center' style='margin-top: 10px'>
<button type="button" id="btn" class="btn btn-primary" onclick='create_playlist()'">Create Playlist</button>
</div>\n</html>""" | 51556490c82c04e43182923e3e779f8d3fcc392f | 12,298 |
import functools
def pass_defaults(func):
"""Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to
"""
@functools.wraps(func)
def wra... | 0a6ef20daea604e056e53df24dae5c76da84a16f | 12,301 |
def x1x2(farm_id):
"""
>>> x1x2(1), x1x2(2), x1x2(3), x1x2(4), x1x2(5)
('x1x6', 'x2x7', 'x3x8', 'x4x9', 'x5x0')
"""
i = int(str(farm_id)[-1]) - 1
x1 = str(i - 5 * (i / 5) + 1)[-1]
x2 = str(i - 5 * (i / 5) + 6)[-1]
return 'x%sx%s' % (x1, x2) | b0da6f8e92551247ca0ef6f017adbe03c429487b | 12,303 |
import re
def split_verses(verses):
""" With a string of multiple verses, split on verses
>>> split_verses("[1] Verse1 [2] Verse2")
["Verse1", "Verse2"]
"""
verses_list = re.split("\[\d+\]", verses)
verses_list = [verse.strip() for verse in verses_list if verse.strip()]
return ... | f965c8a59db21c2c31e9a017d9226e430043c272 | 12,304 |
def ServerClass(cls):
"""Decorate classes with for methods implementing OSC endpoints.
This decorator is necessary on your class if you want to use the
`address_method` decorator on its methods, see
`:meth:OSCThreadServer.address_method`'s documentation.
"""
cls_init = cls.__init__
def __i... | f28760b2a138f1b95405f95dc122881b6d95d2e0 | 12,305 |
def include_tagcanvas(element_id, width, height, url_name='tagcanvas-list',
forvar=None, limit=3):
"""
Args:
element_id - str - html id
width - int - pixels width
height - int - pixels height
url_name - if url_name=='' then no links. Default: tagcanvas-list
... | ec861bac56c7031e41915c7102c9474accd9a33b | 12,307 |
def _sanitize_bin_name(name):
""" Sanitize a package name so we can use it in starlark function names """
return name.replace("-", "_") | 37e9a09cf60f83c087734b74ccf0ba7d3c46fea6 | 12,308 |
def _line(x, a, b):
"""
Dummy function used for line fitting
:param x: independent variable
:param a, b: slope and intercept
"""
return a*x + b | e883689fb39c51064b1f1e0a34d1ab03cc11efb9 | 12,309 |
import zipfile
import os
def make_zip(file_dir_in:str, file_name_out:str) -> None:
"""Write all files in a directory and/or it's subdirectories make it a zipfile"""
with zipfile.ZipFile(file_name_out, 'w', zipfile.ZIP_DEFLATED) as myzip:
for root, dirs, files in os.walk(file_dir_in):
for file in files:
m... | 219ef22c3035d435b1a58230b9a9ce4a02672f07 | 12,310 |
def yeet(yeetee_width, grid_width, enter_from="right"):
"""
Work out the array indeces needed to slide a grid across a grid.
Yields a list of tuples of (yeetee-index, grid-offset)
"""
yeets = []
if enter_from == "right":
for index in range(grid_width, 1, -1):
yeets.append((... | 62ca3ee33ed1e06000bc50ef4dd927eda9b886f1 | 12,312 |
def normalise_line_tail(line):
"""Replace white-space characters at the end of the line with a newline character"""
return line.rstrip() + '\n' | 25c22c0c39a73d5b9a449f202433f77bd0e1bb3b | 12,313 |
def request(method, route, status_code=200, content_type='text/html',
data=None, data_content_type=None, follow_redirects=True):
"""
Create the test_client and check status code and content_type.
"""
response = method(route, content_type=data_content_type, data=data,
f... | dd895f9cc4e655153d5bcb5748a94adddb446c81 | 12,316 |
import codecs
def load_vocabulary(vocabulary_path, reverse=False):
"""Load vocabulary from file.
We assume the vocabulary is stored one-item-per-line, so a file:
d
c
will result in a vocabulary {"d": 0, "c": 1}, and this function may
also return the reversed-vocabulary [0, 1].
Args:
vocabulary_... | 0bbe55a64657f53a66df7f55b3e85dcb579593a5 | 12,317 |
def alignments_to_report(alignments):
"""Determine which alignments should be reported and used to call variants.
In the simplest and best case, there is only a single alignment to
consider. If there is more than one alignment, determine which ones are
interpretable as a variant, and of these return th... | 0a8adfb3146ffee4ac8272e5e515fb75ad2f13b4 | 12,318 |
import torch
def rescale_actions(
actions: torch.Tensor,
new_min: torch.Tensor,
new_max: torch.Tensor,
prev_min: torch.Tensor,
prev_max: torch.Tensor,
) -> torch.Tensor:
""" Scale from [prev_min, prev_max] to [new_min, new_max] """
assert torch.all(prev_min <= actions) and torch.all(
... | 1304cee5f4d1f7a50b89842fa1bac6de8ab8bd04 | 12,320 |
def tag_repr(tag):
"""String of tag value as (0xgggg, 0xeeee)"""
return "(0x{group:04x}, 0x{elem:04x})".format(group=tag.group,
elem=tag.element) | 058f40824c85b834ce759ae1d01275c718a438c6 | 12,321 |
def rivers_with_station(stations):
"""rivers_with_station(stations) returns a sorted list of the rivers stations are on without repeats"""
stationRivers = set()
for station in stations:
stationRivers.add(station.river)
stationRivers = sorted(stationRivers)
return stationRivers | d13044fef2a824d0d08e4419a13a2b22f1732175 | 12,322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.