content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def ignore_transitive_dependency(name):
"""
Return True if @name should not be included in the Steam Runtime
tarball or directly depended on by the metapackage, even though
packages in the Steam Runtime might have dependencies on it.
"""
return name in (
# Must be provided by host system
'libc6',
'libegl-me... | 90835936cfa86b451139df717095ac4bbcd6ca7e | 71,404 |
import re
def parse_roll_syntax(die_info: str):
"""Parses a dice roll of format '2d10' into a tuple, e.g. (2, 10)"""
return map(int, re.findall(r'\d+', die_info)) | e18b67aa5560538e3fcab7fa8624683f48a67bc5 | 71,406 |
def filter_headline(df, non_disaggregation_columns):
"""Given a dataframe filter it down to just the headline data.
In the case of multiple units it will keep all headline for each unit.
"""
special_cols = [col for col in non_disaggregation_columns if col in df.columns]
# Select the non-data rows... | 3e2697a9802a6d5493ea8b81366ca5bf591d17e4 | 71,409 |
def reste(a,b):
"""
a,b sont des nombres entiers (b non nul)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cette fonction renvoie le reste de la division de a par b
"""
r=a%b
if r<0 : r=r+abs(b)
return r | 95389c47d0402ac6cd0ed8dead2dcd5e3412b055 | 71,412 |
def get_absolute_path(path):
"""
Get the absolute path.
:param pathlib.Path path: Path object
:return: Absolute path
:rtype: pathlib.Path
"""
return path.expanduser().resolve() | 8e7f0668f1491a0b898751ad2377ad02c08e5f25 | 71,414 |
import math
def bf_wheel (n):
"""
Bruteforce trial factorization with successive integers as
candidate factors. uses a wheel mod 6 to speed things
up a lot. can be expanded to wheel mod 30 by adding to the
prime basis, but takes extra steps in the trial phase. this seems
to be the most optimized version I coul... | eff52e8c94c5179bc78b70597ebe0a6fa0f287cf | 71,417 |
from typing import List
def __et_elements_to_string(elements: List[str]) -> str:
"""
Converts a list of ET.Element to a string.
"""
return '\n'.join(element for element in elements) | a668a4e4412dc73b885e504ad9368535d300a9ff | 71,419 |
def append_to_get(context, replace=True, **kwargs):
"""
Adds/deletes arguments to the current GET value
and returns a querystring containing it.
@argument replace: If true, any existing argument
named in kwargs will have their value overridden.
If false, kwargs are appended only.
@argu... | 6cd1d4aea2cab30f7ddcddd9a08fa384a4182c59 | 71,421 |
def listing_stopwords(filename):
"""Returns a list of all the stopwords in stopwords.txt"""
try:
h = open(filename)
except:
raise FileNotFoundError
h.close()
f = open(filename, 'r')
list = []
lines = f.readlines()
for line in range(len(lines)): # each line has one word
... | 496eae2244bfd77e8aa1fc57dec208f2a961955b | 71,427 |
def get_distinct_values(column, session):
"""
Return a list of all the distinct values in a table column
"""
q = session.query(column).distinct()
return [v[0] for v in q if v != (None,)] | 8b3802c442daaf9d90d5975217b50d245d6871a8 | 71,428 |
def join_lemmas(doc):
"""Return joined lemmas with appropriate whitespace."""
return "".join(token.lemma_ + token.whitespace_ for token in doc) | 87e6f5b1d826dd9d97519dfe105d9020260d8626 | 71,434 |
def reverse(text):
""" Reverse a string (trivial in python) """
return text[::-1] | 994a75b9d2e5ea9315cd8b9f526eafe4074aa214 | 71,436 |
import re
def canonical_name(artist):
""" Normalize names across variations """
name = re.sub(r' {2,}', ' ', artist.lower())
if name[:2] == '((':
name = name[2:]
if name in ('rem', 'r.e.m.'):
name = 'r. e. m.'
elif name in ('kt tunstall', 'k t tunstall', 'k.t. tunstall'):
n... | ed00188ccd1c57ad4cce19e7155e5e5a19048728 | 71,437 |
import re
def strip_comments(text: str) -> str:
"""Remove XML comments from a string.
.. note::
This will not remove lines that had comments, it only removes the text
from "<!--" to "-->".
:param text:
XML text to strip comments from.
:return:
The given `text` witho... | 6c0a9bc36264a47ecd96d17316a4f031cdfec6d5 | 71,443 |
import re
def parseval(val):
"""Parse a value that could be int, float, % or contain a memory unit."""
if val == "-":
return None
if re.match("\d+$", val):
return int(val)
if re.match("\d+(.\d+)?([eE][+-]\d+)?$", val):
return float(val)
if re.match("\d+(.\d+)?%$", val):
... | 0c91a520d275331a4c3e41fcaf3dd6ad1128ba30 | 71,444 |
import unittest
def skip_unless(condition, reason): # pragma: no cover
"""Skip tests unless a condition holds.
This implements the basic functionality of unittest.skipUnless
which is only available on Python 2.7+.
:param bool condition: If ``False``, the test will be skipped
:param str reason: ... | eb4854a206e5dd3396484fc8c02701052fd39981 | 71,446 |
import re
def rootcint_emitter(target, source, env):
"""
With ROOT >= 6, rootcling generates a <dict>_rdict.pcm mapping file
in addition to the dictionary source file. Add this "side effect" artifact
to the list of targets so that SCons can automatically keep track of it.
"""
if int(env.get('R... | 5a64157614f686c3754022a68f1c7d6fb6a1cfae | 71,447 |
def map_sequence(seq, sequence_map, unk_item_id):
""" Transform a splitted sequence of items into another sequence of items
according to the rules encoded in the dict item2id
seq: iterable
sequence_map: dict
unk_item_id: int"""
item_ids = []
for item in seq:
item_id = s... | 1206740cc3b2e810168a4a24dffbd0acc870ce46 | 71,448 |
def create_extra_var_str(vars_dict):
"""
This method encodes variables into an --extra-vars string
:param vars_dict:
:return: a string that can be added to the ansible-playbook exe
"""
if len(vars_dict) < 1:
return ''
out_val = "--extra-vars='{"
for key, value in vars_dict.items... | af00a41492a7ea2e3eaed32a8581002fe16672f7 | 71,451 |
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr,
assignment_operator: str = ' = ',
statement_separator: str = '\n',
statement_per_line: bool = False) -> str:
"""
Convert a dictionary i... | aec76c6a7b1e29c9540b0cb2a8161f831d2058de | 71,454 |
def combine_password_with_salt(password, salt):
"""
Combine a password with a salt.
Args:
password the password.
salt the salt.
Returns:
A combined string that can be hashed.
"""
return salt + password | d4ceb2c100521253ef6d562fde3077c2994d2333 | 71,455 |
def exceed_ns_icpm(cln_min, cln_max, cls_min, cls_max, dep_n, dep_s):
"""Calculates exceedances based on the methodology outlined by Max
Posch in the ICP Mapping manual (section VII.4):
https://www.umweltbundesamt.de/sites/default/files/medien/4292/dokumente/ch7-mapman-2016-04-26.pdf
NB: A... | a49a1ba13996b54f046629af5718e702db89eec6 | 71,456 |
def split_smb_path(_path):
"""
Parse the Service name from a full path
:param _path: A full SMB path ("/servicename/dir/subdir")
:return: A tuple with service name and the path part
"""
_splitted = _path.split("/")
_service = _splitted[0]
_remote_path = "/".join(_splitted[1:])
return... | 84d0d955c63fdd2f5c3156dfc1c8e66118fbcab6 | 71,458 |
def transform_NRS7(df):
"""Recodes NRS7 to a ordered number scale, 0-10.
"""
def transform_row(row):
if row == "Värsta tänkbara värk":
return 10
elif row == "Ingen värk":
return 0
else:
return int(row)
df["ini_NRS7"] = df["ini_NRS7"].apply... | 695657cf5df4ff254feb3e73deaf498f70c46459 | 71,463 |
def find_cfn_output(key, outputs):
"""Return CFN output value."""
for i in outputs:
if i['OutputKey'] == key:
return i['OutputValue']
return None | 0126ee4aa3c13e0371dd04cd6d6695730f5378a9 | 71,468 |
import math
def dot(p0, p1, p2, p3) -> float:
"""Calculare cosinue of angle between vectors p0->p1 and p2->p3"""
v0 = (p1[0] - p0[0], p1[1] - p0[1])
v1 = (p3[0] - p2[0], p3[1] - p2[1])
return (v0[0] * v1[0] + v0[1] * v1[1]) / (math.hypot(*v0) * math.hypot(*v1)) | f85dc47d0bef10ff96f95f23df2891a8e9eeb870 | 71,469 |
def __SXname__(x):
"""
Returns the name of casadi.SX symbolics
Parameters
----------
x : list[casadi.SX] or casadi.SX
List of casadi symbolics or just casadi symbolics.
Returns
-------
list[str] or str
List of name of symbolics or just name of symbolics
"""
if i... | 697328380c940e38dcb724f5b4383d0343f2ec7e | 71,471 |
def fitAlgorithm(classifier, trainingData, trainingTarget):
"""
Fits a given classifier / pipeline
"""
#train the model
return classifier.fit(trainingData, trainingTarget) | ddc6a7b2f5c42e07e212c2a48fd1d35b1c77dab2 | 71,473 |
def replace_s3_invalid_characters(key):
"""Replaces characters invalid for an S3 object key in a string
Args:
key: string where to replace characters
Returns:
string where any invalid characters were replaced with underscores
"""
spec_chars = " !-_'.,*()"
lst = []
for char in key:
if char.i... | 3ca34ceeddd0133a076f956d430f6e7b77b7097a | 71,476 |
from typing import Any
def composite(*funcs):
"""
Returns the composition of all the given functions, which is a function that runs the last
function with the input args, and then runs the function before that with the return value of
the last function and so on. Finally, the composition function will... | b180782c7358ee8f947c4a41dd1092690cc28094 | 71,477 |
import itertools
def selectSorous (aSorouListList, aF0):
"""
Takes [[f_1, f_2, ...]_j, ...] and returns the list [g_1, g_2, ...]
where each g_i is a sum sorous selected one from each list in aSorouListList + aF_0
"""
output = []
combinations = [p for p in itertools.product(*aSorouListList)]... | fa5d5721df5763a3325db96286f92ecd156874e1 | 71,479 |
def translate(english_days):
""" translate the name of a day in a week from English to French.
:param english_days: string, a day in a week in English.
:return: string, the French name for the day.
"""
french_days = ''
if english_days == 'Monday':
french_days = 'lundi'
elif english_... | 8f43faa3796d9818e33d39c69cf6c0076993b728 | 71,480 |
def marginCorrect(tr, margin):
"""
Correct affine transform for the margin that was added to an image.
"""
tr[0] += margin - (tr[1] + tr[2]) * margin
return tr | 0e35d5fcb208605e2bc1b112999780fcb3f98511 | 71,483 |
def get_field_on_block(block, field_name, default_value=None):
"""
Get the field value that is directly set on the xblock.
Do not get the inherited value since field inheritance
returns value from only a single parent chain
(e.g., doesn't take a union in DAGs).
"""
try:
if block.fiel... | 6f48a89a4684869b2b5ceec0a276b5f8117f70f4 | 71,486 |
def elementwise_residual(true_val, pred_val):
"""The residual between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
residual : float
The residual, true minus predicted
... | e1eb2434b1d24032f3b7abc1233c165d7146ffff | 71,487 |
def get_submit_attr_str(submit_attrs):
"""Convert submit attributes from a dictionary form to the corresponding configuration string
Args:
submit_attrs (dict): the dictionary containing the submit attributes
Returns:
string: the string representing the xml submit attributes section for a s... | 69f35d1db2436abdc648b68f365f54f0041cd5b7 | 71,488 |
import colorsys
def hsv_color(h, s, v):
"""Return an RGB color from HSV."""
r, g, b = colorsys.hsv_to_rgb(h, s, v)
return r * 255, g * 255, b * 255 | dd525abb57b6320688d931e3b97e584086b5f839 | 71,490 |
def gf_degree(f):
"""
Return leading degree of ``f``.
**Examples**
>>> from sympy.polys.galoistools import gf_degree
>>> gf_degree([1, 1, 2, 0])
3
>>> gf_degree([])
-1
"""
return len(f)-1 | 4c5853ddddfa1b65a39b6c7b0b1a822684cc5490 | 71,495 |
def sign_extend(num):
"""Sign extend 8-bit integer"""
num |= (-1 & ~0xFF) if (num & 0x80) else 0
return num | 2601e4f5ddb7c05b8785934c4e4cb8e665835041 | 71,496 |
def rewrite_title(lines, expected_title, rewritten_title):
"""Rewrite the title of a .rst file.
Args:
lines (List[str]): lines of the file.
expected_title (str): title expected to be generated by apidoc
rewritten_title (str): title to replace
Returns
List[str]: rewritten ti... | ec67359363fe82eaf91ea63b92fabca7cbf94606 | 71,497 |
import re
def fix_name(name):
""" Fix the names so that they are valid python variable names """
name = name.lower()
name = re.sub(r'[^a-z0-9_]+', '_', name).strip('_')
name = re.sub(r'[_]+', '_', name)
name = re.sub(r'^[0-9_]+', '', name)
return name | 23c634e4a1496d23c9b932b0ab78dc0029580fc2 | 71,503 |
import struct
def read_double(buf):
"""
Reads a double from `buf`.
"""
return struct.unpack("f", buf.read(4))[0] | 01b639f6221a1591dba41ec864648ee487351ebf | 71,504 |
def gcd(x: int, y: int) -> int:
""" Greatest Common Divisor. """
return x if y == 0 else gcd(y, x % y) | 2b1f6fbebaded95f862a3a37793bd38c27e575a6 | 71,505 |
def is_docs_file(metadata):
"""Only Docs files have the "exportLinks" key."""
return metadata.get('exportLinks') | 3a0daa89e4dddbc75f4fbddba801468c14aa48f0 | 71,512 |
from bs4 import BeautifulSoup
def extract_data_from_html(html, data):
"""
Uses the Beautiful Soup library to extract all links (href) and
images (src) on a given page and stores the results in the
dictionary (dict). The dictionary with collected data is returned
from the task.
Args:
... | 0340d51a648efe1652c5458eafb846c84bc80802 | 71,515 |
def name_from_fn(fn):
"""Human readable module.function name."""
return f"{fn.__module__}.{fn.__name__}" | 85c18ee9140ddca44b5798fed792451f645c62ea | 71,521 |
def convert_to_RGB_255(colors):
"""
Multiplies each element of a triplet by 255
"""
return (colors[0]*255.0, colors[1]*255.0, colors[2]*255.0) | ae45957295b282946d44b085eb5af03101313a41 | 71,523 |
import struct
def read_uint(buf, endianness=""):
"""
Reads an unsigned integer from `buf`.
"""
return struct.unpack(endianness + "H", buf.read(2))[0] | 19e9a962e9d8e66fe04832cf6bfcac72c19943b0 | 71,527 |
def float_range(start, end, step=1., exceed=False):
"""Like range() but for floats"""
l = []
i = start
if exceed:
more = step
else:
more = 0.
while i < end + more:
l.append(i)
i += step
return l | 5d6a57a4cd8004809a7c87ca09ca4aba170e6a6d | 71,537 |
def rescale(old_array, min_, max_):
"""Scale array to vary between min and max."""
scale_factor = (max_ - min_) / (old_array.max() - old_array.min())
return min_ + scale_factor * (old_array - old_array.min()) | 9c1feec7ca305b71ccc68783f9af8f4bfc1adee3 | 71,538 |
import re
def ensure_two_blank_lines_preceding_cell(text: str) -> str:
"""Ensure every cell delimiters has two preceding blank lines.
Adds/deletes lines if there are less/more.
--- before ---
# %%
some_code = 'here'
# %%
--- after ---
# %%
some_code = 'here'
# %%
"""
... | a52a46e29acfa1d335e309267a15e8ba5571e4be | 71,539 |
def trunc(s: str, left=70, right=25, dots=' ... '):
"""All of string s if it fits; else left and right ends of s with dots in the middle."""
dots = ' ... '
return s if len(s) <= left + right + len(dots) else s[:left] + dots + s[-right:] | 08ed3990baa6df66f3508219e96a53612c1cd9f8 | 71,542 |
def read_lines(filename, verbose=True):
"""
Load a file line by line into a list
"""
with open(filename, 'r') as fp:
lines = fp.readlines()
if verbose:
print("Done reading file", filename)
return [line.strip() for line in lines] | 3adc03ddd3afd9e077b8a7f656a274cce91af137 | 71,546 |
import functools
def compose(*functions):
""" Compose functions left-to-right.
NOTE: This implementation is based on a blog post by Mathieu Larose.
https://mathieularose.com/function-composition-in-python/
Parameters
----------
*functions : function
functions = func_1, func_2, ..... | 7796c3af1e717d0820eb20ea9ebf22509e64dc2e | 71,549 |
def get_path(haystack, needle, path=None):
"""Search a nested dictionary for the path to a specific value.
The value may be a key in a dict or a value in a list.
:param haystack: nested dictionary to search
:param needle: string value to search for
:param path: pre-path
:return: path to value a... | 3bcbc563b7bc957260163f359094920075364697 | 71,562 |
def correct_flask_vol(flask_vol, t=20.0, glass="borosilicate"):
"""
Correct flask volume for changes from thermal expansion of glass.
Parameters
----------
flask_vol : array-like
Flask volumes at standard temperature (20C)
t : float, optional
New temperature to calculate volume
... | f73e4b2797be3a040449d408688388c7b0674ef0 | 71,564 |
def option(option, text, **kwargs):
""" Simple shortcut to construct an option for the KolektoPrinter.choices method.
"""
return option, text, kwargs | b50d3ce02fc1099853d95f980cc85b010e42c30e | 71,565 |
def _channel_transf(channel):
"""Transform channel for luminance calculation."""
if channel < 0.03928:
return channel / 12.92
return ((channel + 0.055) / 1.055)**2.4 | 7e220248854257398794f0cc23d6f3bd2206202d | 71,567 |
def getDecile(type):
"""
Return a list of decile in either string or numeric form from ``5p`` to ``95p``.
We also include the ``50p`` for convinient.
Parameters
----------
type: str
Type of decile. Currently supported ``'string'`` (e.g. ``'5p'``) or
``... | 20c7c08639159ee41fc94dfbf124f62c42b44f1f | 71,574 |
import torch
def images_to_cpc_patches(images):
"""Converts (N, C, 256, 256) tensors to (N*49, C, 64, 64) patches
for CPC training"""
all_image_patches = []
for r in range(7):
for c in range(7):
batch_patch = images[:, :, r*32:r*32+64, c*32:c*32+64]
all_image_patches... | 0f630f83bfe1e97b3e619eb09f0d750821685979 | 71,575 |
def _format_read_number(read, read_type=None):
"""
Catch read values without a letter prefix (legacy format), convert
them to Rn format. This could be fixed by a database migration that
updates the JSON blobs.
:param read: The read number. May be eg 'R1', 'R2', 'I1', or
the old for... | e1cb89a778b0d5d2a1d946627e06f755a8f62011 | 71,578 |
def _cast_safe(self, value, cast_type = str, default_value = None):
"""
Casts the given value to the given type.
The cast is made in safe mode, if an exception
occurs the default value is returned.
:type value: Object
:param value: The value to be casted.
:type cast_type: Type
:param ca... | f89300e21a1758c892eb42ad35696a56f77313b5 | 71,584 |
from typing import List
def replace_item(init: str, fin: str, loc_string_list: List[str]) -> List[str]:
"""
Replace items in a list of strings.
A helper function for the Ocean class, as it allows the inputs
to fortran/C ocean model to be rewritten.
Args:
init (str): initial expression to... | 6c54430977cb48760ce459ef500fdb0d2f78370d | 71,585 |
import csv
def write_to_csv(dictionary, header, csvfile):
"""Writes a dictionary from SQL query and list of headers into a csv file"""
with open(csvfile, 'w') as a:
writer = csv.DictWriter(a, delimiter=';', fieldnames=header, lineterminator='\n')
writer.writeheader()
for d in dictionar... | 356a800953b6565301e1b0a6477de32284cb53b7 | 71,589 |
import pickle
def _pickle_import(filename):
"""
Pickle Importer
Helper function for importing pickled objects.
:param filename: Name and path to the pickle file.
:type filename: str
:return: The pickled object
:rtype: Object
"""
with open(filename, 'rb') as f:
obj = pickle.load(f)
return ob... | 2470736ed09211a72cc7d3a61c1eaa8d33361ffc | 71,594 |
def flip_pancakes(pancakes, flipper):
""" Calculates the minimum number of flips
:param pancakes: string representing line of pancakes with + (smile) or
- (empty)
:param flipper: the length of a flipper
:return: number of flips or "IMPOSSIBLE" if it is impossible to do this
... | ddc1e038a8ce3129e1904c62cf2c34f91385a4bc | 71,595 |
from typing import Dict
def dict_cut(d: Dict, a: int, b: int) -> Dict:
"""
Helper function for creating subdictionary by numeric indexing of items.
Assumes that `dict.items()` will have a fixed order.
Args:
d: The dictionary to "split"
a: Start index of range of items to include in r... | faee98deb5fb049958ba5c354c0e7a4987556665 | 71,597 |
def fetch_sensor_pattern(pattern, client, log):
"""Fetch sensor pattern for each antenna.
Args:
pattern (str): per-antenna sensor name with antenna fields
replaced with braces.
client (obj): KATPortalClient object.
log: logger
Return... | 8d4dc48a5592a5be4269c3f61ff518133229b722 | 71,602 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data with the following schema:
[
{
"ip": string,
... | 3d818834869bfab56e12ba73c3a9dd9be229e2cc | 71,605 |
def brightness_to_rflink(brightness: int) -> int:
"""Convert 0-255 brightness to RFLink dim level (0-15)."""
return int(brightness / 17) | c3a066e0b94144ebcb835664e66f395d3a906047 | 71,614 |
def _fmt_simple(name, arg):
"""Format a simple item that consists of a name and argument."""
if arg is None:
return None
return "%s %s" % (name, arg) | 6524de2ec20384b4ca5d56c05527c22ac9ec0cf2 | 71,618 |
def eval_metrics(model_type, params, dtrain, dtest, metrics):
"""Evaluates model with given parameters on train dataset,
evaluates on test dataset and calculates given metrics
Args:
model_type (type, subclass of modelgym.models.Model): class of model
(e.g modelgym.models.XGBClassifier)... | 9c177b617e53de04824925af911af8e84606f200 | 71,622 |
def density_to_air_quality(density):
"""Map PM2.5 density to HomeKit AirQuality level."""
if density <= 35:
return 1
elif density <= 75:
return 2
elif density <= 115:
return 3
elif density <= 150:
return 4
return 5 | 3a1b551f262770d8219874e880e35de5e7fa6b7a | 71,623 |
def convert_time(seconds):
"""convert seconds into natural time. i.e, 122 seconds => 2 minutes 32 seconds
note: does not go beyond minutes
"""
seconds = round(seconds)
minutes, seconds = divmod(seconds, 60)
x, y = "minute", "second"
if minutes > 1:
x += "s"
if seconds > 1:
... | 46ab118a08171234ae94ee9e456fb0b66e707f57 | 71,628 |
def PolygonToXYZ(poly, elev=0.0):
"""Converts Polygons to list of coordinate tuples (x,y,z).
Parameters:
poly: shapely.Polygon
elev: float
Optional z level.
Returns:
List of polygon border coordinate tuples.
"""
print("Converting polygon to points:")
points = []
# Exterior points
... | d2c8c6e890b86ee5070b885e84099561a0fddcb6 | 71,629 |
import json
def get_credentials(credentials_path="credentials.json"):
"""Access database credentials from JSON file
Parameters
----------
credentials_path : str
Location of the credentials JSON file
Returns
-------
credentials : dict
Dictionary containing the database con... | 9d5c06da334b90691985ab26cf071648600d210f | 71,636 |
import hashlib
def sha1(text: str) -> str:
"""Computes SHA1 hash over input string.
Args:
text: Input string.
Returns:
Hex encoded hashed string.
"""
hasher = hashlib.sha1()
hasher.update(text.encode())
return hasher.hexdigest() | ca6b68f89d986b52dc560c2e57ff96777d2347fb | 71,644 |
import math
def hex_shape(x, y, size):
"""
Generate the hexagon shape with specific size
"""
x_set = [math.cos(math.pi/6 * (i*2)) * size + x for i in range(0, 6)]
y_set = [math.sin(math.pi/6 * (i*2)) * size + y for i in range(0, 6)]
return list(map(lambda x,y: (x,y), x_set, y_set)) | 371262dd3156747db9598637a21f37e32d316ab7 | 71,645 |
def help_description(s="", compact=False):
"""
Append and return a brief description of the Sage documentation builder.
If 'compact' is ``False``, the function adds a final newline character.
"""
s += "Build or return information about Sage documentation. "
s += "A DOCUMENT and either a FORMAT ... | 999a92049f7167b198119ea4fb3eab98f02031db | 71,646 |
import glob
def get_chpl_files(mod_path):
"""
Get the chapel files that need to be compiled for the provided package
Parameters
__________
mod_path: path to the module being added to the server.
Returns
______
List of .chpl files at mod_path/server
"""
path = mod_path... | a32c8b04d67259940fdd148b8b0ee893f3753076 | 71,649 |
import ast
from typing import Container
def _get_name_of_class_if_from_modules(
classnode: ast.expr, *, modules: Container[str]
) -> str | None:
"""
If `classnode` is an `ast.Name`, return `classnode.id`.
If it's an `ast.Attribute`, check that the part before the dot is a module in `modules`.
If ... | b5f235a2c185573a5c9dbf270c89abead2d5272a | 71,650 |
def test_decorated_function(x):
"""Test Decorated Function Docstring."""
return x * 2 | 9bb8e1716d2292656ec8d3fead1ee6f935bdc5ef | 71,655 |
import re
def validate_eye_color(ecl):
"""
Validate Eye Color - exactly one of: amb blu brn gry grn hzl oth.
"""
match = re.search("(amb|blu|brn|gry|grn|hzl|oth)", ecl)
return bool(match) | be2e2ad4f09afa1c7afcdc8015d1e1b880bf96e1 | 71,657 |
def parse_csv_data(csv_filename:str) -> list:
"""
Description:
Function which opens a csv file and iterates through the file, adding each line to a list, which is returned.
Each line in the list is seperated by commas like in the csv file.
Arguments:
csv_file_n... | e2288a8bd3c6cf6aac24bd504cba500aad55870a | 71,658 |
import json
def read_json(path: str, encoding: str) -> dict:
"""Read JSON file."""
with open(path, encoding=encoding) as file:
return json.load(file) | 476b072bbb441744a740703df0a583acbfe73de7 | 71,659 |
def makePath(path):
"""
Make path element of URI from a supplied list of segments.
The leadfing '/' is not included.
"""
return "/".join(path) | 03760ebb75684b26db4653e749c46dbbce49c25c | 71,662 |
def count_model_parameters(model):
"""Count trainable parameters of a given model
Args:
model(object): torch model object
Returns:
trainable_parameters(int): number of trainable parameters
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 17b32f0e37f9f47fca4de17ee4cfc27cbaa12b02 | 71,667 |
def build_content_snippet(suggestion):
"""Build snippet for function autocompletion."""
name = suggestion["name"]
if suggestion["func_details"]:
paramText = ""
params = suggestion["func_details"]["params"]
for param in params:
if not paramText:
paramText... | 45f02b43fd61633887a7a35a17670369224c9361 | 71,669 |
def param_combinations(key_values):
"""Recursively combine the value lists that appear in a keyword values dict
into dictionaries describing combinations of simple values.
More directly, it reduces a dict describing valid keyword values to
CRDS bestrefs header dicts:
{ valid keyword values dict...... | 81cbe4974dc8f8e3d110ae308590090950fa5620 | 71,673 |
def get_last_url_item(url: str):
"""Returns everything after the last slash ("/") of a URL."""
last_slash_index = url.rindex("/")
return url[last_slash_index + 1 :] | 7227b8ebbe1b36585eb376e9621854acaa803317 | 71,676 |
def max_interval_intersec(S):
"""determine a value that is contained in a largest number of given intervals
:param S: list of half open intervals
:complexity: O(n log n), where n = len(S)
"""
B = ([(left, +1) for left, right in S] +
[(right, -1) for left, right in S])
B.sort()
c =... | db9998b831c6689fec1bdf5a79d57296301d405f | 71,678 |
import unicodedata
def normalize_fs_path(path: str) -> str:
"""Normalize filesystem paths with unicode in them"""
# macOS HFS+ uses NFD, APFS doesn't normalize but stick with NFD
# ref: https://eclecticlight.co/2021/05/08/explainer-unicode-normalization-and-apfs/
return unicodedata.normalize("NFD", pa... | b0ba3926213ae0b6f4e269a78241a3af19be9d1f | 71,685 |
import requests
def return_package_task(task_id):
"""Returns the content of an iControl LX task"""
task_url = 'http://localhost:8100/mgmt/shared/iapp/package-management-tasks/' + task_id
response = requests.get(task_url, auth=('admin', ''))
if response.status_code < 400:
response_json = respon... | cf5bbea84794adbce8ae9412d680ce4dc9a3c364 | 71,687 |
def get_isoweek_from_date(date):
"""Convenience method to get the ISO week from a datetime
:param datetime.datetime date:
:rtype: int
"""
return date.isocalendar()[1] | 444b237b9474a1427629eb60fa63a7296bf966a5 | 71,688 |
def quality_to_proba_sanger(quality):
"""Quality to probability (Sanger)"""
return 10**(quality/-10.) | 99f068e7d57d291802d8411ccac88897cb4b6110 | 71,693 |
def to_force(weight):
"""
Converts weight in grams to force in N at standard earth gravity.
"""
return 9.81 * weight / 1000 | f173c3e1598edcb7255ec5aff3389ae2de054fc5 | 71,698 |
def reverse(list):
"""
given a list, return a list with all the original items, but in reversed order
"""
return list[::-1] | 468ad9ff6416edf68639e7840abadce9754ac4ac | 71,700 |
def check_spg_settings(fs, window, nperseg, noverlap):
"""Check settings used for calculating spectrogram.
Parameters
----------
fs : float
Sampling rate, in Hz.
window : str or tuple or array_like
Desired window to use. See scipy.signal.get_window for a list of available windows.
... | b3933b03ca77a4ede73e7c4d9e416830355eeb93 | 71,706 |
def get_xref_mcf(xrefs, xref_to_label):
"""Returns the mcf format of a given string of xrefs.
Convert a list of xrefs to their mcf format of <prop_label>: <prop_text_value>
using the xref_to_label dict to lookup the property label of the given
indentifier. For this import, xref_to_label is either GENE_... | 85c530d4082133943bfbf2459a5c0c3c8f2d00cc | 71,711 |
def is_successful_upgrade(upgrade_response):
"""
Match against:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
:see: https://en.wikipedia.org/wiki/WebSocket
... | 88b0fa832b054e73f8eabe7f33866442b679e6b2 | 71,712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.