content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
async def mock_async_call():
""" mocks a generic async function """
return True | 09d35540c0a9c69a2b90cced80085fe58384858e | 673,929 |
def dec_indent(indent, count=1):
"""
decrease indent, e.g.
if indent = " ", and count = 1, return " ",
if indent = " ", and count = 2, return "",
"""
if indent.endswith('\t'):
indent = indent[:len(indent) - 1 * count]
elif indent.endswith(' '):
indent = in... | 0f8bf02b67ea7fbb539cdf04ac8d70dd51f3e57a | 673,934 |
import yaml
from textwrap import dedent
def create_cron_resource(name="cron", minute=5, image="cron-image"):
"""Create a CronTab resource from parameters.
Args:
name (str): name of the resource
minute (int): time set for the minutes in the CRON specifications.
image (str): image used ... | 03d9ae543b49d067792d80463b80cccb295be747 | 673,935 |
def freeze_one_half(basis):
"""
Split the structure into two parts along the z-axis and then freeze the position of the atoms
of the upper part (z>0.5) by setting selective dynamics to False.
Args:
basis (pyiron_atomistics.structure.atoms.Atoms): Atomistic structure object
Returns:
... | f48f1c3e1b9b73b203ea9dec0091e6500c5a338c | 673,939 |
def format_args(args):
"""Formats the args with escaped " """
comma = "," if args else ""
return comma + ",".join(['\\\"' + a + '\\\"' for a in args]) | d62baeb4f4bb45fdd13386fdf023bc1fb66444ba | 673,941 |
def rescale(ndarray, min, max):
"""Rescale values of ndarray linearly so min of ndarray is min, max is max
Parameters
----------
ndarray: numpy nd array
min: int
max: int
Returns
-------
numpy ndarray
"""
old_max = ndarray.max()
old_min = ndarray.min()
old_range =... | f1266a6d91fe207a454293de30ff7c7603f91bf3 | 673,942 |
def parse_so_terms(so_file):
"""Retrieve all available Sequence Ontology terms from the file.
"""
so_terms = []
with open(so_file) as in_handle:
for line in in_handle:
if line.find('name:') == 0:
name = line[5:].strip()
so_terms.append(name)
return... | c61acbd574701244a4ad9cdca5095e4b12514bda | 673,943 |
def avgTeq(L, a, e=0., albedo=0., emissivity=1., beta=1.):
"""compute the time-averaged equilibrium temperature as in Mendez+2017.
This uses eqn 16 in Méndez A, Rivera-Valentín EG (2017) Astrophys J 837:L1.
https://doi.org/10.3847/2041-8213/aa5f13"
Parameters
----------
L : float
stell... | 994821be5f397cd504bfcb4040e17d066bcaf3ae | 673,944 |
def is_member(user, groups):
""" Test if a user belongs to any of the groups provided.
This function is meant to be used by the user_passes_test decorator to control access
to views.
Parameters
----------
user : django.contrib.auth.models.User
The user which we are trying to identify t... | f1b2acc378900d9f4d53b2a9069531c45e3743b8 | 673,945 |
def _UpdateFertileSlotsShape(unused_op):
"""Shape function for UpdateFertileSlots Op."""
return [[None, 2], [None], [None]] | 6332cb6856bf124a1c051c20f7fe227b17cca160 | 673,948 |
def str2bytes(data):
"""
Converts string to bytes.
>>> str2bytes("Pwning")
b'Pwning'
"""
return bytes(data, encoding="utf-8") | 0e9ef347c245cdf4965e0b594b450ebeebc52a41 | 673,951 |
import math
def normalize(val, min_val, max_val):
"""
Normalize the popularity value with log transformation.
"""
new_val = val - min_val + 1
return math.log(new_val) | 011bb397fadf80bc05be80fc02773816e8aff2e1 | 673,960 |
def black_is_not_installed(*args, **kwargs):
"""Check black is not installed."""
return not args[0] == "black" | 1f6942e529aefbb905fcee67bd315af7f7e8e6a9 | 673,963 |
def get_trend(row, window_size, center=True):
"""
Returns trend component of a time series
:param row: pandas series containing the time series to extract seasonality from
:param window_size: length of moving window
:param center:
:return:
"""
trend = row.rolling(window_size, center=cent... | 6c241f595c1ce904bc56dc639358abcdf9ae62e7 | 673,968 |
def _get_prefixes(response):
"""
return lists of strings that are prefixes from a client.list_objects() response
"""
prefixes = []
if 'CommonPrefixes' in response:
prefix_list = response['CommonPrefixes']
prefixes = [prefix['Prefix'] for prefix in prefix_list]
return prefixes | 4f4734d4f8282aea7699bb54fe17991cb339020c | 673,971 |
def interface_to_ip(interface):
"""
Gets the IPv4 address from a `net_if_addrs` interface record.
The record is passed as a `snic` `namedtuple`.
This function locates the IPv4 one and returns it.
"""
for record in interface:
if record.family == 2: # AF_INET
return record.add... | 1ee2ae312c892e11e7abcabcf7846651030215e2 | 673,972 |
def filter_dict_keys(org_dict, keep_keys):
"""Helper function to keep only certain keys from config.
Pass in a dictionary and list of keys you wish to keep
Any keys not in the list will be removed in the returned dictionary"""
newDict = dict()
# Iterate over all the items in dictionary and filter it... | d4b971f643236d55f76cfd30c844f2ea41feec6e | 673,974 |
import gzip
import re
def readHeader(fname):
"""Read QA4ECV NO2 ASCII data header.
PARAMETERS
----------
fname : str
Path to the filename
RETURNS
-------
header : a list of useful variables: year, month, nlat, nlon, lat_start, lat_end, lon_start, lon_end
"""
f=gzip.open(... | 5c1549b9be220f5875820b14ea6239bfa5d7d10e | 673,976 |
from typing import Set
import click
def get_states_as_set(state_list: str) -> Set:
"""Helper method to parse the state string.
Args:
state_list: comma separated string with codes and states
Returns:
Set with valid state names in upper case
"""
codes_to_states = {
"BF": "B... | af6160cee0f8d84f3e8accbc3a8e949bb21c95bd | 673,980 |
def transform_globs_into_regexes(globs):
"""Turns glob patterns into regular expressions."""
return [glob.replace("*", ".*").replace("?", ".") for glob in globs] | bda321b2b1cb863bb0e3944bb5c9ef7b77427aae | 673,984 |
def adjust_convention(img, convention):
"""
Inverts (could) the image according to the given convention
Args:
img (np.ndarray): Image numpy array
convention (int): -1 or 1 depending on macros.IMAGE_CONVENTION
Returns:
np.ndarray: Inverted or non inverted (vertically) image.
... | dcd3de247921a338c0356c79ee1828af10713f35 | 673,991 |
import textwrap
async def snippet_to_embed(file_contents, file_path, start_line, end_line):
"""Given file contents, file path, start line and end line creates a code block"""
split_file_contents = file_contents.splitlines()
if start_line is None:
start_line, end_line = 1, len(split_file_contents... | 9872d32c40b7b0a2c7c388496cab3c83b44023c2 | 673,996 |
def stringify_keys(d):
# taken from https://stackoverflow.com/a/51051641
"""Convert a dict's keys to strings if they are not."""
keys = list(d.keys())
for key in keys:
# check inner dict
if isinstance(d[key], dict):
value = stringify_keys(d[key])
else:
va... | 5e235823af70107eb96ddde91f7175442b32efb3 | 673,997 |
def make_average(fn, num_samples=100):
"""Return a function that returns the average_value of FN when called.
To implement this function, you will have to use *args syntax, a new Python
feature introduced in this project. See the project description.
>>> dice = make_test_dice(3, 1, 5, 6)
>>> avg_... | 940090cb690a84f2feba6f80b261941d2b71ffa0 | 673,998 |
def format_time(total_seconds, hours_fmt=False, precise=False, hours_pad=True):
"""
Convert total_seconds float into a string of the form "02:33:44". total_seconds amounts
greater than a day will still use hours notation.
Output is either in minutes "00:00" formatting or hours "00:00:00" formatting.
... | ddb0555b78cff794b86bd3c36de971c47c123745 | 674,002 |
def get_channels_number(*, mode: str) -> int:
"""
This function return the numbers of channels given a color mode.
Parameters
----------
mode: str
color mode.
Returns
-------
out: int
number of channels associated with the color mode.
"""
if mode == "YCbCr":
... | 8a7d495d04dd731888083730e94af53e73f51c43 | 674,003 |
def _merge_ranges(ranges):
"""
From a list of ranges (i.e.: list of tuples (start_idx, end_idx)
Produce a list of non-overlapping ranges, merging those which overlap.
:param ranges: list of tuples (start_idx, end_idx)
:return: list of tuples (start_idx, end_idx)
"""
if ranges == []:
return []
r... | 6dd284ccefead6fde61f4d7353264a5ebc1553b2 | 674,004 |
def find_when_entered_basement(text):
"""Find position in text when santa enters basement first time."""
cur_floor = 0
for position, floor_change in enumerate(text, start=1):
cur_floor += 1 if floor_change == '(' else -1
if cur_floor < 0:
return position
return -1 | bb3a5d9949297fdba905e9bd596ad64635ab5861 | 674,005 |
from typing import Iterable
from typing import Tuple
from typing import Dict
from typing import List
def adjacency_list(edges: Iterable[Tuple[str, str]]) -> Dict[str, List[str]]:
"""
Convert a sequence of undirected edge pairs into an adjacency "list".
"""
adj = {}
for e1, e2 in edges:
if... | 269599602a44d78287b67fea3aed381d4580fa69 | 674,006 |
import string
import random
def randStr(chars = string.ascii_uppercase + string.digits + string.ascii_lowercase, N=42):
"""Generate a random string of len 42 to spoof a reset token"""
return ''.join(random.choice(chars) for _ in range(N)) | ed7d5cfc72a7d7e1e5e269c4ba9af76f2c208408 | 674,009 |
def _merge(*parts):
"""
Utility function to merge various strings together with no breaks
"""
return ''.join(parts) | d6a7b51677d6c2c8adbeeea1c8e8b2d8b878892b | 674,012 |
def parse_sensors(configuration):
"""
Bake the sensors array to a dict where the telldus id is
the key for easier parsing later on.
"""
result = {}
for sensor in configuration["my_sensors"]:
result[sensor["id"]] = sensor
return result | 396db49ce78cd61c8ce450203a11b2d07798156e | 674,014 |
def get_egress_lossless_buffer_size(host_ans):
"""
Get egress lossless buffer size of a switch
Args:
host_ans: Ansible host instance of the device
Returns:
total switch buffer size in byte (int)
"""
config_facts = host_ans.config_facts(host=host_ans.hostname,
... | a2bd17d4d8b522f80e4f3749feb29aa63fd80184 | 674,017 |
def format_nums(number, decimals):
"""
rounds to a number of decimals and if possible makes a integer from float
:param number: input number
:param decimals: decimals to round to
:return: integer or float
"""
if round(float(number), decimals).is_integer():
return int(f"{number:.0f}... | fe51717404ecd569cfcea63a18bcf4aa3f58214f | 674,023 |
def _totuple(a):
"""
Converts a numpy array into nested tuples, so that each row of the array
is a different tuple.
E.g.
a = [ [0 1 2 3]
[4 5 6 7] ]
out = ((0, 1, 2, 3), (4, 5, 6, 7))
"""
try:
return tuple(_totuple(i) for i in a)
except TypeError:
return a | 518d4a089e449f7e908b2327c98a3588839e4089 | 674,026 |
from pathlib import Path
def some_dir(tmp_path) -> Path:
"""Folder with some data, representing a given state"""
base_dir = tmp_path / "original"
base_dir.mkdir()
(base_dir / "empty").mkdir()
(base_dir / "d1").mkdir()
(base_dir / "d1" / "f1").write_text("o" * 100)
(base_dir / "d1" / "f2").... | 1fa99d40b102107d39df18f5cbd1337a3163d645 | 674,029 |
def DEFAULT_REPORT_SCRUBBER(raw):
"""Default report scrubber, removes breakdown and properties."""
try:
del raw['breakdown']
del raw['properties']
except KeyError:
pass
return raw | 9fddb184a7ad91172f0dc64d1df3ac968362c6e5 | 674,032 |
def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | 0dc40dc8ec4176f0cd30c508a837aeba5d073e03 | 674,033 |
def _task_info(clazz):
"""
from a provided class instance extract task metadata.
This will error if any of the expected fields of the task are missing.
:param clazz: class object you need metadata for
:return: a metadata dictionary
"""
params = []
for e in clazz.parameters:
param... | 66132749b9e30c9b103f39159c0c48c7f47930e0 | 674,036 |
import hashlib
def sha1sum(filename):
"""return the sha1 hash of a file"""
with open(filename, mode='rb') as f:
d = hashlib.sha1()
while True:
buf = f.read(8192)
if not buf:
break
d.update(buf)
return d.hexdigest() | 5eda7df935cd12e827c1e340ea77143a34f4575a | 674,037 |
def get_tokens_from_node(node, result=None):
"""Return the list of Tokens in the tree starting at node."""
if result is None:
result = []
for dtr in node.dtrs:
if dtr.isToken():
result.append(dtr)
get_tokens_from_node(dtr, result)
return result | ff7269b6d042b8d565cfff4ecd30b9d24ae56a91 | 674,038 |
import re
def parse_string_to_int_tuples(tuples):
""" parse a string to tuples, while the string is:
(x, x, x, x), (x, x)...
"""
tuple_list = re.findall('[(](.*?)[)]', tuples)
ret = []
for i in tuple_list:
int_shape = []
shape = i.strip().split(',')
for j in shape:
if j:
int_... | 642f504dda665c062fac59a08be1964c4dced602 | 674,040 |
import requests
from bs4 import BeautifulSoup
def get_url_from_character_page(url_IDMB,THUMBNAIL_CLASS="titlecharacters-image-grid__thumbnail-link"):
"""
Gets url of image viewer of a serie pictures on IMDB (e.g. https://www.imdb.com/title/tt0108778/mediaviewer/rm3406852864)
Given the url of a character o... | b5dfac0c28ca476e860149e6920cd96fbc419ba0 | 674,044 |
def get_orders_list(orders_dict):
"""Returns orders list from orders dict"""
return orders_dict.get('orders') | 12c6eb7dc8cd774b265bf0e1dd3b7f21a1d52f0b | 674,048 |
def _generate_anchor_configs(min_level, max_level, num_scales, aspect_ratios):
"""Generates mapping from output level to a list of anchor configurations.
A configuration is a tuple of (num_anchors, scale, aspect_ratio).
Args:
min_level: integer number of minimum level of the output feature pyramid.
... | d0bfd58b012965ec42d067c2878d6f1c9f4f35e9 | 674,049 |
import copy
def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0):
"""Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad_id : int
... | fe03c11a2e583b2bc5be413cda0f632387a763f3 | 674,051 |
import sqlite3
import typing
def get_robot_types(cursor: sqlite3.Cursor) -> typing.List[dict]:
"""Gets all robot types from the db
:param cursor: [description]
:type cursor: sqlite3.Cursor
:return: [description]
:rtype: typing.List[dict]
"""
return cursor.execute(
"SELECT id, nam... | 8aa21cebf8211ecaf8093a3d76e3bbfe48760ee5 | 674,054 |
from typing import Sequence
from typing import Dict
def get_tagged_secrets(secrets_manager, secrets_tags: Sequence[str]) -> Dict[str, str]:
"""
Return a dictionary of AWS Secrets Manager names to arns
for any secret tagged with `secrets_tag`.
"""
secrets = {}
paginator = secrets_manager.get_p... | 14637ff1f76e2db5e857d56ce328d3cc6c165d67 | 674,067 |
def usechangesetcentricalgo(repo):
"""Checks if we should use changeset-centric copy algorithms"""
if repo.filecopiesmode == b'changeset-sidedata':
return True
readfrom = repo.ui.config(b'experimental', b'copies.read-from')
changesetsource = (b'changeset-only', b'compatibility')
return readf... | cd3d1d2a1566b24947caf0369d0e09550673ae0b | 674,068 |
def can_zip_response(headers):
"""
Check if request supports zipped response
:param headers: request headers
:return:
"""
if 'ACCEPT-ENCODING' in headers.keys():
if 'gzip' in headers.get('ACCEPT-ENCODING'):
return True
return False | 26021f2778ced4174aae29850a42ea95ea32172a | 674,070 |
from typing import Optional
from typing import Dict
from typing import List
def get_mock_aws_alb_event(
method,
path,
query_parameters: Optional[Dict[str, List[str]]],
headers: Optional[Dict[str, List[str]]],
body,
body_base64_encoded,
multi_value_headers: bool,
):
"""Return a mock AWS... | 63c87da158285482fa242fc36db64865d4355e5d | 674,071 |
def get_artist_names(artist_database, artist_id):
"""
Return the list of names corresponding to an artist
"""
if str(artist_id) not in artist_database:
return []
alt_names = [artist_database[str(artist_id)]["name"]]
if artist_database[str(artist_id)]["alt_names"]:
for alt_name... | 7cac34db693418650530c4551bc52742cd634173 | 674,072 |
def containsAll(str, set):
"""
Checks if a given string contains all characters in a given set.
:param str: input string
:type: string
:param set: set if characters
:type: string
:rtype: boolean
"""
for c in set:
if c not in str: return False
return True | 0d167d9901f9f8b7ace23d58724b87b29af89c48 | 674,075 |
def format_artist_rating(__, data):
"""Returns a formatted HTML line describing the artist and its rating."""
return (
"<li><a href='{artist_tag}/index.html'>{artist}</a>" " - {rating:.1f}</li>\n"
).format(**data) | 49ebafaff169662f80ff80f2884981ca029d9f08 | 674,081 |
def _human_list(listy):
"""
Combines a list of strings into a string representing the list in plain
English, i.e.
>>> _human_list(["a"])
"a"
>>> _human_list(["a", "b"])
"a and b"
>>> _human_list(["a", "b", "c"])
"a, b and c"
"""
if len(listy) == 1:
return listy[0]
... | 4eeae7264368d2c0da33df319a8574cbf17a0bfd | 674,085 |
import hashlib
def _hash_file(fpath, algorithm="sha256", chunk_size=65535):
"""Calculates a file sha256 or md5 hash.
# Example
```python
>>> from keras.data_utils import _hash_file
>>> _hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8... | abc4874c9284a0e00392cc7668ce9d94e64e94ee | 674,086 |
def avoid_keyerror(dictionary, key):
""" Returns the value associated with key in dictionary. If key
does not exist in the dictionary, print out 'Avoid Exception' and
map it to the string 'no value'.
>>> d = {1: 'one', 3: 'three', 5: 'five'}
>>> avoid_keyerror(d, 3)
'three'
>>> avoid_keyer... | 7c55a5ea9c682547a1ab72474d488b2d24bdaca5 | 674,087 |
def string_boolean(value):
"""Determines the boolean value for a specified string"""
if value.lower() in ('false', 'f', '0', ''):
return False
else:
return True | b6da9f2802fba2014e2bc2b2eb97791c23aee4bb | 674,089 |
import torch
def cosine_similarity(x, y=None, eps=1e-8):
"""Calculate cosine similarity between two matrices;
Args:
x: N*p tensor
y: M*p tensor or None; if None, set y = x
This function do not broadcast
Returns:
N*M tensor
"""
w1 = torch.norm(x, p=2, dim=1, keepdim=True)
if y is None... | 68faf837293556409899487b47de072d013a1f42 | 674,093 |
def all_same(L):
"""Check if all elements in list are equal.
Parameters
----------
L : array-like, shape (n,)
List of objects of any type.
Returns
-------
y : bool
True if all elements are equal.
"""
y = len(L) == 0 or all(x == L[0] for x in L)
return y | 8ceee5400f348de205a769fb1553901e4dd6a62e | 674,095 |
def _IsDuplicateInterestedUser(url_entity, bots_user_key):
"""Checks if bots_user_key exist in interested_users.
Args:
url_entity: BotsUrl Entity to check for.
bots_user_key: bots_user entity key (db.Key).
Returns:
True if bots_user_key exist in interested_users, else False.
"""
return str(bots_... | 974580702e0cc05d28a285062447c050a5593444 | 674,096 |
def defined_or_defaut_dir(default, directory):
"""
if given a directory it will return that directory, otherwise it returns the default
"""
if directory:
return directory
else:
return default | 6d8227cb215e2eb8f44a806c21476b9467471672 | 674,097 |
def display_timedelta(minutes):
"""Converts timedelta in minutes to human friendly format.
Parameters
----------
minutes: int
Returns
-------
string
The timedelta in 'x days y hours z minutes' format.
Raises
------
ValueError
If the timedelta is negative.
"... | c8606cf6defcc38e5a12dc88cfc65d7c21aefd69 | 674,099 |
def obs_model_parameter_values(values):
"""
Return a list containing all of the values for a single parameter.
:param values: The values for the parameter.
:type values: Union[List[Any], Any]
"""
if isinstance(values, list):
return values
else:
return [values] | bcd8fe5847cf52c13795621842fff2154c91b693 | 674,102 |
import ast
def subscript_type_to_string(subscript: ast.Subscript) -> str:
"""
Returns a string representation of a subscript.
For example, if the subscript is Optional[int] it returns "Optional[int]".
"""
return ast.unparse(subscript) | 2c6f20df7d655858c5c3bfa7f992448f8012d856 | 674,103 |
import random
def makelist(random_int):
"""Creates a list of random float values of total list length
random_int (specified as function param)"""
num_list = []
for count in range(random_int):
num_list.append(random.random())
return num_list | 8479ae3b52b6a8f7723ffe7bd71caca9f5ab9c18 | 674,105 |
def get_table_headers(table):
"""Given a table soup, returns all the headers"""
headers = []
for th in table.find("tr").find_all("th"):
headers.append(th.text.strip())
return headers | 7a7291a4a440dfed678e3060f10c9083c27775ca | 674,108 |
import logging
from datetime import datetime
from pathlib import Path
import requests
def download_file(url, file_location=None, overwrite=False):
"""
Purpose:
Download file from specified URL and store in a specfied location.
If no location is provided, the file is downloaded in the current
... | e5e96485faa5b5577688d4dff4f3631b83ce05cd | 674,111 |
import re
def md(text):
"""Basic filter for escaping text in Markdown."""
return re.sub(r'([_*])', r'\\\1', text) | e4ab0c874cb0818778506fdf77d79b1a0c2515ed | 674,113 |
def get_confirmation_block_from_results(*, block_identifier, results):
"""
Return the confirmation block from results list
"""
return next((i for i in results if i['message']['block_identifier'] == block_identifier), None) | 5e815f7c59a953c8b373d0d484ef70e528458424 | 674,116 |
def add(initial: int=0, number: int=0) -> int:
"""Return sum of *intial* and *number*.
:param initial: Initial value.
:type initial: int
:param number: Value to add to initial.
:type number: int
:return: Sum of initial and number.
:rtype: int
"""
return initial + number | 14b29b7ff49ac2961fe49ddbade7eddc3fd2a7a3 | 674,117 |
from urllib.parse import urlencode
from typing import OrderedDict
def make_pr_link(url, project, slug, from_branch, to_branch):
"""Generates a URL that can be used to create a PR"""
if "github.com" in url:
result = "{url}/{organization}/{repo_name}/compare/{to_branch}...{from_branch}".format(
... | db5b43db58348789092d3170ccc8e84e32230255 | 674,119 |
from typing import List
from typing import Tuple
def generate_options_for_point(x: int, y: int, z: int) -> List[Tuple[int, int, int]]:
"""
generate 24 different orientations for point presented of (x, y, z)
"""
return [(x, y, z), (z, y, -x), (-x, y, -z), (-z, y, x),
(-y, x, z), (z, x, y), ... | 34530c959686692ac6d749653f8da3a99c0bc4bc | 674,122 |
def filter_bin(length, index_pairs):
"""
用于某些二进制标志位的场景
index_pairs: {index: value,}
返回 length 长度内第 index 位值为 value 的所有可能的 int 的 list, index 从 1 开始, e.g.
>>> filter_bin(3, {1: 1})
[1, 3, 5, 7]
>>> filter_bin(3, {1: 1, 2: 0})
[1, 5]
>>> filter_bin(3, {1: 0, 2: 1})
[2, 6]
"""
... | 692448a8ff75ca997e551ed193498498931ee6ed | 674,123 |
def switch_month(month: str):
"""
Translates an english month to a french one. For example: 'Jan' becomes '(01)Janvier'.
month : the month that will be translated
"""
return {
"Jan": "(01)Janvier",
"Feb": "(02)Fevrier",
"Mar": "(03)Mars",
"Apr": "(04)Avril",
... | 2a292c64333d9455ca6ce5b7f41b9e83eee2cb82 | 674,133 |
import json
def extract_json(serie, k):
"""Extract a value by a key."""
return serie.map(lambda row: json.loads(row)[k]) | 1ac588712e832d5e282ca223f3205b2e59d3891a | 674,145 |
def escape_quotes(s: str) -> str:
"""Replaces double quotes in the input string with either ' or \\".
Description:
Given a string, returns that string with double quotes escaped in one of two ways.
If the string contains single quotes, then \\" will be used to escape the double quotes.... | 836ff53b7aa19f0a0aeba768b0b9ca181ecd5a4e | 674,150 |
def process_icon_emoji(inIconEmoji: str) -> str:
"""Process an 'icon_emoji' string.
Args:
inIconEmoji:
Single icon emoji string.
Returns:
Properly formatted 'icon_emoji' string
"""
tmpStr = inIconEmoji.strip(": ")
return f":{tmpStr}:" if tmpStr else "" | 8c497c3c213d5c1ae6dd2991ec0ce1547ba0cf62 | 674,154 |
def GetLabelsFromDict(metadata):
"""Converts a metadata dictionary to a string of labels.
Args:
metadata: a dictionary of string key value pairs.
Returns:
A string of labels in the format that Perfkit uses.
"""
return ','.join('|%s:%s|' % (k, v) for k, v in metadata.iteritems()) | 907611aa94551565d86eccf0f8b01740cd480484 | 674,156 |
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str:
"""The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks.
This one liner accommodates for this by just padding a code block with 4 additional spaces.
Hacky? Sure. Effective? Yu... | 4f6f1f61f211292c9f92975fb12659f283f566ef | 674,158 |
def subsample(data, every=5):
"""Subsample to the desired frequency. Use every `every`th sample."""
return data[::every] | 799516f13e75608fbaf22f9adcafff5247fc33d6 | 674,159 |
def get_subclasses(klass):
"""Gets the list of direct/indirect subclasses of a class"""
subclasses = klass.__subclasses__()
for derived in list(subclasses):
subclasses.extend(get_subclasses(derived))
return subclasses | 22d9a8def2a1d6b795c05ee0e0fa1899ee839c8b | 674,161 |
def is_vulnerable(source):
"""A simple boolean function that determines whether a page
is SQL Injection vulnerable from its `response`"""
errors = {
# MySQL
"you have an error in your sql syntax;",
"warning: mysql",
# SQL Server
"unclosed quotation mark after the cha... | aafb015e794bccd100a8d63954d6fd43b2ddcf91 | 674,167 |
def skip_material(mtl: int) -> int:
"""Computes the next material index with respect to default avatar skin indices.
Args:
mtl (int): The current material index.
Returns:
int: The next material index to be used.
"""
if mtl == 1 or mtl == 6:
return mtl + 2
return mtl + 1 | fc167912b06137244bbbcb7d9b4225334a5e564e | 674,169 |
import json
import requests
def getProcedures(host, service):
"""
Get all the procedures (stations) using the WA-REST API
"""
proc_url = f"http://{host}/istsos/wa/istsos/services/{service}/procedures/operations/getlist"
# Request and Get the procedures from the response
procedures = json.loa... | 442727d6b844855f52fd6f3f3b52b31aeab5a1bd | 674,171 |
def agg_moy_par_pret(dataframe, group_var, prefix):
"""Aggregates the numeric values in a dataframe. This can
be used to create features for each instance of the grouping variable.
Parameters
--------
dataframe (dataframe):
the dataframe to calculate the statistics on
g... | d046591d17249e21eb65c197aa26bce394a5abdf | 674,172 |
import unicodedata
def lowercase_and_remove_accent(text):
"""
Lowercase and strips accents from a piece of text based on
https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
"""
text = " ".join(text)
text = text.lower()
text = unicodedata.normalize("NFD"... | f05d6815c5dfec40ed51b50662e171c0e13809f6 | 674,173 |
import random
def blood_pressure_depending_on_age(age):
"""Randomly generate a blood pressure value depending upon the given age
value.
It is assumed that for a given age value the blood pressure is normally
distributed with an average blood pressure of 75 at birth (age 0) and of
90 at age 100,... | 77dfbe437a37659ae2326c8aa42c5d8cd5df429b | 674,176 |
def write_content(path, content):
"""Write string content to path name."""
print(f"- writing {path}")
with open(path, 'w') as file:
file.write(content)
return path | cba2dd75969435863078f032c01ca2b83745cc0a | 674,178 |
import hashlib
def sha1_hash(bytes):
"""
Compute the SHA-1 hash of a byte stream.
"""
sha = hashlib.sha1()
sha.update(bytes)
return sha.digest() | ba45c369407a77bc320b511bafcec7a7c503cf38 | 674,184 |
def founder_allocation() -> float:
"""How much tokens are allocated to founders, etc."""
return 0.2 | 90967e693d9c21c3f729bc9ffdea1472768f58b0 | 674,185 |
import torch
def generate_padding_masks(data, pad_value=0):
"""
Returns a mask based on the data. For values of the padding token=0, the mask will contain 1, indicating the
model cannot attend over these positions.
:param data: The data of shape (sequence_len, batch_size)
:param pad_value: The val... | f11baece2f4e087440b88562204a4cf187ded6cc | 674,189 |
from typing import Dict
def _get_local_logging_config() -> Dict:
"""Create local logging config for running the dummy projects."""
return {
"version": 1,
"formatters": {
"simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
},
"root": {"level"... | ba9503e6f408533e360b64eef66d971b9ba4f51a | 674,191 |
import warnings
def get_mol_3d_coordinates(mol):
"""Get 3D coordinates of the molecule.
This function requires that molecular conformation has been initialized.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule instance.
Returns
-------
numpy.ndarray of shape ... | 7174a29decb05398cae8c4859b323f86d67fb747 | 674,194 |
def population_render_transparency(x, invert_colours=False, b=None):
"""Render image from patches with transparancy.
Renders patches with transparency using black as the transparent colour.
Args:
x: tensor of transformed RGB image patches of shape [S, B, 5, H, W].
invert_colours: Invert all RGB values.
... | de7e7a0e0fc79ed889fce4bb686d77eff6d1c078 | 674,196 |
def youngs(vp=None, vs=None, rho=None, mu=None, lam=None, bulk=None, pr=None,
pmod=None):
"""
Computes Young's modulus given either Vp, Vs, and rho, or
any two elastic moduli (e.g. lambda and mu, or bulk and P
moduli). SI units only.
Args:
vp, vs, and rho
or any 2 from la... | 127d0598a4e8d53c2e31b10c53ab1fddfedc4987 | 674,202 |
def initial_workload_is_ready(ops_test, app_names) -> bool:
"""Checks that the initial workload (ie. x/0) is ready.
Args:
ops_test: pytest-operator plugin
app_names: array of application names to check for
Returns:
whether the workloads are active or not
"""
return all(
... | fa789c7993f3773c125bf95989e24d7ab7f09278 | 674,203 |
def duplication_consistency(set_one, set_two):
"""
Calculates the duplication consistency score for two sets of species
:param set_one: set/list of species
:param set_two: set/list of species
:return: float with duplication consistency score
"""
union_size = len(set(set_one).union(set(set_t... | e5f84fd15d75b8dc3046e17efdc69ef4848adf3e | 674,213 |
def _auto_correlations(n_states):
"""Returns list of autocorrelations
Args:
n_states: number of local states
Returns:
list of tuples for autocorrelations
>>> l = _auto_correlations(np.arange(3))
>>> assert l == [(0, 0), (1, 1), (2, 2)]
"""
local_states = n_states
retur... | f908a30d2942a5d8c305fffa54752a528a45ba7f | 674,216 |
import re
def process_clinical_significance(clin_sig):
"""
Processes ClinVar clinical significance string into a format suitable for OT JSON schema.
Namely, splits multiple clinical significance levels into an array and normalises names (to lowercase, using only
spaces for delimiters). Multiple level... | d266ca548455a50dba3c9ec0aa08a11a52eab53b | 674,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.