content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def listdir(fld):
"""
List the files into a folder with the complete file path instead of the relative file path like os.listdir.
:param fld: string, folder path
"""
return [str(f) for f in Path(fld).glob("**/*") if f.is_file()] | 816d4e461852ce2836f65d69a4a5d065d7c92b0a | 576,741 |
def compose_tweet(days, vacation):
"""
Composes the tweet that will be sent to the API.
:param days: Number of days until the next vacation.
:type days: int
:param vacation: String that connects the tweet's sentence. Either "meio de ano" or "fim de ano".
:type vacation: str
"""
if ... | dba0038799fb61f30f325a5f1cd63a29401e771a | 576,742 |
def manhattan(p,q):
"""
Calculate the manhattan distance
"""
same = 0
for i in p:
if i in q:
same += 1
n = same
vals = range(n)
distance = sum(abs(p[i] - q[i]) for i in vals)
return distance | 2b4ed7e4c290e093ae04da4f6a4f6a948bfe4513 | 576,743 |
def reverse_list(x):
"""Takes an list and returns the reverse of it.
If x is empty, return [].
>>> reverse_list([1, 2, 3, 4])
[4, 3, 2, 1]
>>> reverse_list([])
[]
"""
return x[::-1] | 25c4b2c6f2b8b59e1b0772a1f74e4a0d15fc3577 | 576,747 |
from typing import Tuple
def distance(point_a: Tuple[int, int],
point_b: Tuple[int, int],
m: int) -> float:
"""Generalized distance between two points
Note:
See more info here: https://xlinux.nist.gov/dads/HTML/lmdistance.html
Args:
- point_a (Tuple[int, int]): a ... | f73fb9045a94dfe745f29bae7a30891f34221791 | 576,748 |
def imc(peso: float, estatura: float) -> float:
"""Devuele el IMC
:param peso: Peso en kg
:peso type: float
:param estatura: Estatura en cm
:estatura type: float
:return: IMC
:rtype: float
>>> imc(78, 1.83)
23.29
"""
return round(peso/(estatura**2), 2) | 19c3423342239831205ba234a9e0bc8045582a36 | 576,751 |
def get_word_decoder(train_data, word_index):
""" Returns a function that can decode a sentence. """
reverse_word_index = dict(
[(value, key) for (key, value) in word_index.items()])
def reverse(idx):
return " ".join([reverse_word_index.get(i, '?') for i in train_data[idx]])
return rever... | 84c3de95f4b3affc680a633d8d1a389003d341ce | 576,752 |
def merge_kwargs(defaults: dict, kwargs: dict):
"""
Merge ``defaults`` into ``kwargs`` and return ``kwargs``.
Intended usage is for setting defaults to ``**kwargs`` when the caller did not
provide a given argument, but making sure not to overwrite the caller's explicit
argument when specified.
... | 49b3cb8631be89a7223043399cc1e49b3bb81426 | 576,756 |
from datetime import datetime
def format_time(timeobj: datetime) -> str:
"""Format a datetime object to the specific iso UTC string the datastore desires."""
# Strip out any existing time zone data, because the time zone formatting
# isoformat uses by default is offset based, rather than suffex code '+0' ... | ed509701ff271e154701ce08442896d989a1e685 | 576,757 |
def blank(s):
"""Count numbers of blank cells."""
blank = 0
for i in range(81):
if s[i] == 0:
blank = blank + 1
return (blank) | ac93c36f9d462377efbf85b1955b09a3466d23f0 | 576,759 |
def to_symbol(i):
"""Covert ids to text."""
if i == 0: return ""
if i == 11: return "+"
if i == 12: return "*"
return str(i - 1) | f52b93415f76ae4d0767977b1b368981724237ca | 576,764 |
from typing import Dict
from typing import List
def remove_exchanges(datasets_dict: Dict[str, dict], list_exc: List) -> Dict[str, dict]:
"""
Returns the same `datasets_dict`, where the list of exchanges in these datasets
has been filtered out: unwanted exchanges has been removed.
:param datasets_dict... | fa8497d58d13faf37ecc8c58bc3e39bcd9d7f020 | 576,765 |
def npBestFit( fitResult, filter=None ):
"""
Returns a vector of best fit results for the parameters that match the filter and the
corresponding list of parameter names.
"""
pars = fitResult.floatParsFinal()
l = [ (pars.at(i).getVal(),pars.at(i).GetName()) for i in range( pars.getSize() ) if not filter or filter ... | 80f72234cf5b3ba87ed162f0e3332e476b8a2870 | 576,766 |
def dot(a,b):
"""Dot product."""
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return sum([a[i]*b[i] for i in range(len(a))]) | dccec62e7ab62e5af3c1305e4648a18047043f21 | 576,768 |
import re
def rename_values_in_column(df, column_name, pattern,
repl):
"""Renames row values of dataframe by regex replacement.
Args:
df: A pandas dataframe.
column_name: In which column to rename values. Has to be string column.
pattern: Regex pattern to replace.
repl... | f8780ef86a51a3e516c3c6c1deebe1a13c1fa6aa | 576,769 |
def setsWith( element, index ):
"""setsWith( element, index) -> list
Takes a list of sets and returns a list of all sets with the element in
them."""
a = []
for set in index:
if set.contains( element ):
a.append( set )
return a | 260c9b3ff8e02e5cfaf005ef76240076a4c8b65f | 576,774 |
def num_digits(n):
"""Return the number of digits used to represent a number
"""
nd = 1
base = 10
while 1:
if n // base == 0:
break
else:
base *= 10
nd += 1
return nd | 2525c1b2b733a6e1f7f27a6973488302dddc7b7a | 576,779 |
def _np(tensor):
""" Converts given tensor to numpy array. """
return tensor.cpu().detach().numpy() | 730369c621f767357d67681681eed2a462ef9d7c | 576,780 |
def hierarchy_depth(hierarchy, path=()):
"""
Create a mapping of every path in the hierarchy to the node living at
that path in the hierarchy.
"""
base = {}
for key, inner in hierarchy.items():
down = tuple(path + (key,))
if isinstance(inner, dict):
base.update(hier... | fdc57ed2229f55b04dab2f4cc4467fef58a93132 | 576,783 |
from typing import Any
def create_null_type(name: str) -> Any:
"""
Creates a singleton instance of a custom nullable-type. This nullable-type acts much in the
same way `None` does. It is a "Falsey" value, returns `None` when called, raises `StopIteration`
when iterated, returns `False` when checking f... | e976a0a14e53ca63bdce3fc16252782960e0b3c5 | 576,789 |
import requests
def get_kills_dict(sys_id, list_len):
"""
Creates a list of kill IDs and a list of hashes and zips those together in to a dictionary
:param sys_id: the integer value ID of the system to be checked
:param list_len: The upper bound of number of entries in the lists to create
:return:... | e1a1a8d4d7571e836a0ffc6c88d17d93af7adccd | 576,790 |
import re
def regex_boolean_detect_creating(text_item):
"""
This helps with detecting the ready-state of a new/being made
dynamoDB table, checking to see if the status = "creating"
"""
# look for the pattern of: tablestatus = creating
pattern = r"'TableStatus': 'CREATING'"
# run regex t... | ec344b15206733b522b136c97e5909489ef2a509 | 576,791 |
def gcd(a: int, b: int):
"""Problem 32: Determine the greatest common divisor of two positive integer numbers.
Parameters
----------
a : int
An positive integer number
b : int
An positive integer number
Returns
-------
int
The greatest common divisor of the give... | b3f8cd55f0c9067f76f5407e5162796cca907d1c | 576,793 |
def tinyurlFindUrlstart( msg, start = 0 ):
"""Finds the beginnings of URLs"""
index = -1
if start < 0 or start >= len(msg):
return index
for prefix in ( "http://", "https://", "ftp://", "ftps://" ):
index = msg.find( prefix, start )
if index > -1:
break
return index | ed85a8b348091813168ef8117834e033b38417b3 | 576,796 |
def validate_page_title_minimum_length(page, parent):
"""
Ensure the page title is at least 10 characters long
"""
return page.title and len(page.title) >= 10 | f3276093dd3edcd8296be557e0fa2d8ad33e4baf | 576,799 |
import random
def generate_name(names_nouns_tuple):
"""
Generates a Docker style name in the format 'name_noun'.
Args:
names_nouns_tuple: An two element tuple.
The first element is a list containing the names.
The second element is a list containing the nouns.
Returns:
... | ef2d3e523e7f93a64d55f6406b37b28303c9799e | 576,800 |
def square(num:int) -> int:
"""
Return the square of num.
>>> square(3)
9
"""
return num * num | 245e56734564a72be6bd4bf4cea28b7fc31a2012 | 576,802 |
import re
def convert_price(line):
"""Convert line to price (float) or raise ValueError"""
# line might be '£2.90' or something else
matches = re.findall("(\d+\.\d+)", line)
if not matches:
raise ValueError()
price = float(matches[0])
assert price >= 0, "We expect positive prices over ... | 56182e6f7c64ed58161a7c9386955993ebac7c19 | 576,806 |
from typing import Dict
from typing import Any
def convert_crowdsourced_old_to_new(old: Dict[str, Any]) -> Dict[str, Any]:
"""Convert scraped data from the original format (which had "answers-cleaned" field) to a clearer format."""
raw = old["answerstrings"]
clusters = {
cluster["clusterid"]: {"co... | eca48afc3b55aa32b444da0b15f4bc802daff403 | 576,810 |
def rfile(node):
"""
A function to return the results of a Node's rfile() method,
if it exists, and the Node itself otherwise (if it's a Value
Node, e.g.).
"""
try:
rfile = node.rfile
except AttributeError:
return node
else:
return rfile() | 6f0ccc3ebb84ca52efed67e228dbeb74dd8a9d65 | 576,812 |
def format_query_result(query_result):
"""
Format query results to match column names with their values for each row
Returns: list containing a dictionaries (column_name, value)
Args:
query_result (obj): QueryResult object
"""
formatted_query_result = []
query_columns = [meta[0] for... | 4af1b5c4912df58b8b19f55c5d1c0fd921227918 | 576,815 |
def fill_spaces(word, desired_length):
"""Fill spaces at the end until word reaches desired length."""
return str(word) + ' ' * (desired_length - len(word)) | 5fc23932beba6b94bd6cdc89ba3af3b8064f883e | 576,817 |
import math
def getLineCircleIntersection(line, center, R):
""" Return the intersection of a line and circle.
line is a vector (a, c) such as the line equation is y = ax + c.
center is the coordinate of the center of the circle.
R is the radius of the circle.
"""
a, c = line
xl, yl = cen... | 7df3b5c43f2cb44c3033261d21faf19938ca2d1b | 576,818 |
from typing import List
import requests
import json
def get_asset_urls(host: str, token: str, photoGuids: List[str]):
"""
Get precice asset URLs based on a list of photo GUIDs
"""
url = "https://{}/{}/sharedstreams/webasseturls".format(host, token)
response = requests.post(url, json.dumps(
... | 3a2976834e34e9b41bdfdcc0b39248e44d94d758 | 576,819 |
import re
def _get_year(url: str) -> int:
"""Plucks the year from the provided URL."""
filename_regex = re.match(r".*-(.{4})(\..*)$", url, re.I)
assert filename_regex is not None
year_str = filename_regex.group(1)[-4:]
return int(year_str) | 8f020e41304f997148208dc6170b0d51d0e0ac39 | 576,821 |
def proximity_to_brightness(value):
"""Maps the proximity values (0 - 255) to the brightness values (0.0 - 1.0)"""
return value / 255 * 1.0 | f3e27d95bdec4dda756b9bbe5a26c8a02ca838b6 | 576,824 |
import math
def is_prime(number):
"""
Determine whether a number is prime.
Args:
number (int): The number to check
Returns:
(bool): True if the number is prime, false otherwise.
"""
# 1 is not prime
if number == 1:
return False
# 2 and 3 are prime
elif num... | 1f799499cd5785d958571184ce2fe887362f247d | 576,825 |
def load_wordlist(filename):
"""
filename: string, the path of a file to be read in containing the list of
every word to be used for the spellchecker
returns: list of strings, a list of every string contained in the
file, stripped of newlines
"""
with(open(filename, 'r')) as f:
conte... | 09467723155d5644d85c9922bc7fad31f3f59313 | 576,829 |
import hashlib
def sha1_hash(string):
"""Computes the SHA-1 hash of the given string."""
return hashlib.sha1(string).digest() | ae437cac0ac7ecf5514fca49fb2059db1d673f2d | 576,830 |
def _parse_record(record):
"""Return a list of all top-level importable names from a distribution's RECORD"""
python_names = set()
for rec in record.splitlines():
# every entry is made up of three parts
name = rec.rsplit(',', 2)[0]
# RECORD paths are not required to be in the style o... | 53dcd3ea6f27d5b65f6b4450701c5e946a479ec5 | 576,839 |
def _lpips_wrapper(sample, gt, lpips_model):
"""
Computes the frame-wise LPIPS between two videos.
Parameters
----------
sample : torch.*.Tensor
Tensor representing a video, of shape (length, batch, channels, width, height) and with float values lying in
[0, 1].
gt : torch.*.Tens... | 30961e84cd73fa21842daba27c293d8e485ed32f | 576,840 |
def is_s3(s: str) -> bool:
"""Check whether a string represents an S3 path."""
return s[:5] == "s3://" | 793cba676de9d231da2de8b96757104694f971d8 | 576,842 |
def get_marginal_protein_obs(p: int, r_max: int):
"""Get the observable for a marginalized protein abundance."""
marginal = ''
for r in range(r_max-1):
marginal += f'x_{r}_{p} + '
marginal += f'x_{r_max-1}_{p}'
return {'name': f'x_p{p}', 'formula': marginal} | fc16bb7288745c75a4900b7ec804a465bffe913c | 576,844 |
def get_percentage(part, whole):
"""Utility method for getting percentage of part out of whole
Parameters
----------
part: int, float
whole: int, float
Returns
-------
int : the percentage of part out of whole
"""
if 0 in [part, whole]:
return float(0)
return 100 * ... | 56f9a37650dd234f4d0ae48d9382e067d0c34960 | 576,851 |
def read_repr(file_path):
"""Read individual representation from given file.
Arguments:
file_path -- Path to file that stores the individual representation.
"""
with open(file_path, 'r') as f:
freq = f.readline()
repr_ = f.readline()
return freq, repr_ | 3b7f3fc458a8eead18c151deb0ad9eb574832e24 | 576,852 |
def factorielle_it(n: int) -> int:
"""
Description:
Factorielle méthode itérative
Paramètres:
n: {int} -- Nombre à factorielle
Retourne:
{int} -- Factorielle de n
Exemple:
>>> factorielle_it(100)
9.332622e+157
Pour l'écriture scientifiq... | c8ab61e1a05c172e5bf1ddc1d46a6e062c59b770 | 576,856 |
def name_to_number(name):
"""
Helper function that converts
a name to a number between 0 and 4
"""
num = -1
if name == "rock":
num = 0
elif name == "Spock":
num = 1
elif name == "paper":
num = 2
elif name == "lizard":
num = 3
elif name ==... | 08395b9ba98df22df59dbb97faf73e8e3da169cd | 576,867 |
def update_dict_path(base, path, value, default=dict):
"""
Set the dict path ``path`` on the dict ``base`` to ``value``. If the path
does not yet exist, the callable ``default`` will be used to create it.
A dict path is a way to represent an item deep inside a dict structure.
For example, the dic... | b45b88a19956c7a5dbd4fc141f48bfcf090132b7 | 576,869 |
def parse_surname_comma_surname_prefix(surname):
"""Separates the surname prefix from the surname, expected input is 'Ham, van der'."""
names = surname.split(',')
surname = names[0].strip()
surname_prefix = ''
if len(names) == 2:
surname_prefix = names[1].strip()
return surname, surname_... | 517fbf9e748627c485ce73aaa9fa05f1860b7294 | 576,870 |
def _nth_str(n):
"""Return posessive form of numeral `n`: 1st, 2nd, 3rd, etc."""
if n % 10 == 1 and n % 100 != 11:
return "%dst" % n
if n % 10 == 2 and n % 100 != 12:
return "%dnd" % n
if n % 10 == 3 and n % 100 != 13:
return "%drd" % n
return "%dth" % n | 57603203d067ca713804b9d46f5922ea2dc587df | 576,871 |
def shape_factory_from_coords(neighbor_coords, ref_shape):
""" Factory function to create a shape given coordinates.
Use a reference shape as a template.
@param neighbor_coords List of Coord objects for neighboring points
@param ref_shape Shape object of appropriate type for templa... | ebb04ee6039388a30847202104185ca933102f7c | 576,875 |
def map_div_js(context, center_latitude, center_longitude, zoom_level, map_div_id):
"""
Standardize map display
zoom_level should be 14 or higher for individual trees.
map_div_id may be: map or tree-map
"""
return {
'geojson': context['geojson'],
'zoom_level': zoom_level,
... | ae0261c243e910596c73be9b4704531900f10795 | 576,877 |
def tag(text, tag, values={}):
""" Wraps text into an HTML tag. Example:
>>> tag("Some text", "p", {"id": "id_value"})
>>> "<p id=id_value>Some text</p>
Args:
text (str): The text to wrap inside tags.
tag (str): The kind of tag.
values (dict): Optional additional tag key... | 19a5d4e1fcf632bb053cd2d5f711c518339894f2 | 576,882 |
import json
def pretty(js):
""" pretty print a json object """
return json.dumps(js, indent=2, ensure_ascii=False) | 2f2fd9e37f1b8183fc159258037fefc8dd63ebff | 576,884 |
def import_symbol(symbol_path):
""" Import the symbol defined by the specified symbol path.
Examples
--------
import_symbol('tarfile:TarFile') -> TarFile
import_symbol('tarfile:TarFile.open') -> TarFile.open
To allow compatibility with old-school traits symbol names we also allow
all-dott... | 29b52a5f1147ea5418184f3fca2f79e19e43774c | 576,885 |
def nopython(request):
"""nopython keyword argument for numba.jit"""
return request.param | ef4f06c86058d15220ff85df8e66432048b4d333 | 576,886 |
def join_lines(line1, line2):
"""Join 2 lines of text
>>> join_lines('abc', 'de')
'abcde'
>>> join_lines('a-', 'b')
'ab'
"""
if line1 == u"":
pass
elif line1[-1] == u'-':
# hyphenated word at the end of the
# line - don't add in a space and remove hyphen
... | 80314d859902b86ae1af02920f8904a9bcdd1db5 | 576,889 |
from pathlib import Path
def part_two(filename='input.txt', target=2020):
"""This is a simple extension of the method above to three items.
It is not a generalizable solution and a good rule-of-thumb would be
once you get three nested loops deep, you should start second-guessing your
implementation.
... | e42d852913dc0d79c3cc001631baaced3a050462 | 576,892 |
def sanitize_branch_name(branch_name):
"""Replace punctuation that cannot be in semantic version from a branch name with dashes."""
return branch_name.replace('/', '-').replace('_', '-') | 52a13ff7f0fded0934b27b19dd981d5cee5fd30d | 576,895 |
import json
def get_account_iam(account):
"""Given account data from the config file, open the IAM file for the account"""
return json.load(open(account['iam'])) | fabe1b0ff263fce5ca7e7854a2a728fe51900aa0 | 576,897 |
def retweet_proportion(tweets):
"""
Returns percentage of retweets in a list of tweets.
Raises error if list is empty.
:param tweets: the list of tweets, represented as dictionaries.
:return: float. the percentage of retweets in 'tweets', a number between 0 and 100.
"""
retweets = 0
... | 98569a86949acfdadc89cfa8d1a999733491ccc7 | 576,899 |
import math
def maxplus(x, y):
"""Rule for finding the maximum of two numbers, given the Histogrammar convention of representing the maximum of no data to be nan."""
if math.isnan(x) and math.isnan(y):
return float("nan")
elif math.isnan(x):
return y
elif math.isnan(y):
return ... | 8dd64f12d70ecd031bbd850824397d76ea4a1b45 | 576,902 |
def circle_coordinates(x, y, radius):
"""Calculates the bounds of a circle, given centre and radius."""
x1 = x - radius # Left
x2 = x + radius # Right
y1 = y - radius # Bottom
y2 = y + radius # Top
return (x1, y1, x2, y2) | a16cda58fbe5e0b9ad8ecdf067d6bd0d25c1eb19 | 576,905 |
def calcular_porcentaje_grasa(imc: float, edad: int, valor_genero: float) -> float:
""" Calcula el porcentaje de grasa corporal.
Parámetros:
imc (float) Índice de masa corporal redondeado a dos decimales.
edad (int) Edad de la persona en años. Número entero positivo.
valor_genero (float)... | 57967198c9356d0750066ae2e9f268e3cc73962e | 576,906 |
def calculate_cumulative_infections(new_infections):
"""Calculate the cumulative infections over time.
Args:
new_infections: a xr.DataArray containing new_infections and dimension
(locations, time)
Returns:
cumulative_infections: a xr.DataArray containing the cumulative infections
of dimension... | 57f617bb716036ddff23a785dd3cec5e579fe635 | 576,909 |
def task_15_list_customers_with_any_order_or_not(cur):
"""
List all customers, whether they placed any order or not.
Args:
cur: psycopg cursor
Returns: 213 records
"""
cur.execute("""SELECT customername, contactname, country, orderid
FROM customers
... | c3c8c66d4c244fb8fdc0c09bb67560e07c143546 | 576,912 |
def planckian_table_minimal_distance_index(planckian_table_):
"""
Returns the shortest distance index in given planckian table using
*Ohno (2013)* method.
Parameters
----------
planckian_table_ : list
Planckian table.
Returns
-------
int
Shortest distance index.
... | 70db6f22c47929e132ef3abad0dc9462aa6eb2fa | 576,913 |
from typing import Union
def filext(filename: str) -> Union[str, None]:
"""This grabs the extension of a filename. This is used to guess the MIMEtype of a file when sending it to the client."""
if not "." in filename:
return None
return filename.rsplit(".", 1)[1].lower() | 3dea1c6aabe60c83dc2758aa6a705b35d6132024 | 576,918 |
def subInSexp(sexp, x, y):
"""Substitute (replace) `x` with `y` in `sexp`, i.e. returns `sexp[y/x]`
"""
if type(sexp) != list:
return (y if sexp == x else sexp)
else:
return [subInSexp(s, x, y) for s in sexp] | 6179beeed451aa33f028f92f801a0d37db976be2 | 576,919 |
import struct
def dump_tensor_protos(protos):
"""
Serialize a list of :class:`TensorProto`, for communication between custom TensorFlow ops.
Args:
protos (list): list of :class:`TensorProto` instance
Notes:
The format is:
[#tensors(int32)]
(tensor1)[size of meta prot... | 9d2eacfd2b890203b0ef546810cfa845cd2c7765 | 576,921 |
def clean_name(name: str) -> str:
"""Clean a name to a ticker
Parameters
----------
name : str
The value to be cleaned
Returns
----------
str
A cleaned value
"""
return name.replace("beta_", "").upper() | 7f4f059137e1d5f4bb0667345075a073760f77ad | 576,924 |
import click
def get_user_credentials(username_msg, password_msg):
"""Get a username and password from the user
:param username_msg: The message to display when getting the username
:param password_msg: The message to display when getting the username
:return: A tuple of strings in the form (username... | b48ec6071ab33701519cd999a1dc8eac3560c632 | 576,925 |
async def convert_media_format(media_format):
"""Translates media format names into norwegian"""
media_formats = {
'TV': 'TV-Serie',
'TV_SHORT': 'Kort TV-Serie',
'MOVIE': 'Film',
'SPECIAL': 'Ekstramateriale',
'MUSIC': 'Musikk',
'MANGA': 'Manga',
'NOVEL': ... | bd338c984baf9fa46f2f427c8965ff2331198a76 | 576,926 |
def _check_image_valid(im_source, im_search):
"""Check if the input images valid or not."""
if im_source is not None and im_source.any() and im_search is not None and im_search.any():
return True
else:
return False | 4f8d3060d427b85a068a5c8d9db8358315299bd1 | 576,927 |
def Patch(image, i, j, m):
""" Returns a m x m patch taken from Image, centered at coordinates i,j """
patch = image[:, :, i-m:i+m+1, j-m:j+m+1]
return patch | cf763a97eaaf90a8b35ea574e974dcf33a753871 | 576,928 |
def make_abbr(text, title):
"""
Make a 'abbr' html element from body text and its definition (title)
Parameters
----------
text : str
Text to be definied
title : str
Definition for text
Returns
-------
str
"""
return f'<abbr title="{title}">{text}</abbr>' | 2091cc08736ce53522f3326b173286754748337e | 576,930 |
def I(x):
"""The identity function. Simply returns its input unchanged.
Since Patsy's formula parser ignores anything inside a function call
syntax, this is useful to 'hide' arithmetic operations from it. For
instance::
y ~ x1 + x2
has ``x1`` and ``x2`` as two separate predictors. But in::
... | 04cba8f2473ad8d9f99b2684643bd79bf6b10c60 | 576,932 |
import pickle
def pickle_object(save_path, obj):
"""
Pickle object to save_path location
Parameters:
-- save_path (str) : path to pickled object
-- obj : whatever object you want pickled
Returns:
-- None
"""
outfile = open(save_path, 'wb')
pickle.dump(ob... | ce642c88eebe385e8aa54eac2200687e2f886850 | 576,934 |
def dataframe_tptnfpfn(df, pos_label=True, labels=None):
"""Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2)
>>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]]
>>> columns=['Cat', 'Dog', 'Rabbit']
>>> x = np.array([[tc, pc] for (tc, row) in e... | 00a1f59c7699f375c088f86825b3a29076bc1fda | 576,936 |
def get_adapters_config(config_data):
"""Extracts adapters configuration from configuration data
:param config_data: A configuration file data
:return: A dictionary of the adapters configuration
"""
adapters = {k: config_data[k] for k in ('adapters',)}
adapters = adapters['adapters']
return... | 47d4fafc72634364275afc098670e547df189ae9 | 576,939 |
def clean_data_one(df):
"""Clean data for graph one"""
categories = df.drop(columns=['message', 'genre'])
sum_per_category = categories.sum()
percent_category = (
(sum_per_category / sum_per_category.sum())
.sort_values(ascending=False)
.reset_index()
)
percent_category.c... | 1ae4dc903346e8a1659d28ec6cea43a6b67691bc | 576,944 |
from datetime import datetime
def convert_date_to_unix(d):
""" Convert a given date to millis since epoch """
return int((d - datetime.utcfromtimestamp(0)).total_seconds() * 1000) | 1dd23d3b9ca327bf7dc8a8fa2493a3ae8556102c | 576,945 |
import warnings
def find_parameter(name, parameters_list):
"""
Utility method to loop through parameters to find values
etc...
Parameters
----------
name : str
parameter name
parameters_list : list
list of ParameterRecord objects or ControlRecord objects
Returns
-... | 854c651b1ea4ccf9383af083f832e57fbd4ccafa | 576,946 |
import torch
def neighbor_elements(atomic_numbers, neighbors):
"""
Return the atomic numbers associated with the neighboring atoms. Can also be used to gather other properties by
neighbors if different atom-wise Tensor is passed instead of atomic_numbers.
Args:
atomic_numbers (torch.Tensor): ... | 1a76135478162dc1a602a701a45e6a46b5c533ca | 576,947 |
from typing import Dict
def parse_yarn_lock(json_element: Dict) -> Dict[str, str]:
"""Parse yarn lock json into dict where
keys are package name + required version and value is locked version
Example:
{
"package@1.2.3": "1.2.3",
"utilsPackage@^1.2.3": "1.5.0",
"renderPackage@... | ac1abb94f1c1eca208d68460e2b9bb7d79d061fa | 576,957 |
def qb_datetime_format(input_date):
"""
Converts datetime to quickbooks datetime format
:param input_date:
:return:
"""
return input_date.strftime("%Y-%m-%dT%H:%M:%S") | d09e5ff99653f2f4a687fa06715a0c67d12bf6cc | 576,960 |
def names_cleaner(name):
"""
Helper function to clean up string from 'thml' symbols
"""
# pylint: disable=W1402
return name.replace('\u202a', '').replace('\u202c', '').strip() | aad1ddeb69a0ebba1350f7663a948b9ca31fb1e5 | 576,961 |
def parseDeviceNumber(deviceNum):
""" Parse the device number, returning the format of card#
Parameters:
deviceNum -- DRM device number to parse
"""
return 'card' + str(deviceNum) | fc5fb439865b6fff62d399bd0d02981e6ea710a7 | 576,963 |
def parser_stuffing_Descriptor(data,i,length,end):
"""\
parser_stuffing_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor serves as padding. It carries no data.
{ "type": "stuffing" }
(Defined in ETSI EN 300 468 specification)
"""
return { "type"... | 9904a881949aa3c6572254d8ad9b73c867d34175 | 576,965 |
def make_jinja2_filename(file_name: str) -> str:
""" Add .jinja2 to a filename.
:param file_name: the filename without an extension.
:return: the filename.
"""
return f'{file_name}.jinja2' | 3d8a9fe002e75b51e0b3e333bd8b7a4766bdb23b | 576,966 |
def linear_forecast(slope, intercept, value):
"""Apply the linear model to a given value.
Args:
slope (float): slope of the linear model
intercept (float): intercept of the linear model
value (float): int or float value
Returns:
float: slope * x + intercept
Example:
... | 8e9cff7ac5ef6cb43962470fbbcb148e2cef6040 | 576,967 |
def return_type(paper):
""" Return the PublicationTypeList from the paper nest"""
return str(paper['MedlineCitation']['Article']['PublicationTypeList'][0]) | 9775c6dda74346a4f06ead3719c4d2e28993e593 | 576,968 |
def censor(text, word):
"""takes two strings, text and word, as input and returns the text with the word you chose replaced with asterisks."""
result = ""
prep = text.split()
list_pos_counter = 0
for i in prep:
if i == word:
prep[list_pos_counter] = "*" * len(word)
list_p... | 9f92b4db40089a2b68d619adc1fafd8aa7a70067 | 576,970 |
def groupby_aggs(df,aggs,col = "object_id"):
"""
Given a Dataframe and a dict of {"field":"["agg", "agg"]"}, perform the
given aggregations using the given column as the groupby key. The original
(non-aggregated) field is dropped from the dataframe.
"""
res = None
for i,j in aggs.items():... | f725761de6b70d368f9af6c1b2a4a781031c44a4 | 576,975 |
from datetime import datetime
def from_timestamp(timestamp):
"""Convert timestamp to datetime object."""
return str(datetime.fromtimestamp(int(timestamp))) | 336738695f2998cdcbda96e8f65aa04ee5d732c5 | 576,976 |
import json
def decode_extra_parameters(metadata):
"""Returns a dictionary parsed from the json string stored
in extra_parameters
Parameters
----------
metadata
A SolarForecastArbiter.datamodel class with an extra_parameters
attribute
Returns
-------
dict
The ... | d86603fe86ed5944d22c616200ca77af24e54b1f | 576,977 |
def is_palindrome(string):
"""Returns whether a given string is a palindrome"""
return string[::-1] == string | db1358a2c2756e3fa69a248f9846c7c242b235f1 | 576,979 |
def preprocess(cube, input_layers):
"""
Takes the cube input and stores it in a dictionary where each key represents a layer name.
For clarity, the structure will be ``{..., input_layer_name_i:cube, ...}``. For the Salt
model, there is only one layer, so the output will be ``{first_input_layer_name:cube... | b259ea27ed20508d2b63dcb5a33251a2edc81eb1 | 576,983 |
from typing import List
def cal_information_gains(prior_entropies, pred_entropies) -> List[float]:
"""
Calculate information gains from prior and prediction entropies
:param prior_entropies: prior entropies
:param pred_entropies: prediction entropies
:return: list of information gain for each ent... | aa0188727b6b5c8b1ddf70fd50242769e20e47a1 | 576,988 |
def has_hash_diff(install_file, codebase_resource):
"""
Return True if the one of available hashes on both `install_file` and
`codebase_resource`, by hash type, is different.
For example: Alpine uses SHA1 while Debian uses MD5, we prefer the strongest hash
that's present.
"""
hash_types = ["... | 1241c4d4aa9302db99c08735e19db02be59d4247 | 576,990 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.