content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def make_slow_waves(events, data, time, s_freq):
"""Create dict for each slow wave, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 5 matrix with start, trough, zero, peak, end samples
data : ndarray (dtype='float')
vector with the data
t... | eb84b4cc4d4024246905597be68d8dc170c9aeeb | 403,498 |
def totalcost(endclasses):
"""
Tabulates the total expected cost of given endlcasses from a run.
Parameters
----------
endclasses : dict
Dictionary of end-state classifications with 'expected cost' attributes
Returns
-------
totalcost : Float
The total expected cost of ... | 0ddffda6ee537d9f5159ad722ffb4925df39e035 | 570,142 |
import collections
def compute_f1_single(prediction, ground_truth):
"""Computes F1 score for a single prediction/ground_truth pair.
This function computes the token-level intersection between the predicted and
ground-truth answers, consistent with the SQuAD evaluation script.
This is different from another ... | 5fd82efdcd128fab3b4f40704b9f229348551828 | 332,611 |
import random
def subsample(samples, labels, target_size):
"""subsample a dataset"""
resized = random.sample(list(zip(samples, labels)), target_size)
return zip(*resized) | 221d7548cc00c5df61216788c9b5fe104b94e7c8 | 560,769 |
import torch
def tensor_dot(x, y):
"""Performs a tensor dot product."""
res = torch.einsum("ij,kj->ik", (x, y))
return res | 987198ddb5a851c01ec31ab6bfeaf7c3dac133af | 84,640 |
import math
def norm(p0,p1):
"""Calculate norm_2 distance between two points"""
return math.sqrt((p1[0]-p0[0]) ** 2 + (p1[1]-p0[1]) ** 2) | e22c01b52114c1989bdeda66909e84381d9d4d93 | 477,630 |
def has_fusion(args):
"""Returns whether some kind of Fusion reference is given
"""
return args.fusion or args.fusions or \
args.fusion_tag | 08377f211dbd48c404ef0488089a9b2923ee296e | 102,029 |
def read(fname, mode = "r"):
"""Read content from a given file.
Args:
fname (str, Path): The path to the file.
mode (str): File mode while opening. Defaults to "r".
Returns:
[type]: The content within the file.
Example
>>> bpy.read("path/to/file")
'Hello, Worl... | fb46f57e59a3e4580e8d8801df6c4ebb93af0357 | 328,574 |
def add_end_slash(url: str):
"""Add final slash to url."""
if not url.endswith("/"):
return url + "/"
return url | 82301f238ba8692ac210e3a310e461499b824e57 | 438,592 |
def is_leap(year,print_=False):
""" returns true if year is leap year, otherwise returns False and prints the output per assignment of print_"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
if print_: print("Leap year")
return True
el... | f68111ae533e1cca3561f2517755e1d75728aa6a | 460,699 |
from pathlib import Path
def sim_top_build(pytestconfig):
"""Return path to Verilator sim model."""
path = Path(pytestconfig.getoption('verilator_model')).resolve()
assert path.is_file()
return path | bae5fc842ebb9c734e72fdfa1616ac0727dd5721 | 333,939 |
def _colors(strKey):
"""
Function gives access to the RxCS console colors dictionary. The
Function returns a proper console color formating string (ANSI colors)
based on the key given to the function. |br|
Available keys:
'PURPLE'
'BLUE'
'GREEN'
'YELLOW'
'RE... | 90f09148ac709299d1666930e7c675595d04663f | 681,689 |
def rebin(arr, new_shape):
"""
Rebin 2D array arr to shape new_shape by averaging.
inputs:
arr: numpy array to reduce at the size new_shape
new_shape: tuple of the wanted size as (width, height)
output:
numpy array of the reduced arr
from https://scipython.com/blog/binning-a-2d-array-... | 05149c7d364e3e138d0e3c623d1d28cc26cf3416 | 372,163 |
def prefix(name):
"""Returns a rule that matches symbols that start with `name`."""
def rule(symbol):
return symbol.startswith(name) or None
return rule | 26c351ef9d9dacb2ae4d01350354235cded0db44 | 367,514 |
def measurement_with_tools(measurement, tmpdir):
"""Create a measurement with all dummy tools attached.
"""
measurement.add_tool('pre-hook', 'dummy')
measurement.add_tool('post-hook', 'dummy')
measurement.add_tool('monitor', 'dummy')
measurement.root_task.default_path = str(tmpdir)
return m... | 78d52cad9cf1faab36ec057f3622366a3b71e0a5 | 348,418 |
import requests
def send_image(chat_id, token, image_url):
"""Send message to Telegram BOT
Args:
chat_id (int): chat_id number: -111111
token [str]: Token to HTTP API: 11111111:AAAAAAAAA
image_url (str): Image url
Returns:
str : Response Status Code
"""
data = {'c... | 692ea6e30f8f135fff3ced180f568feee56b022e | 205,753 |
import re
def get_pos(pattern, string):
"""Get start position for each pattern match in string
"""
return set(m.start() for m in re.finditer(pattern, string)) | afd4f49e224ff842835be4d5382aae72e2b083c9 | 209,423 |
import re
def clean(text):
"""
Cleans text, removes excess tabs, CRs, spaces
:param text: raw text string
:return: clean text string
"""
text = re.sub('\s*\n\s*', '\n', text)
text = re.sub('[ \t]{2,}', ' ', text)
return text.strip() | 57475bb5e2955d33cdefa7ba593413affa3293e2 | 586,773 |
import threading
def run_on_another_thread(function):
"""
This decorator will run the decorated function in another thread, starting it immediately.
:param function:
:return:
"""
def f(*args, **kargs):
threading.Thread(target=function, args=[*args, *kargs]).start()
return f | f539b508d70d0cd24c9fa27d59090de8f6a9f8cd | 398,550 |
def chr22XY(c):
"""Reformats chromosome to be of the form Chr1, ..., Chr22, ChrX, ChrY, etc.
Args:
c (str or int): A chromosome.
Returns:
str: The reformatted chromosome.
Examples:
>>> chr22XY('1')
'chr1'
>>> chr22XY(1)
'chr1'
>>> c... | 13677f728ce8221e9a6966951353deba703f3294 | 702,021 |
def convert_string_AE2BE(string, AE_to_BE):
"""convert a text from American English to British English
Parameters
----------
string: str
text to convert
Returns
-------
str
new text in British English
"""
string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() e... | b032b007ad59ef653733e01b3c7b43de5d2a956a | 663,916 |
def createMysqlEscapeList(num):
"""Create a string with a list of %s for escaping."""
esc_str = ''
for i in range(num):
esc_str += '%s, '
return esc_str.rstrip(', ') | 00ea775c31e38365a1d8d14e37f72be0ebd9fdf8 | 262,777 |
def prepare_numbers(numbers):
"""Prepares the numbers for the chatbot to interpret.
Parameters
----------
numbers : list
Numbers that the user has input into the chatbot
Returns
-------
numb : list
List of integers that the chatbot can use to put into the calcul... | 3f60538c993e2f544e25ca3b6a988856585284fb | 111,636 |
def top_row(matrix):
"""
Return the first (top) row of a matrix.
Returns a tuple (immutable).
"""
return tuple(matrix[0]) | c41968ccef372ee609911640650541b99921aa43 | 457,095 |
def generate_report(data):
""" Process the property data from the web page, build summary dictionary containing:
* 'property_name' - Name of property
* 'property_type' - Type of property e.g. 'Apartment'
* 'room_type' - Type or number of bedrooms
* 'room_number' - Number of bedrooms
* 'ba... | 92d178f8fe2ec4e11433837440a454bf2b8d4e67 | 558,165 |
def GetParentFromFlags(args, is_list_api, is_insight_api):
"""Parsing args to get full url string.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
is_list_api: Boolean value specifying whether this is a list api, if not
append recommendation id or insig... | 1df2b6bfc23e74277339a545cfaf131053c22dcb | 287,939 |
from typing import List
def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List:
"""
This is a mock function for random.choice(). It generates a deterministic sequence of the
candidates, each one with frequency weights[i] (count: int(len(candidates) * k). If the
sum of total ... | c60aebb59aeb299e6e36b9b7ed24a0fe6e0882b3 | 654,177 |
def patch_grype_wrapper_singleton(monkeypatch, test_grype_wrapper_singleton):
"""
This fixture returns a parameterized callback that patches the calls to get a new grype wrapper singleton
at that path to instead return the clean, populated instance created by test_grype_wrapper_singleton.
"""
def _... | f95f45f80a8af1a71f1f8ee1ef55162b63ddc9af | 38,656 |
import asyncio
def singleton(func):
"""
A decorator that ensures only one instance of a coroutine is running at any time.
"""
func.lock = asyncio.Lock()
async def func_wrapper(self, *args, **kwargs):
if func.lock.locked():
return
async with func.lock:
awai... | ddede0b30fe5c05b5213135c24029b90f35c580d | 471,701 |
def establish_relevant_columns(df):
"""
Creates a dataframe with columns that are useful for month/year pivoting.
:type df: pd.DataFrame
:param
df: A pd.DataFrame object that has exactly two columns: 'Date' containing DateTime values, and 'Miles' containing floats.
:return
A pd.DataFrame i... | dfebafeb5bad6e4815ec44040f1acf6ad0340ea3 | 163,157 |
def get_sum(list):
"""Calc the sum of values from a list of numbers
Args:
list: The list from where the calc will be done
Returns:
Return the sum of values from a list of numbers
"""
sum = 0
for value in list:
sum += value
return sum | 1d5e588993da40ff9f04e3f1cb5a5214c1b686bd | 571,095 |
def split_labels(data, label_idx=-1):
"""
Split labels from numerical data
:param data: array of inputs data
:type data: nd.array
:param label_idx: index where label is located in the array. It can be only at start of at the end of the array
:type label_idx: int
:return: data without labels... | d3b59dca790255ae14269836ace58df151f84684 | 25,890 |
def shift2d(x,w,a,b):
"""Shift a 2d quadrature rule to the box defined by the tuples a and b"""
xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]]
ws=w*(b[0]-a[0])*(b[1]-a[1])
return xs,ws | 84c2090cc0e1689a79aa2c7fa40fb399bc03f535 | 699,329 |
import re
def get_fig_name(title, tag, legends=[]):
"""Get the name of the figure with the title and tag."""
fig_name = "_".join(re.split("/|-|_|,", title) + legends).replace(" ", "")
return f"{fig_name}_generalization_{tag}.pdf" | a1bb5c3d91eba412ffaca7354b5d663c37de0a46 | 653,975 |
def lt(y):
"""lt(y)(x) = x < y
>>> list(filter(lt(3), [1,2,3,4,5]))
[1, 2]
"""
return lambda x : x < y | a98e87097e0518b30c456d380509551f7516f1d6 | 69,892 |
def client(app):
"""Creates a flask.Flask test_client object
:app: fixture that provided the flask.Flask app
:returns: flask.Flask test_client object
"""
return app.test_client() | 1041652fc1c84cfd81a92f09d09980dc2333f858 | 154,448 |
def matches(case, rule):
"""Match a test case against a rule
return '1' if there's a match, 0 otherwise
"""
if len(case) != len(rule):
return 0
match = 1
for i in range(len(case)):
if rule[i] != "*" and case[i] != rule[i]:
match = 0
break
return match | 354ac866c49c0bcc7d0a9be10a8585ed67e4cb1b | 171,778 |
def set_name_from_dict(string, dictionary, key, leading, trailing):
"""Replaces the string with the value from a specified dictionary key,
prepending and appending the leading/trailing text as applicable"""
return "{}{}{}".format(leading,
dictionary[key],
... | 4641822ccca293b59a39f666fd715329d884c529 | 659,585 |
from typing import List
def generate_def(functions: List[str], dll_name: str) -> str:
"""Generate .def file defining provided functions
Args:
functions: list of functions to define
dll_name: name for LIBRARY
Returns:
string containing a .def file that defines and exports those fu... | b859772b4af34b00cb1bcecee36bc7811cf8d42d | 499,737 |
def get_next_line(fin):
"""return the next, non-blank line, with comments stripped"""
line = fin.readline()
pos = line.find("#")
while (pos == 0 or line.strip() == "") and line:
line = fin.readline()
pos = line.find("#")
return line[:pos] | 23ca167db675916e0f2bf007a9204237176ca022 | 506,171 |
def pascal_case(str):
"""convert string to pascal case"""
return ''.join(x for x in str.replace('_', ' ').title() if not x.isspace()) | 68d6a2ca288d2243801107c52de70fda465b8604 | 542,690 |
def get_stream_id_for_topic(topic_name, rng=2):
"""To distribute load, all the topics are not in the same stream. Each topic named is hashed
to obtain an id which is in turn the name of the stream.
This uses the djb2 algorithm, as described here
https://mapr.com/docs/60/AdministratorGuide/spyglass-on-st... | f2d462a0985d9e8c24f02800ba3f72d77bbae344 | 512,874 |
import requests
def is_responsive_404(url):
"""
Hit a non existing url, expect a 404. Used to check the service is up as a fixture.
:param url:
:return:
"""
try:
response = requests.get(url)
if response.status_code == 404:
return True
except ConnectionError:
... | 46a5f869d4e86accaa07dc186e1fe758a49ab312 | 111,384 |
def regex_match_lines(regex, lines):
"""
Performs a regex search on each line and returns a list of matched groups
and a list of lines which didn't match.
:param regex regex: String to be split and stripped
:param list lines: A list of strings to perform the regex on.
"""
matches = []
b... | 8553dda253a26919ba41b774d5335ccd018aa2c2 | 516,149 |
import hashlib
import six
import base64
def CalculateMd5Hash(file_path):
"""Calculate base64 encoded md5hash for a local file.
Args:
file_path: the local file path
Returns:
md5hash of the file.
"""
m = hashlib.md5()
with open(file_path, 'rb') as f:
m.update(f.read())
return six.ensure_text(... | 2a24ce3dd4f6e5f9d9a5d9be5632e6d481fd690b | 37,851 |
def validate(metric,
net,
val_data,
batch_fn,
data_source_needs_reset,
dtype,
ctx):
"""
Core validation/testing routine.
Parameters:
----------
metric : EvalMetric
Metric object instance.
net : HybridBlock
... | d816a1f2d2568cbe9ab8f6159be09c63644735b3 | 382,057 |
from typing import Dict
def largest_valued_key(dic: Dict[str, set]) -> str:
"""Find the key with the largest value."""
biggest_size = -1
biggest_key = None
for key, value in dic.items():
length = len(value)
if length > biggest_size:
biggest_size = length
biggest... | 2d4312217b93560514fb717251028baaeee7a6fe | 18,335 |
import typing
def _secret_key(secret_key: typing.Union[bytes, str]) -> bytes:
"""ensure bytes"""
if isinstance(secret_key, str):
return secret_key.encode('latin1')
return secret_key | a8999c5df6a1e9a09659747172e9747ed628f691 | 274,587 |
def my_formatter_2f(x,p):
"""Format tick marks to have 2 significant figures."""
return "%.2f" % (x) | 642a6a612ed25cadc8309dc698671baaa91780b1 | 246,818 |
def has_ways_in_center(tile, tolerance):
"""Return true if the tile has road pixels withing tolerance pixels of the tile center."""
center_x = len(tile) / 2
center_y = len(tile[0]) / 2
for x in range(center_x - tolerance, center_x + tolerance):
for y in range(center_y - tolerance, center_y + tol... | 111520a1959696dfb254e20bc5a7698f8cd3f3f3 | 457,639 |
def vecDistanceSquared(inPtA, inPtB):
"""calculate the square of the distance between two points"""
ddx = inPtA[0] - inPtB[0]
ddy = inPtA[1] - inPtB[1]
ddz = inPtA[2] - inPtB[2]
return ddx*ddx + ddy*ddy + ddz*ddz | dd054e1a2e6fde7d56bd0febd18847c09e900e8c | 617,796 |
from typing import Dict
from typing import Any
def prefix_dict(d: Dict[str, Any], prefix: str):
""" Prefix every key in dict `d` with `prefix`. """
return {f"{prefix}_{k}": v for k, v in d.items()} | ab27c08cf25c19ca2073bb7432692a838d0ada87 | 128,919 |
def parseInput(input):
"""
Converts an input string of integers into an array of integers.
"""
return [int(num) for num in input.split(',')] | 0d29a72c1c19b2703c6f736de5819cd58ab08d4d | 73,725 |
def s2f(s):
""" Convert a string to a float even if it has + and , in it. """
if s == None or s == '':
return None
if type(s) == type(0.0) or type(s) == type(0):
# Already a number
return s
if s:
return float(s.replace(',', ''))
return None | ef8c3ed83dc1440286a346765a6f8a6cbfbadc12 | 346,224 |
import math
def tile_iterator(tile_order, width, height, tile_width, tile_height):
"""
Returns iterator function depending of tile_order.
Also iterator functions has 'len' field which consists number of tiles
:param tile_order: could be 'VERTICAL', 'HORIZONTAL', 'CENTER_SPIRAL'
:param width: rend... | b96591fbe00dce046ab3f1b059023fa90bb877ec | 560,231 |
def return_core_dense_key(core_idx, dense=False):
"""Return core dense keys in the right format."""
if dense is False:
return (core_idx, 0)
else:
return (core_idx, dense) | 4ed9e9fd75d9ec7549d227378f9da8089244a414 | 311,205 |
def bitmap2str(b, n, on='o', off='.'):
""" Generate a length-n string representation of bitmap b """
return '' if n==0 else (on if b&1==1 else off) + bitmap2str(b>>1, n-1, on, off) | 25817d00d604492cf3d03ed8b1f849f8fc859194 | 564,498 |
from pathlib import Path
def is_equal_or_child_of(source1: Path, source2: Path) -> bool:
"""
Checking if a source equal or a child of another source.
:param source1: Child source to check
:type source1: Path
:param source2: Parent source to check
:type source2: Path
:return: Is sources1 r... | 3278fae2fac3e1b239a75b56355526a061d9f28e | 442,747 |
def rem_item_from_list(item, string):
""" Removes all occurrences of token from string. If no occurrences of
items are in string, nothing is removed."""
return string.replace(item, "") | 5b0406c57aed3b786c4f20501be80e18f945928f | 695,833 |
def is_registration_api_v1(request):
"""
Checks if registration api is v1
:param request:
:return: Bool
"""
return 'v1' in request.get_full_path() and 'register' not in request.get_full_path() | fe82c373420022ad198785eb2c8575abe7d29c56 | 464,607 |
def error(p:float, p_star:float) -> tuple:
"""
Compute the absolute error and
relative error in approximations
of p by p^\\star.
----------------------------
Args:
p, p_star: Float.
Returns:
(absolute error, relative error).
Raises:
None.
"""
absolute_e... | e75a96616592a8f844c967a2968a748860023732 | 232,313 |
import math
def distance(x1, y1, x2, y2):
"""distance: euclidean distance between (x1,y1) and (x2,y2)"""
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) | b7b4662a88c9afd4b63d6ab04fc51749916749f1 | 696,214 |
def get_endpoint(url):
"""Get the parent url of this url."""
return url.rsplit("/", 1)[0] | 42022b2e897a76ca56bb70d72e45c6eaea478d95 | 593,424 |
def _get_log_formatter(verbosity_level):
"""
Get a log formatter string based on the supplied numeric verbosity level.
:param int verbosity_level: the verbosity level
:return: the log formatter string
:rtype: str
"""
formatter = "%(levelname)s: %(message)s"
if verbosity_level >= 3:
... | b34d470b679e3b7d540290ef394ccada418b9ef7 | 595,733 |
def multiply(m, n):
"""Recursively multiply the number 'm' by 'n' times
>>> multiply(5, 3)
15
"""
"""BEGIN PROBLEM 2.1"""
return m if n == 1 else m + multiply(m, n - 1)
"""END PROBLEM 2.1""" | 389e9692db846230e53670ceb53ffffcdad007f9 | 410,771 |
def loose_bool(s: str) -> bool:
"""Tries to 'loosely' convert the given string to a boolean. This is done
by first attempting to parse it into a number, then to a boolean. If this
fails, a set of pre-defined words is compared case-insensitively to the
string to determine whether it's positive/affirmativ... | a22eaac28b0b3452ca2656d2dff7836bb0daa49a | 331,070 |
def read_converged(content):
"""Check if program terminated normally"""
converged = False
for line in content.split("\n"):
if 'EXECUTION OF GAMESS TERMINATED NORMALLY' in line:
converged = True
return converged | d3132bd1fd8d61556f0f48eb19ff5042ac2f6302 | 533,569 |
def isAnalysisJob(trf):
""" Determine whether the job is an analysis job or not """
if (trf.startswith('https://') or trf.startswith('http://')):
analysisJob = True
else:
analysisJob = False
return analysisJob | 75ccaf711dd04dc99aca266533fee7303fad3e85 | 698,038 |
def format_signing_data(api_key_id, host, url, method):
""" Format the input data for signing to the exact specification.
Mainly, handles case-sensitivity where it must be handled.
>>> format_signing_data('0123456789abcdef', 'veracode.com', '/home', 'GET')
'id=0123456789abcdef&host=veracode.com&url=/h... | 6e1959a127ac76559d08fe896f7dcdd822e270ff | 274,449 |
import torch
def masked_logsumexp(x: torch.Tensor,
mask: torch.Tensor,
dim: int = -1) -> torch.Tensor:
"""Computes logsumexp over elements of a tensor specified by a mask
in a numerically stable way.
Parameters
----------
x
The input tensor.
m... | 838b747bbcbd155f0ba338268c732575283c324a | 412,012 |
def total_others_income(responses, derived):
""" Return the total of other incomes """
total = 0.0
for income in derived['others_income']:
try:
total += float(income['income_others_amount'])
except ValueError:
pass
return total | ab9dcca24609a32c846dcabdea08fc262d725a03 | 503,366 |
def non_basemap_layers(layers):
"""Retrieve all map layers which are not basemaps"""
return [layer for layer in layers if not layer.is_basemap] | 8a8bab454d97e8fe686be874c56421d2013a039f | 51,901 |
def findDivisors (n1, n2):
"""Assumes that n1 and n2 are positive ints
Returns a tuple containing all common divisors of n1 & n2"""
divisors = () #the empty tuple
for i in range(1, min (n1, n2) + 1):
if n1%i == 0 and n2%i == 0:
divisors = divisors + (i,)
return divisors | 60c20f6866fbed2cfc79bbe0b28396751fdfe6ff | 530,854 |
def estimate_average_price(order_qty: float, order_price: float, current_qty: float,
current_entry_price: float) -> float:
"""Estimates the new entry price for the position.
This is used after having a new order and updating the currently holding position.
Arguments:
orde... | 2466ba8a3d4374d83e44b4ffeff262a8741d621d | 466,559 |
def I2(Q,dfg):
"""
Computes the I^2 value, ie, percent of variation due to heterogeneity rather than chance
By convention, Q = 0 if Q < k-1, so that the precision of a random effects summary estimate
will not exceed the precision of a fixed effect summary estimate
See Higgins & Thompson 2002; DOI: 1... | 4e9b08f1484f578cb6a0af9c630ba607071fd21c | 523,802 |
def uniq(iterable, key=lambda x: x):
"""
Remove duplicates from an iterable. Preserves order.
:type iterable: Iterable[Ord => A]
:param iterable: an iterable of objects of any orderable type
:type key: Callable[A] -> (Ord => B)
:param key: optional argument; by default an item (A) is discarded
... | 219cba5494198fc806b503e9000a7e491fe2a7c5 | 625,466 |
import random
def split_test_from_training_data(network, ratio=0.1):
"""
Splits a given network into two networks with disjoint edges randomly.
"""
test_edges = random.sample(list(network.edges()), int(len(network.edges()) * ratio))
training_network = network.copy()
training_network.remove_edg... | 589c2b4f8c56941bca70a7342e5a47a41e23ce86 | 631,072 |
from typing import List
def append_suffix(name: str, suffix: List[str]) -> List[str]:
"""
Helper function to append suffixes to the given name.
"""
return list(map(lambda x: name + x, suffix)) | 6ce093b30eced8b9f5bc52503fd91cf95c6accba | 190,428 |
def pybel_to_inchi(pybel_mol, has_h=True):
"""
Convert an Open Babel molecule object to InChI
Args:
pybel_mol (OBmol): An Open Babel molecule.
has_h (bool): Whether the molecule has hydrogen atoms. ``True`` if it does.
Returns:
str: The respective InChI representation of the mo... | 219842968790d62cb05cd91228aacc500bf726a5 | 327,062 |
import json
def json_dump(obj, path):
"""Save a json object to a file."""
with open(path, 'w') as f:
return json.dump(obj, f, indent=2) | dc1ca23ed1322d860cf2c9236e56394489acf29e | 101,818 |
def path_as_0_moves(path):
"""
Takes the path which is a list of Position
objects and outputs it as a string of rlud
directions to match output desired by
Rosetta Code task.
"""
strpath = ""
for p in path:
if p.directiontomoveto != None:
strpath += p.directiontomove... | 6423f7c4c46fc79cd38cdddb3d367411ef9a05d4 | 663,515 |
import csv
def read_path2port_map(filename):
"""
Reads csv file containing two columns: column1 is path name,
column2 is port number
:param filename:
:return: dictionary with port as key and path as value
"""
res = {}
with open(filename, 'r') as csvfile:
reader = csv.reader(c... | 39a317c21d66c544bd50576493cb1e50dbc5b6bf | 72,391 |
def get_height(image):
"""get_height(image) -> integer height of the image (number of rows).
Input image must be rectangular list of lists. The height is
taken to be the number of rows.
"""
return len(image) | 3aa94c4b2458d2a233f32ee10889e52566c04ecb | 14,979 |
def month_str(month, upper=True):
"""Returns the string e.g. 'JAN' corresponding to month"""
months=['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
'sep', 'oct', 'nov', 'dec']
mstr = months[month - 1]
if upper:
mstr = mstr.upper()
return mstr | 535422928b6fa66691d6f29431ca3dc1a064b670 | 514,630 |
from pathlib import Path
import yaml
def load_plot_these_methods_config(path):
"""
Loads PLOT_THESE_METHODS.yaml present at `path`.
Args:
path (str): path where config files can be found.
Returns:
(set): a set of method that needs to be plotted. an empty set if the file is not found.... | 17f5951d82a3ad24747cbe868743d436275b6082 | 160,088 |
def identify_url(url):
"""
A possible way to identify the link.
Not Exhaustive!
:param url:
:return:
0 - Profile
1 - Profile post
2 - Group
3 - Group post
"""
if "groups" in url:
if "permalink" in url:
return 3
else:
return 2
elif "... | eb2c63c9d421e0ce1dd3d5cb8a144403895433fe | 541,087 |
import math
def next_even_number(val):
"""Returns the next even number after the input. If input is even, returns the same value."""
return math.ceil(val / 2) * 2 | 700334e60c4abfa949524c1825b7ee97dd8f75cd | 76,213 |
from datetime import datetime
def get_tag(tag=None):
"""
Simple helper function to create a tag for saving a file if one does not already exist.
This is useful because in some places we don't know whether we will have a tag or not,
but still want to save files.
Parameters
----------
tag ... | 5cecc708086dbcb1a7361ecf55dd015f9edaeedf | 624,785 |
import torch
def project_to_2d_linear(X, camera_params):
"""
Project 3D points to 2D using only linear parameters (focal length and principal point).
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_params -- intrinsic parameteres (N, 2+2+3+2=9)
"""
assert X.s... | bdd879930f6ee03eb170b85445e0a17727d37de2 | 287,529 |
def bdf_width(width: int) -> int:
"""Calculates the width in bits of each row in the BDF from the actual witdth of a character in pixels."""
# NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits
# (https://stackoverflow.com/a/37944252)
return -((-width) // 8) * 8 | c9d478d41ab94358524e384cf0c384994052626c | 637,243 |
def get_n_beads(n, i1 ,i2):
"""
given length of the ring polymer (n) and the starting-ending positions (i1, i2)
returns the length of the segment of the smaller length
:param n: number of elements
:type n: int
:param i1: starting position
:type i1: int
:param i2: ending position
:ty... | 5dee01efe31f9d98972dcdc997ad60ea1ba45b39 | 664,458 |
def int_to_bytes_big_endian(x: int, n_bytes: int) -> bytearray:
"""Converts integer to bytes in big endian mode"""
if x >= 256 ** n_bytes:
raise ValueError("Conversion overflow")
res = bytearray(n_bytes)
shift = 0
for i in range(n_bytes - 1, -1, -1):
res[i] = (x >> shift) & 0xff
... | 95487c6be1c24f68585619643ca90a1a87c3b1fb | 528,032 |
def strip_2tuple(dict):
"""
Strips the second value of the tuple out of a dictionary
{key: (first, second)} => {key: first}
"""
new_dict = {}
for key, (first, second) in dict.items():
new_dict[key] = first
return new_dict | 20f721da141f75bceb8bfd90d7ab02dbb82a01ce | 660,188 |
def _parse_row(row):
"""Parses a row of raw data from a labelled ingredient CSV file.
Args:
row: A row of labelled ingredient data. This is modified in place so
that any of its values that contain a number (e.g. "6.4") are
converted to floats and the 'index' value is converted t... | e4b521a8906dbe46c80604f93a76bea39db21f8a | 134,912 |
def evalt(t):
""" Evaluate tuple if unevaluated
>>> from logpy.util import evalt
>>> add = lambda x, y: x + y
>>> evalt((add, 2, 3))
5
>>> evalt(add(2, 3))
5
"""
if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]):
return t[0](*t[1:])
else:
return t | 6214f6c3e35be0556e04d5994d6f2e730756917a | 642,052 |
def split_cdl(cdl_string):
"""
Accepts a comma delimited list of values as a string,
and returns a list of the string elements.
"""
return [x.strip() for x in cdl_string.split(',')] | 8f73bdfdc1a70f513ed8f381a93bdd7392e4b332 | 564,590 |
def build_url() -> str:
"""Build url for standings source"""
return 'https://www.hockey.no/live/Standings?date=01.11.2020&tournamentid=397960&teamid=0' | 039f0ead632f9e2e9af54fc028552d9f8d7343b2 | 610,308 |
def decode_text(text):
"""Decodes a string from HTML."""
output = text
output = output.replace('\\n', '\n')
output = output.replace('\\t', '\t')
output = output.replace('\s', '\\')
output = output.replace('<', '<')
output = output.replace('>', '>')
output = output.replace('"',... | 0ea8d4ead854a44cf0da6e8b3a08c6f286d3420e | 307,550 |
def format_time(start, end):
"""
Format length of time between start and end.
:param start: the start time
:param end: the end time
:return: a formatted string of hours, minutes, and seconds
"""
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{... | 5e6879251c6f253c0260dd31fc455f0c87901ab9 | 634,061 |
import re
def str_pattern_valid(sname, pattern_group):
"""
Whether the sname matches the pattern in pattern_group
"""
for patt_str in pattern_group:
pattern = re.compile(patt_str)
match = re.match(pattern, sname)
if match is not None:
return True
return False | b9f86b58a068d88a9defeb279ab1a9a24cec9fdf | 608,616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.