content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import io
import zipfile
def build_zip_file_in_memory(entries):
"""
Creates a zip file by writes files and data to a zip file
:param entries is compose of MemoryZipFile objects and MemoryZipData
:return: File-like object containing a zip file, backed in memory.
"""
zip_bin = io.BytesIO()
... | 1d2285a3292e89e2a189ea9a5e5ae94f7cd48ba2 | 585,431 |
def moments_parser(data, label) -> dict:
"""
moments are returned from the rest api as a dictionary. The moments parser returns a dictionary that only contains the specified label
Parameters
----------
data : dict
The complete dictionary
label : str
The key value of moments to ... | ddb70fe5c3685894b18940bed9b00fc8e40e8a79 | 585,438 |
def fix_samp_id(mystring):
"""Remove all of the extra ID info from TCGA barcodes."""
if mystring.startswith('TCGA'):
return mystring[:12]
else:
return mystring | fdb45475d7df8e2de8884dbdedd6c66dc3657a9f | 585,442 |
def get_props(obj, prop_names):
"""
Get multiple attributes of `obj`.
Names are given by `prop_names` list.
"""
return [getattr(obj,p) for p in prop_names] | 49e977c7cdd4acd49ecc1b9974cf8343c054ebe6 | 585,446 |
def validate_channel_config(channel_config):
"""
Validates a channel config
Args:
channel_config (dict):
the channel config object
Returns:
list of str:
list of errors or an empty list if no errors
"""
errors = []
if not channel_config:
erro... | 7793d9c45ee32fb411af1db96545fa2aa596fc80 | 585,456 |
def gaussian_focal_loss(pred, target, alpha=2.0, gamma=4.0):
"""
Focal Loss introduced in [1] for targets in gaussian distribution.
Args:
pred (:obj:`torch.Tensor`): The predictions.
target (:obj:`torch.Tensor`): The learning targets in gaussian
distribution.
alpha (floa... | 92911aa9f395580a1c6fd48fd718c46fe713acad | 585,462 |
def parse_args(content):
"""Gets the command name and arguments from message content"""
#Split the message
splited = content.split(" ")
command_text = splited[0]
args = splited[1:]
command_text = command_text[1:]
command = command_text
#If the message is in a group, we need to remove... | dc92b213cc09a747bda9d7ee7cc3225310a64a48 | 585,466 |
def resolve_parent(previous, parent):
"""
Figure out the parent to use based on the previous pane or given parent
Breadth-based recursion means the previous pane should take precedence
over the original parent if one is provided
Parameters
----------
previous
The previous pane
... | cfe5150def14037a1ad1c85128e7664db58bb674 | 585,468 |
def trloadchan(dbin, t0, t1, sta, chan):
"""Load time-series data for a given station, channel, and time-interval into memory"""
return dbin.loadchan(t0, t1, sta, chan) | 63ec20feed91577d278f03c1f6ba2cc10a61afd3 | 585,469 |
from typing import List
def change_base(number: int, base: int) -> List[int]:
"""Express an integer in another base.
Args:
number: The integer to convert.
base: The base to which to convert number.
Returns:
A list of integers, where each integer is a digit in number expressed
... | 977dbbac1998b33acb10e5595a5e91edb2f77c43 | 585,470 |
from datetime import datetime
def validate_timestamp(timestamp): # test
"""Validates timestamp input for correct format
Args:
timestamp: datetime string
Returns:
boolean: if string is in correct format
"""
try:
datetime_input = datetime.strptime(timestamp, '%Y-%m-%d %H:%... | 175a235de7f7eb6187fbaf73a75b25924b01197a | 585,473 |
def normalize_data(x):
"""Normalize data to values between 0-1
Args:
x(NxN float matrix): data to be normalized
Returns:
x_norm((NxN float matrix): normalized data
"""
return (x-x.min())/(x.max()-x.min()) | b58c24fe4ecc1aa0556f672a3d34e2b5bb29b5c8 | 585,474 |
def multiply_regular(data):
"""
Multiplies all elements in passed sequence.
You may assume that all elements in passed argument is numeric.
>>> multiply_regular([3, 6, 9])
162
>>> multiply_regular(range(10))
0
>>> multiply_regular(range(1, 10))
362880
>>> multiply_regular((8.2, ... | fa7d3b43064f612bed48c0d8d9ba01b2b91f9401 | 585,477 |
import math
def to_decibel(value, limit=-70):
"""
Convert a ratio to decibels. This method will never return less than the
specified limit (default -70dB). If value is zero or negative, the limit
will be returned as well.
"""
if value > 0:
db = 10 * math.log10(value)
if db >= l... | 8d32f16fa9f70ead928562d6b8237fc5164e2112 | 585,480 |
def min_node(tree):
"""
Return the minimum node of the tree or raise a ValueError
if the tree is empty.
"""
if tree is None:
raise ValueError("Can't take min of empty tree")
if tree.left:
return min_node(tree.left)
return tree | 63a06cf50edb036d06c40c7801d4f4dfea1641b2 | 585,490 |
def byte_pad(data: bytes, block_size: int) -> bytes:
"""Pad data with 0x00 until its length is a multiple of block_size."""
if remainder := len(data) % block_size:
return data + bytes(block_size - remainder)
return data | d9ff4bab9d98c2027f9b4db57ce7dcf2274009c6 | 585,491 |
def init_farthest_distance(far_mat, dist_mat, s):
"""initialize matrix to keep track of distance from set
Parameters:
------------------
far_mat : python list length = dist_mat.shape[0]
the minimum distance from solution set to all the points
dist_mat : numpy.array (n, n)
distanc... | 8f87b8c27df203154fcafdc283e6767d5a5e14df | 585,492 |
def get_integer(byte_str):
"""
Get a integer from byte string
:param byte_str: byte string
:return: byte string, integer
"""
integer = int.from_bytes(byte_str[:4], byteorder="little")
byte_str = byte_str[4:]
return byte_str, integer | a95ae51dc8666eb215069ae28cfe14aa3d7fe5c1 | 585,499 |
import requests
def get_token(code, token_service, client_id, client_secret, redirect_uri,
grant_type):
"""Fetches an OAuth 2 token."""
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': grant_type,... | b75e647bd5af263d423ca8844742851a6cd08088 | 585,500 |
def tidy_dataframe(df, column, sep='|'):
"""
Given a dataframe with a delimiter-separated string, create a new dataframe
with separate rows for each value in each corresponding string.
E.g.::
gene score
0 g1|g2 1
1 g3 5
2 g4|g5|g6 9
... | ab72e3cde468a7225b38fe09a884c220d9a17d35 | 585,509 |
def tag_clean(n):
"""Get tagname without prefix"""
if n[0] in u"-~!": return n[1:]
return n | 493d7c69dcc5cd55a0d1d5f041b855fcc42698ae | 585,511 |
def restrict_common_genes(X1, X2, genes1, genes2):
"""
Given two expression matrices and two lists of gene
identifiers corresponding to the two columns of the
matrices, re-configure the matrices to keep only
columns for genes that are common between the two
datasets.
"""
gene_to_index1 =... | b2b6cdf55d817313d713a0f9f7ead6b8ab54b6e3 | 585,512 |
def _AddDSATargeting(client, ad_group_id, label_name):
"""Set custom targeting for the page feed URLs based on a list of labels.
Args:
client: an AdWordsClient instance.
ad_group_id: a str AdGroup ID.
label_name: a str label name.
Returns:
A suds.sudsobject.Object representing the newly created ... | b5fd49fefddd603de4f7a7217ecc70bb35624ac1 | 585,513 |
def unpack_hashtags(hashtag_list):
"""Takes a list of hashtags and adds a "#" before and a space after each"""
hashtags = ""
for tag in hashtag_list:
hashtags += "#%s " % tag
return hashtags | 67ca762829b80865befa901e0679e64bacf190ae | 585,514 |
def normalize_float(v: float, lower_bound: float, upper_bound: float) -> float:
"""Normalizes ``v`` between ``lower_bound`` and ``upper_bound``
Assumes (and will not check) that `lower_bound <= v <= upper_bound`
:param v: the value to be normalized
:param lower_bound: the supposedly lowest possible va... | ebe675a4acab4c1cfbd2aca9e4dc61cfa3ad20ea | 585,518 |
def escape_latex(value):
"""Escape a value for Latex
"""
value = value.replace('\\', '\\textbackslash{}')
value = value.replace('{', '\\{')
value = value.replace('}', '\\}')
value = value.replace('#', '\\#')
value = value.replace('$', '\\$')
value = value.replace('%', '\\%')
value = ... | a33a8d197d7ac437f8b045c136bfe127487f3d57 | 585,520 |
def split_table(table_name):
"""Split a fully-qualified table name into schema and table
Args:
table_name (string) A table name, either with or without a schema prefix
Returns: (tuple) of schema and table name
"""
table_parts = table_name.split(".")
if len(table_parts) == 2:
re... | 71bb15ddbae85867ae90fcd7dd2878fc43e43d78 | 585,522 |
import wave
def get_wav_properties(wav_path):
"""
Reads sampling rate and duration of an WAV audio file
:param wav_path: path to the WAV file
:return: sampling rate in Hz, duration in seconds
"""
with wave.open(wav_path, "rb") as wave_file:
fs = wave_file.getframerate()
duratio... | 2035f9249e91f0693d962356bba7e6233f736cf5 | 585,529 |
import copy
def uniform_crossover(random, mom, dad, args):
"""Return the offspring of the uniform crossover on the candidate.
Based on two candidates (parents) build 2 children:
- elements present in both parents will be present in both children;
- both children have at least one element;
- elemen... | 5a0bfa295684deedaf8825bbd51d9bd76ae2fbe4 | 585,534 |
def encode_intent(encoded_account_identifier: str, currency_code: str, amount: int) -> str:
"""
Encode account identifier string(encoded), currency code and amount into
Diem intent identifier (https://dip.diem.com/dip-5/)
"""
return "diem://%s?c=%s&am=%d" % (encoded_account_identifier, currency_cod... | a132e2026dbced05d192e30a652518a48d87b4c7 | 585,539 |
def get_characteristic(input: str | list[str]) -> str:
"""Return the unique, sorted characters in the string."""
return "".join(sorted(set(input))) | 36039bfe0c2fb980cf0275343510acde13c50daa | 585,541 |
import math
def cos(theNumber):
"""Returns math.cos(theNumber)."""
return math.cos(theNumber) | eeb6c952c74c785926fff536366ab12d8a3bd29c | 585,543 |
def trim_all_columns(df):
"""
Trim whitespace from ends of each value across all series in dataframe
"""
trim_strings = lambda x: x.strip() if isinstance(x, str) else x
return df.applymap(trim_strings) | a9ee15ef88e2732b831310679e713d801d84b74b | 585,544 |
def parametrized(decorator):
"""
Helper meta-decorator that allows us to provide parameters to a decorator.
:param decorator: The decorator that should accept parameters.
"""
def inner(*args, **kwargs):
def g(f):
return decorator(f, *args, **kwargs)
return g
return ... | abe7ac9ce7c2c4b18b8fb3962402fc1a23f1f98b | 585,545 |
def tiddlytag(tg):
"""Format the tags for tiddlywiki5;
when the tag includes white space, it is surrounded by '[[' ']]'.
:param str tg: A tag.
:return: Decorated tag.
"""
if ' ' in tg:
return '[[' + tg + ']]'
else:
return tg | ee0316fc7e008641301ed70af5a72298abada7dc | 585,546 |
def compute_min_max_variances(variances, n_variances=10):
"""
Compute the indexes with highest and lowest variances
"""
max_variances = variances.argsort()[-n_variances:][::-1]
min_variances = variances.argsort()[:n_variances]
return max_variances, min_variances | 70ad4ee37c3a6ec4fe3dd190d58e91f041d385dc | 585,550 |
import math
def CalcSpeedOfSound(T, Rh=50, P=101.325):
"""Compute the speed of sound
T: temperature in degees C
Rh: relative humidity in % (default 50)
P: pressure in kPa (default 101.325)
adapted from:
http://resource.npl.co.uk/acoustics/techguides/speedair/
"This calculation ... | 7c6dd634b9fd9b0b1802c2bd9a1a688c9a26e52a | 585,554 |
import urllib3
import certifi
def post_json(ctx, path, json):
"""
Make a POST request with a JSON payload to be sent to a NuvIoT endpoint.
Parameters
----------
ctx:
Context Object that defines how this method should call the server to include authentication.
path:
Path u... | a6c1f49ce04d4f129d5fc8d180c2e460bbc825ac | 585,558 |
def int_to_vlq(val):
"""
Converts an integer value into a variable length quantity (list).
"""
vlq = []
for i in range(21, 0, -7):
if val >= (1 << i):
vlq.append(((val >> i) & 0x7F) | 0x80)
vlq.append(val & 0x7F)
return vlq | 0e8dd5affb8084109d34751c3151aeaeacac1314 | 585,564 |
def reverse_wave(lst):
"""
Reverse list of lists
:param lst: list of lists
:return: reversed list
"""
return lst[::-1] | 76116a8f74a4468a5eb6adfdd01898ce117464ef | 585,566 |
import select
def more_data(pipe_out):
"""Check if there is more data left on the pipe
:param pipe_out: The os pipe_out
:rtype: bool
"""
r, _, _ = select.select([pipe_out], [], [], 0)
return bool(r) | ae90ca3e560db3b31eed043890e671b1f2528f44 | 585,567 |
def overflow_format(num, overflow):
"""
Returns string of the given integer. If the integer is large than given overflow, '{overflow}+' is returned
:param num: int
:param overflow: int
:return: str
"""
if not isinstance(num, int):
raise ValueError('Input argument "num" should be int... | acd065dd667e9744dd45b0e641f17468a3c7876e | 585,570 |
import urllib.request as ur
def uniprot2seq(ProteinID):
"""Get protein sequence from Uniprot ID
Parameters
----------
ProteinID : str
Uniprot ID
Returns
-------
str
Amino acid sequence of input uniprot ID
"""
ID = str(ProteinID)
localfile = ur.urlopen('http://www.uniprot.org/uniprot/' + ID + ... | e29d3707c1a9c91844fd020d834ea04a1e3b9fcb | 585,571 |
from typing import Any
def _get_log_name(var: Any) -> str:
"""Return var.__name__ if available, 'this object' otherwise."""
try:
return str(var.__name__)
except AttributeError:
return 'this object' | d66a5f9dfeedc77f5e6bef2630379124f69e7676 | 585,572 |
from typing import Sequence
def format_hex(in_bytes: bytes) -> Sequence[str]:
"""
format an input sequence of bytes into a ordered form with lines of
8 hex-formatted bytes prefixed by the address of the first byte in the line.
:param in_bytes: the bytes to format
:return: a list of formatted line... | 8e2ab48e15ff511a787fbd2bf3d0f7e15cd6738e | 585,573 |
def camel_to_snake(word: str, depublicize: bool = False):
"""Convert came case to snake case."""
word = "".join(["_" + i.lower() if i.isupper() else i for i in word])
if not depublicize:
word = word.lstrip("_")
return word | 7e942c127e43fab98afa538217dec1562bfcb228 | 585,574 |
def reverse(s: str) -> str:
"""Reverses the string provided.
Example:
"Abcd" returns "dcbA".
"""
return s[::-1] | 96825cadf994b5c5c339fb7fb3b74faa5d316426 | 585,576 |
def get_threshold_from_DESC(desc_file):
"""
Parses a family DESC file and returns the gathering
threshold
desc_file: The path to a valid Rfam family DESC file
return: A string which is the corresponding gathering threshold
"""
threshold = 0
desc_fp = open(desc_file, 'r')
for lin... | b7883d3f8921fee8ac77ce3f8ba34987733b5bf6 | 585,577 |
def downcase(val: str) -> str:
"""Make all characters in a string lower case."""
return val.lower() | 2d546ef4a81c554b000384cd06d1b8eefe9f57e3 | 585,578 |
import itertools
def take(iterable, n):
"""Return first n items of the iterable as a list."""
return list(itertools.islice(iterable, n)) | dd8b9681707b6abb0b2974e383d053ec9011af88 | 585,582 |
from datetime import datetime
def data_schema(key, value, url, url_certificado):
"""
Final data schema
input:
key: string
value: string
url: string
url_certificado: string
return: dict
"""
return {
"key": key,
"value": value,
"ur... | 70481369dd57281f693499e95c728d87a4615416 | 585,583 |
def _is_number(val):
"""
Determine if the value is a number
:param val:
:return:
"""
if isinstance(val, list):
for v in val:
if not _is_number(v):
return False
return True
return isinstance(val, int) or isinstance(val, float) | 20dd44802ec2ff9d655bc9746e35e5ffda9c09b7 | 585,584 |
def binary_search_iterative(array, target):
"""
Search target element in the given array by iterative binary search
- Worst-case space complexity: O(1)
- Worst-case performance: O(log n)
:param array: given array
:type array: list
:param target: target element to search
:type target: A... | 0cca6c4344e384b058408e935c663409b0f78b00 | 585,589 |
def _make_headermap_input_file(namespace, hdrs, flatten_headers):
"""Create a string representing the mappings from headers to their
namespaced include versions. The format is
virtual_header_path|real_header_path
Note the separator is a pipe character.
:param namespace: 'foo' in #include <foo/bar... | a23f542abe63779cf88138097c2ef5ee4de57987 | 585,591 |
import base64
def file_to_attachment(filename, filehandler=None):
"""
Convert a file to attachment
"""
if filehandler:
return {'_name': filename,
'content': base64.b64encode(filehandler.read())
}
with open(filename, 'rb') as _file:
return {'_name': filename,... | 022ad346cf3a0e4a8d25193f19ab565ea16b504c | 585,595 |
def var_shape(tensor):
"""Get TensorFlow Tensor shape.
Parameters
----------
tensor : tf.Tensor
the input tensor
Returns
-------
list of int
the shape
"""
out = tensor.get_shape().as_list()
assert all(isinstance(a, int) for a in out), \
"shape function a... | ce2ea5c8361b31547429d702679bb1434eba6717 | 585,599 |
def _get_shape_as_list(tensor):
"""Replaces None with -1 in the tensor shape list representation."""
shape = tensor.get_shape().as_list()
for i, v in enumerate(shape):
if v is None:
shape[i] = -1
return shape | 2e70ecb0cd044ee8cf49a61e9214a2e2a72a3799 | 585,600 |
def convert_extension(filename, extensions=('yaml', 'yml',)):
"""
Convert YeT extension in filename to .tex
:param filename: string of file name. validity not checked.
:param extensions: tuple of extensions (without dot) to treat as YeT
"""
# change YAML extension to .tex
if '.' in filename... | 0d254547332b7ada0939fcee0ce2825be12ac8e2 | 585,605 |
def handle_aligns(aligns):
"""Converts comma delimited string of alignments to tuple
Arguments:
aligns: comma delimited string of 'l', 'r', 'c' or empty string
Returns:
aligns_tuple: tuple of alignments or None
"""
if not aligns:
aligns_tuple = None
else:
aligns_... | 892adca706e338e4cad39c570c73612f9e775640 | 585,612 |
import re
def get_rx(regex, body):
""" Return first result of regular expression 'regex' in 'body' """
results = re.compile(regex).findall(body)
if not results:
return False
return results[0] | bce8caa48454648c43fcb57a29c992e1ff204045 | 585,614 |
import time
def song_to_starred_time_struct(song):
""" Take a song, return the starred date in the form of a time module 9-tuple. """
try:
return time.strptime(song.get('starred', ''), '%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
return time.gmtime(0) | b821e81db2de630129c020df08cfe0e965d26e7b | 585,617 |
import re
def match_date(date):
"""Check if a string is a valid date
Args:
date(str)
Returns:
bool
"""
date_pattern = re.compile("^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])")
if re.match(date_pattern, date):
return True
return False | 1fc47008be214bc0f470ea8863a11eaf0f1fe0b2 | 585,618 |
def line_indices(lines, tag):
"""
:param lines: Must be a list of strings representing each line
:param tag: is the tag to find in the list of lines
:return: the indices of the lines with that tag
"""
return [l for l in range(len(lines)) if tag in lines[l]] | 353c4cc85b0e911dfc8686bcac073b5a6bc82b24 | 585,623 |
def _lstrip(text: str, chars: str) -> str:
"""
Given a string `text`, remove the leading `chars` if and only if they
appear as the leading characters
"""
if chars and text[:len(chars)] == chars:
text = text[len(chars):]
return text | f5b60619de70ed56b12aedf5e1d59ab0262d53b8 | 585,625 |
def safe_index(alist, elem):
"""
Return index of element e in list l. If e is not present, return the last index
"""
try:
return alist.index(elem)
except ValueError:
return len(alist) - 1 | 7cbec85802f36109bd84459a0a22f91a57639aa0 | 585,627 |
def get_mitigations(df, threshold=0.5):
"""Return number of impact mitigations performed."""
return df[(df['y_prob_1'] > threshold)] \
.groupby(level=['date_time', 'id_blade']) \
.size() \
.size | 6105a76cd30b65c319525f53ba2850dffc70e8d4 | 585,628 |
import curses
def hline_after(prev_win, xstart=0):
"""
Create a new window on the next row after prev_win.
The new window will be for a horizontal line and hence
only needs to be 1 line high.
To underline the previous window it is 2 cols wider than the pre_win
:param prev_win: curses.win
:... | 91b2ef3ffc310097e5b1e885afaa7f681afe7247 | 585,629 |
import re
def get_largest_blocks(blocking_rule, df, spark, limit=5):
"""
For a given blocking rule, find out which will be the largest blocks
"""
parts = re.split(" |=", blocking_rule)
parts = [p for p in parts if "l." in p]
parts = [p.replace("l.", "") for p in parts]
col_expr = ", ".jo... | 8f0572c0e3c25b92fda456de4dc321a6cbb7d31a | 585,630 |
def problem_3_6(stack):
""" Write a program to sort a stack in ascending order. You should not make
any assumptions about how the stack is implemented. The following are the
only functions that should be used to write this program:
push | pop | peek | isEmpty.
Solution #1: use one more stack.
... | d8c95fb053a4190a1628c48fe4014ca45e962890 | 585,632 |
def get_stride_from_chips(chips):
"""
Stitch up chips into a full array
Parameters
----------
chips : dict
dictionary of partition indices mapping to actual chips
Returns
----------
stride: int
number of pixels skipped over to generate adjacent chips
"""
keys = ... | 82eceb7cbc55d2485c625c1ab2bcec08912ed493 | 585,634 |
def class_as_descriptor(name):
"""Return the JVM descriptor for the class `name`"""
if not name.endswith(';'):
return 'L' + name + ';'
else:
return name | 128c344a73920d32dbbec65afd87cf4733920298 | 585,636 |
def find_opposite_axes(axes, ndim):
"""
Based on the total number of dimensions function
finds all axes that are missed in the specified
list ``axes``.
Parameters
----------
axes : list or tuple
Already known axes.
ndim : int
Total number of dimensions.
Returns
... | 491f340bbbb37da7d9cc58b522424ff85bc547cb | 585,637 |
def comma_code(a_list):
"""
Turns a list into a string of elements separated by commas
:param a_list: a list of strings
:return: a string separated by commas
"""
a_list[-1] = 'and ' + a_list[-1]
stringified = ", ".join(a_list)
return stringified | 8f746b2afa349df6752f4feea82bf672a30de5ed | 585,640 |
def feature_to_geojson(json_data: dict) -> dict:
"""
Converts feature into a GeoJSON, returns output
From::
>>> {'geometry': {'type': 'Point', 'coordinates': [30.003755665554, 30.985948744314]},
... 'id':'506566177256016'}
To::
>>> {'type': 'FeatureCollection', 'features': [{... | 97353f207678e5325313abaf141b06038c8c1eee | 585,641 |
def filter_example(ex, use_src_len=True, use_mt_len=True,
use_pe_len=True,
min_src_len=1, max_src_len=float('inf'),
min_mt_len=1, max_mt_len=float("inf"),
min_pe_len=1, max_pe_len=float("inf")):
"""Return whether an example is an acceptable... | bbec0e3b3e4e13485eea698bc7a6a9e726ffbd78 | 585,646 |
def is_py_file(file_name: str) -> bool:
"""
Return whether a file is a python file.
"""
return file_name.endswith(".py") | 19bd902906953d1925a1018e270e81fecb923fd6 | 585,647 |
def join_string(part1, part2, concatenation_string = 'AND', seperator=' '):
"""
Join two strings together using a concatenation string
Handles the case where either part1 or part2 are an empty string
@param part1: First string
@param part2: Second string
@param concatenation_string: String use... | 123ddd5756f972f635a175c2a1948897ae74bdd8 | 585,648 |
def merge_two_dicts(dict_x, dict_y):
"""
Given two dicts, merge them into a new dict.
Uses a shallow copy.
"""
new_dict = dict_x.copy()
new_dict.update(dict_y)
return new_dict | 5154aa0fe81093b4bb92212639d6211a6f050d7f | 585,650 |
def swap_dict(old_dict):
"""Returns a new dictionary in wich the keys are all the values of the old
dictionary and the values are lists of keys that had that value.
Example:
d = { 'a':['c','v','b'], 's':['c','v','d']}
swap_dict(d) -> {'c': ['a', 's'], 'b': ['a'], 'd': ['s'], 'v': ['a', 's']}
... | 99864d25ba6d60072ed9fbbeaf80092867d49baa | 585,652 |
def brzycki(w, r):
"""
Realistic for low reps. Conservative for high reps.
1RM estimate based on weight and reps of a set.
"""
return w * 36 / (37 - r) | 70169739da514c29185554b3f8bda76a6b5b17f6 | 585,653 |
def _get_author_weight(authors_in_paper):
""" Method that returns the weight of a single author in a paper"""
#I check if there is at least 1 author otherwise the weight is 0
if len(authors_in_paper) > 0:
return 1./len(authors_in_paper)
else:
return 0 | 7cf7c723572cd48e26672bcffb7916d044e4ee97 | 585,657 |
def last_but_one_word(string):
"""Function to get the last but one word of a sentence in lower case"""
try: return (string.rsplit(None, 2)[-2]).lower()
except: return None | b7e230ab1c598166939d05436479582b331125bc | 585,658 |
def summation(numbers):
"""
Summation of a list of numbers
Args:
numbers: int, float
Returns: sum of numbers, int, float
"""
return sum(numbers) | eea70962253624e3526af61037a811a03d3c047b | 585,662 |
def sorted_squares_brute_force(nums: list[int]) -> list[int]:
"""Returns a (non-decreasing) sorted array of the squares of each element in nums
Naively squares each element and sorts the array
Complexity:
n = len(nums)
Time: O(nlogn)
Space: O(n) (for the sorted array)
N... | fca0b2dc89ea7b575d1e5a55be5bc56b3ba9a0d5 | 585,672 |
import torch
def brownian_motion_sample(num_steps, num_samples, dim, t, init_point, model):
"""Returns the points of a discretized Brownian motion (BM)
on a manifold (a.k.a. latent space).
params:
num_steps: int - the number of time steps for which
the BM will run
... | 479ec3f77747ddbea74ff51b51fdd432ca83422c | 585,673 |
def fibonacci(end=None, start=0, inclusive=True, length=None):
"""This function returns a Fibonacci series list:
- either upto an end number
- or with a length argument which defines the length of the list
start number is default to 0 and optinal to change for both.
All items in the returnin... | e44bfa7f0ce96c2fbcffd34b5f3628be81fd2ccc | 585,675 |
def afficher_graine(graine):
"""
Formate un texte avec la graine donnée ou ne donner rien si cette dernière est None
:param graine: La graine à afficher
:return: Un texte sous la forme ". Graine aléatoire: <graine>" si seed différent de None sinon ""
"""
if graine is None:
return ""
... | 375db45a6447b747cf616daba6521206cb058259 | 585,677 |
def invert_items(df):
"""This function inverts the scale of some items of LoC so that for all
items higher numbers reflect greater feelings of control."""
inverted_items = [
"LOC_ACHIEVED_DESERVE",
"LOC_LUCK",
"LOC_OTHERS",
"LOC_DOUBT",
"LOC_POSSIBILITIES",
"L... | b69e02a20fdcf2329996f52d9c5ae8ace419ac78 | 585,678 |
def _all_close(values, other_value, threshold):
"""Return true if all values are within threshold distance of other_value."""
for value in values:
if abs(value - other_value) > threshold:
return False
return True | 1f8e8d0532cdf3615f95ff5b63e3597473d0bb43 | 585,683 |
def key_value(tree):
"""Returns the key value of given tree"""
return tree[1] | 753bb9502bb87b07adbf56b2ad415886d084c85d | 585,685 |
import re
def unmangle_columns(columns: list[str]) -> list[str]:
"""Utility function to convert "X.1...X.N" into "X...X", reversing the normal column name mangle
ref: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
:param columns: Original mangled column names
:type columns: list[st... | 2378ea60ce62aece4bebc4c056817464b1bc1eef | 585,686 |
def is_id_selector(selector):
"""
A basic method to determine whether a ID selector or not
"""
if ":id" in selector:
return True
return False | e9588de5ac2113bda7271af283c1a31f2a620766 | 585,688 |
from datetime import datetime
def convert_to_milliseconds(date_time: datetime) -> int:
"""takes datetime and returns milliseconds"""
return round(date_time.timestamp() * 1000) | 068b74617a7294888e21b5640bdf6c31099076d7 | 585,691 |
from typing import List
import warnings
def get_expression_blocks(expression: str) -> List[str]:
"""Split expression in blocks.
Args:
expression (str): band math/combination expression.
Returns:
list: expression blocks (str).
Examples:
>>> parse_expression("b1/b2,b2+b1")
... | eb0d6a1aa17409b51a7663f66791ed6941ebfa2b | 585,692 |
def has_flag(flag, content):
"""Determines if a command's content contains a flag.
Arguments:
flag -- the flag for which to search
content -- the content of the command
"""
return "-" + flag in content.split() | c0fba18fa6a9da448228f3e441b31247dd705720 | 585,693 |
def greeting(name: str = 'World') -> str:
"""Returns greeting message."""
return f'Hello {name}' | 74914a0c07438c661487c478ab3d70a3611e32e9 | 585,694 |
def extrapolate_wind_speed(height_in, height_out, wind_speed):
"""
:param height_in: m, Height data was recorded at
:param height_out: m, Height desired
:param wind_speed: m/s, Array of wind speeds recorded at height_in
:return:
"""
shear_exponent = .144444
extrapolated_wind_speed = [x ... | 09fa85fa019a068fede495258baf33593acc18c3 | 585,695 |
def get_report(analytics, query):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(body=query).execute() | 543a234c60325de26fc5d05bbf474ef8b9f75b39 | 585,696 |
def deprel(args, premise):
"""Return dependency relation to head."""
return args[0].deprel | 467e07e49cde19774c8c63de21aa8f722ff44333 | 585,697 |
def getCisDist(df):
"""Calcualtes percentage of reads at certain distance"""
result = {}
for dist in [
"cis_1kb+",
"cis_2kb+",
"cis_4kb+",
"cis_10kb+",
"cis_20kb+",
"cis_40kb+",
]:
result[dist] = (
df.loc[df[0] == dist, 1].values[0]
... | 419fa2b5239a26564900c590ba56ca52c3355134 | 585,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.