content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def bayesdb_rowid_tokens(bdb):
"""Return list of built-in tokens that identify rowids (e.g. oid)."""
tokens = bdb.sql_execute('''
SELECT token FROM bayesdb_rowid_tokens
''').fetchall()
return [t[0] for t in tokens] | c054749baafa4e54e96b499d9c94521c1644a76f | 577,559 |
def addition(s, t):
"""Returns the mod-2 sum of two n-bit strings s and t."""
return tuple([(s[i] + t[i]) % 2 for i in range(len(s))]) | 4f11058d7245fd7c9d8f9518898f716ab7c076bf | 577,561 |
def _check_flexibility_scenario(flex):
"""Checks the flexibility scenario input to
:py:func:`partition_flexibility_by_sector`.
:param str flex: The input flexibility scenario that will be checked. Can be any of:
*'Base'* or *'Enhanced'*.
:return: (*set*) -- The formatted set of flexibility scen... | e7bfceec23f6e02e7d8895f0593b3704628a8e28 | 577,562 |
def get_line_count(filename):
""" Returns the number of non-empty lines
"""
lines = open(filename).readlines()
count = 0
for line in lines:
if len(line.strip()) > 0:
count += 1
return count | 5a579b5d519b9a834952ee831ab1ddde84219347 | 577,563 |
def perpendicular(x_val, y_val):
"""
This function gives the intercepts and slope of the perpendicular bisector of a given line segment.
Parameters
----------
x_val, y_vals : coordinates of the two points of the line segments(x_val = [x1, x2], y_val = [y1, y2]).
Return
----------
cx, cy : intercepts o... | 92d6697b3a36a3be951db5f09890e4ec957f4aa7 | 577,564 |
def read_body(environ):
"""
Pull the body from the request and return it
"""
length = environ.get("CONTENT_LENGTH", "0")
length = 0 if length == "" else int(length)
return environ["wsgi.input"].read(length) | a37c72f8d040807db5fb1039548c6d85966671af | 577,566 |
from typing import Union
from typing import Dict
import random
def get_value(value_or_range: Union[float, Dict[str, float]]) -> float:
"""
Get a specific or random value from a given specification.
The specification can either be the value itself, or an interval
given through a dictionary with the en... | a9d55660fce1ee13b9215298122c93eb2ebee326 | 577,567 |
def relative_sunshine_duration(n_act, n_max):
"""
Calculate the ratio of the actual duration of sunshine to the maximum
possible duration of sunshine or daylight hours (Allen et al. 1998).
This ratio expresses the cloudiness of the atmosphere.
Parameters
----------
n_act : float
Ac... | b69408697ac4ec040229bdc8c2ce7822a85523cf | 577,574 |
from functools import reduce
def getNestedAttribute(obj, attr, *args):
"""
Gets nested attribute from "."-separated string
Arguments:
obj {object} -- object to parse
attr {string} -- attribute name, optionally including
"."-characters to denote different levels
... | dbb61b9171750454ae219417dbc96672ce665e8c | 577,579 |
def _process_df_index_names(data):
"""Create a list containing the index names of a pandas.DataFrame
If the index does not have names, assign them as index0, index1, etc.
Args:
data (pandas.DataFrame): The data set to process index names for
Returns:
list: A list of index names for th... | b46a3967bf1d2f4bc7fc47c857a7396c30cc8076 | 577,580 |
def str_to_bin(data_string):
"""Returns the binary representation of a string
Uses unicode (or ASCII) representation of the string values
args:
data_string (str): Incoming string in unicode/ASCII format
return args:
binary_data (str): Binary representation of the string
"""
un... | 87e2f21843eb97566f13ff5386d6e412650c4b13 | 577,581 |
import random
def get_retry_interval(attempt: int, retry_interval_base: float,
retry_interval_cap: float) -> float:
"""Calculate interval before the next retry of an operation put into
retrying loop.
:param attempt: int, attempt number
:param retry_interval_base: fl... | 7cd8715ed5a81e1f623b05df73f147fb3f7011eb | 577,582 |
def format_board(state):
"""Format the board"""
cells = []
for i, char in enumerate(state, start=1):
cells.append(str(i) if char == '.' else char)
bar = '-------------'
cells_tmpl = '| {} | {} | {} |'
return '\n'.join([
bar,
cells_tmpl.format(cells[0], cells[1], cells[2... | 538cddd09eaa68328e29330c592ec2e04e07eb6c | 577,583 |
from typing import Callable
def applicable_function(target_category: str) -> Callable[[str], bool]:
"""Given a target category, returns a function(category: str) which tells
whether category is applicable to target_category.
"""
if target_category.endswith("."):
return lambda cat: cat.startswi... | 60373a543d170a83f216604d8ca66f4ff54bd6ae | 577,584 |
def f1(recall, precision):
"""
stantard f1 for binary classification
recall:
precision:
"""
return 2*precision*recall/(precision + recall) | 34b90a2e8aa9befded8773998f7549e23466ac45 | 577,585 |
def cubed(v):
"""
Returns cubed value
"""
return v*v*v | b29e95b2ac2b946bd4c6da1fcdee107e7c11df6b | 577,588 |
def break_scaffold(sequence: str, n: int = 10) -> list:
"""
We want to split scaffolds whenever there is a run of Ns. To achieve this,
we scan a sequence from left to right and keep track of the number of
consecutive Ns. If the number ever exceeds the threshold, we save the
sequence, and wait until ... | 78ad6f4d8bdf51847ebaeaaa8ab4fbede7554924 | 577,589 |
def _protein_dict(pep_lst):
# region
"""
Create a dictionary:
key = protein id
value = list of peptides associated with protein )
Dictionary gives us the raw count of unique peptide count for each protein.
Parameters
----------
pep_lst
Returns
-------
dictio... | d97584d6d2dee9b86729ac9bcacaca20e1ee4f68 | 577,590 |
import hashlib
def caclulate_hash(path: str) -> str:
"""Calculate md5 hash of the file in binary mode
Args:
path (str): Path to the file to be hashed
Returns:
str: The calculated hash
"""
hash_md5 = hashlib.md5()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.updat... | 5d4fd285a0921aaafe5d2387bfb7856d0e5d8621 | 577,592 |
def get_time_sorted_events_list(df, n_states):
"""
Given a dataframe returns a list of events, ordered by timestamp.
"""
end_event = n_states - 1
beginning_event = n_states - 2
events_list = list([beginning_event])
events_list.extend(df.reset_index()
.set_index("ti... | 5858bf34d896cf838e404a4c6001d7430cd7ed32 | 577,601 |
def get_floating_ip(body_response_server_details, network_name):
"""
Retrieve the first floating IP from the given network attached to VM
:param body_response_server_details: (dic) Parsed response. Server details data
:param network_name (String): Name of the network where floating IP is allocated.
... | e481a437d78987704da5e57f9a3a8b07380377a3 | 577,602 |
def max_or_none(iterable):
"""
Returns the max of some iterable, or None if the iterable has no items
Args:
iterable (iterable): Some iterable
Returns:
max item or None
"""
try:
return max(iterable)
except ValueError:
return None | 6d123df136e427d54525306439930dc560a0cf05 | 577,604 |
def is_cell_free(line, col, grid):
""" Checks whether a cell is free.
Does not throw if the indices are out of bounds. These cases return as free.
"""
# Negative indices are "legal", but we treat them as out of bounds.
if line < 0 or col < 0:
return True
try:
return grid[line][... | 4c1375e39a907cb75a57b24cfe6c62994dc3dc54 | 577,609 |
def tribonacci_memo(n, memo):
"""
Uses memoization to calculate the nth tribonacci number
Args:
n: the number
memo: the dictionary that stores intermediate results
Returns:
nth tribonacci number
"""
if n in memo:
return memo[n]
else:
ans1 = tribonacci_... | e125702543e9f682509f5f0860b74acac2611627 | 577,610 |
def karatsuba(x, y):
"""Karatsuba method for fast multiplication"""
if x < 10 and y < 10:
return x * y
num1_len = len(str(x))
num2_len = len(str(y))
n = max(num1_len, num2_len)
# round decides to be floor or ceil value
# by this we can reduce some function calls
# of ceil or f... | 9369d4ccf85230ad593efc5a996d48b78574ccf6 | 577,611 |
def parse_params_bool(params, p):
""" Get and parse a boolean value from request params. """
val = params.pop(p, None)
if not val:
return False
return val.lower() in ("yes", "1", "true") | dc4464c89087c2a45a5548f67a6fa18aa1276b6b | 577,612 |
def swap_kv(kv):
"""Swap a key-value tuple."""
return (kv[1], kv[0]) | 9363d914229986ba0f404a7f8291fbc2221e7518 | 577,617 |
import torch
from typing import Any
def tensor2image(tensor: torch.Tensor, range_norm: bool, half: bool) -> Any:
"""Converts ``torch.Tensor`` to ``PIL.Image``.
Args:
tensor (torch.Tensor): The image that needs to be converted to ``PIL.Image``
range_norm (bool): Scale [-1, 1] data to between [... | 794a4e30227ba6024cb8d1514d25e71cf048b211 | 577,619 |
def prefix_match(value: str, prefix: str) -> bool:
"""Test of the given string value starts with a given prefix.
Parameters
----------
value: str
Value for which the prefix is evaluated.
prefix: str
Prefix string that is tested for the given value.
Returns
-------
bool
... | 3781ad40339cdd8c1479538f76d11752a8a4803f | 577,621 |
def is_file(line: str) -> bool:
"""Check if a return line is a song file."""
return line.startswith('file:') | 71d6ad3cbc1435a14b5ac9730c558e4454adacc2 | 577,624 |
import struct
def parseindexentry(a):
"""decodes the DataIndexEntry made of a timestamp, config and offset as dictionary"""
ts, cid, pos = struct.unpack("=QiQ", a.read(20))
return dict(timestamp=ts, config=cid, offset=pos) | 55483308606d6d85fd90a83b988555644ab68f05 | 577,625 |
def make_thinner(interval):
"""
Return a thinner function for the given interval.
The function should be called with sequential values;
if the value should be used, the function will return True,
if ignored, False.
:param interval: Interval; whatever makes sense for the values passed in.
:... | 9fefc0829d436211f6a51cd564a93cc4b80d209e | 577,627 |
def nottest(f):
"""Mark a function as not a test (decorator)."""
f.__test__ = False
return f | d7ae85682c4be0ca0d96926d638c24b01567f002 | 577,638 |
def int_to_hexstring(data, data_type='H', str_len=8):
"""
Takes an integer and creates a hex string of the appropriate length
Args:
data (int): value to hexlify
data_type (int): one of the enumerated TAGTYPES
str_len (int): number of characters in the resulting string... | fb9bfcc698a3df1bce41d7520f9e4fc2bf135025 | 577,639 |
def dot_product(tf1, tf2):
"""
Calculates the dot product of two term frquency vectors.
Returns the dot product of the frequencies of matching terms
in two term frequency vectors. The term frequency vectors are
dictionaries with the term as the key and the frequency as the value.
Parameters:
... | ce141ed1fca3e754b2f81dc2f2a7ece9263e594d | 577,642 |
from typing import Iterable
from typing import AnyStr
def join_separated(iterable: Iterable[AnyStr], sep: AnyStr) -> AnyStr:
"""
Join the elements of ``iterable`` together, separating consecutive elements
with ``sep``
:param iterable: an iterable of binary or text strings
:param sep: a binary or ... | e2cd30bf76b0f17623d00dbd302a7976ee8230db | 577,643 |
def get_specific_comments(client, parent_id):
""" Call the API's comments.list method to list the existing comment replies
Args:
client (IntalledAppFlow): a dedicated client registered with credentials
parent_id (int): comment thread parent id
Returns:
comments["items"]: a simple li... | eecff95e377f5013ea57c0a7ada90c8618a605b0 | 577,646 |
def dewPointToRH(t_dry, t_dew):
"""
Calculate relative humidity from dry bulb and dew point (in degrees
Celsius)
:param float t_dry: Dry bulb temperature (degrees Celsius).
:param float t_dew: Dew point temperature (degrees Celsius).
:returns: Relative humidity (%)
:rtype: float
"""
... | ffac60d4873a69a2525b625296c5d1c8912d9265 | 577,648 |
def subarray_slice(index, num_items):
"""
Returns a slice that selects for selecting a chunk out of an array
@param index: Which chunk to select
@param num_items: Number of items in a chunk
@return A slice for selecting index*num_items to (index+1)*num_items
"""
return slice(index * num_ite... | 0555b367195918ba06d8da309b1ef5d02bd3786d | 577,649 |
def fortrandouble(x):
"""Converts string of Fortran double scientific notation to python float.
Example
-------
>>> val = '-0.12345D+03'
>>> print(fortrandouble(val))
-123.45
"""
return float(x.replace('D', 'E')) | 704d18861a5014b3817c089f275e270d95544a6f | 577,650 |
import json
def SequentiallyLoadJavascript(files, selector='', closure=''):
"""Produces javascriprt to sequentially load all files.
Example
SequentiallyLoadJavascript(
files=['jquery.js', 'jquery-deathstar.js'],
selector='#msgid',
closure='ActivateDeathStar()')
Args:
files: i... | 467ea9f3e9047362d7e4172fad02147b3f14748c | 577,651 |
def lowerBackslash(r, c):
"""
>>> lowerBackslash(6, 3)
[(6, 3), (7, 4), (8, 5)]
>>> lowerBackslash(2, 2)
[(2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)]
>>> lowerBackslash(1, 8)
[(1, 8)]
>>> lowerBackslash(1, 1)
[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)... | 8269b34c71651df32a79f111f18d2a28350807dd | 577,652 |
def split_list(L, S):
"""Split list given a list of breaking elements"""
output = list()
for s in S:
if s in L:
idx = L.index(s)
output.append(L[:idx])
L = L[idx+1:]
return output | f218ff03571221413d69c5447df5da726645d6ef | 577,656 |
def qrcode_size_table() -> dict[int, int]:
"""Dictionary that contains the size of the QR-code depending
on the version.
Returns:
dict[int, int]: A dictionary that contains data in the
form (version: size)
"""
table = {
1: 21, 2: 25, 3: 29, 4: 33, 5: 37, 6: 41, 7: 45, 8: 49,... | f4de761348a2331f047786b09f58b45d039efb7f | 577,659 |
def count(grid, char):
"""Counts the occurrences of [char] in the grid."""
res = 0
for line in grid:
res += sum(1 for c in line if c == char)
return res | b66ce11d53480e260f8e2e7a2dd7a9796aebdf5e | 577,663 |
def max_sequence(seq):
"""
Функция ищет пять соседних элементов списка, сумма значений которых максимальна.
>>> max_sequence([1, 3, 1, 1, 4, 4, 3, 1, 4, 4, 4, 3, 4, 4, 1, 3, 2, 4, 4, 4])
[4, 4, 4, 3, 4]
>>> max_sequence([1, 5, 7, 2, 9, 2, 9, 2, 5, 3, 7, 6, 3, 3, 7, 4, 4, 1, 9, 5])
[7, ... | 11f1a675cc806e7b6d3a0b76bc0cf36df201dc85 | 577,666 |
def broadcast(dct):
"""Convenience function for broadcasting a dictionary of lists.
Parameters
----------
dct : dict
Input parameter ranges. All parameter ranges must have only 1 or N values.
Returns
-------
list
List of N dictionaries; the input parameters with N values ar... | 85d8e32b0cf784b3975bd033b0a56d9df0641de1 | 577,671 |
def get_val_unit(json_data, arg1, arg2, unit):
"""Extract value from JSON and concatenate with a unit."""
value = str(json_data[arg1][arg2])
return f"{value}{unit}" | de66fe4b87c43eccfb6e30e3e577e14613a855a7 | 577,672 |
import re
def matches_key(key: str, message: str):
"""
Find key in message
:param key: key to find in message
:param message: message
:return: matched key
"""
return len(re.findall(r'(?<!\d)' + key, message)) > 0 | c7e82627514c077a45bfe611cad822be2eda3fc1 | 577,673 |
def target_directory(tmp_path_factory):
"""Set up a tmp directory for writing artifacts."""
return tmp_path_factory.mktemp("target") | c85b128ff480ed25c8d4944522d3baf6c75ce8fa | 577,675 |
def hausdorff_result_to_dict(haudorff_result):
"""
Converts the tuple returned by the Hausdorff distance functions to a dictionary
for easier use.
Args:
haudorff_result: Tuple returned from Hausdorff distance function
Returns:
Dictionary version of the tuple.
"""
return {
... | 1f03a7641ea6703ed9954b9879d69dc2b1fbcf92 | 577,680 |
def isiterable(obj):
"""Checks if an object is iterable
Parameters
----------
obj: object
Object to check
Returns
-------
is_iterable: bool
Boolean variable indicating wether the object is iterable
Example
-------
>>> from pymatting import *
>>> l = []
... | cc51029317a0fe459ebb60608763560cd1af27d6 | 577,683 |
import re
def findSignatures(page):
"""
Regex to the last possible position of a date in a rendered page.
Searches for dash surrounded by spaces with a span or div element at the
end of a possible text entry.
"""
positions = []
# Date located before this regex
p = re.compile('( [-] )(.... | 71a9084bf2fa1eec1029038d57f964e13efa90ca | 577,684 |
def get_eula(task):
"""Return a dict containing the module's EULA information"""
return task.dto['eulaInfo'] | 830356516ab1dd5f12e779f4b678d6b8120ef2f9 | 577,693 |
from typing import List
def unbox_tokens(tokens: List[str]) -> List[str]:
"""
Remove square brackets around tokens if any.
:param tokens: List of tokens.
:return: List of "unboxed" tokens
"""
return [t[1:-1] if t[0] == "[" and t[-1] == "]" else t for t in tokens] | f06a18a92ecd050402d46a1e6732bf3726dc6884 | 577,694 |
def bad_request(except_msg: str = "", *args: tuple, **kwargs: dict) -> dict:
"""
Bad Request exception response
:param except_msg: message stating the error
:param args: positional arguments passed to the function - list
:param kwargs: keyword arguments passed to the function - dict
:return: Ope... | d1096ca108607c67966c47b39135815dbbc620eb | 577,701 |
from datetime import datetime
import calendar
def date_with_last_day_of_month(date):
"""
Changes date to date on the last day of the month.
:param date: <datetime.datetime> -> datetime object
:return: <datetime.datetime> -> datetime object with last day of the month
"""
return datetime(date.ye... | ddc5e37265d5d3d84e856f0ce2493e90b6eb25b8 | 577,702 |
def crop_box_right_bottom(current_size, target_size):
"""
Returns box coordinates (x1, y1, x2, y2) to
crop image to target size from right-bottom.
"""
cur_w, cur_h = current_size
trg_w, trg_h = target_size
assert trg_w <= cur_w
assert trg_h <= cur_h
x1 = cur_w - trg_w
x2 = cur_w
... | 1279019976f9e283edf13aebf61b643aa1eb6ac7 | 577,705 |
from collections import defaultdict
def get_modules(module, grouped=False, sorted=True):
"""
Retrieve @module actions from a python module.
If *grouped*, return modules grouped by action tag.
If *sorted*, sort the actions by name attribute, otherwise they appear
in the original order in the modu... | 8ed1b856dd80b98976a52957af878a966cdfd111 | 577,712 |
def show_vm_template(client, private_cloud, template, location):
"""
Returns details of a VMware virtual machines template in a private cloud.
"""
return client.get(location, private_cloud, template) | 27a0e8ac7d3cc0f6c54317ec06069909ec3d3b9d | 577,713 |
def drop_cols(train_X, val_X, cols):
"""Function to drop columns"""
# copy data
drop_train_X = train_X.copy()
drop_val_X = val_X.copy()
# drop columns
drop_train_X = drop_train_X.drop(cols, axis=1)
drop_val_X = drop_val_X.drop(cols, axis=1)
return drop_train_X, drop_val_X | a2a7990d7a8e3aff151f113a38aefd8ae9628ef6 | 577,715 |
import configparser
def get_db_url(file: str = "creds.ini") -> str:
"""Gets Postgres URL including credentials from specified file.
Example of File:
```
[pg_creds]
pg_url = postgresql://testusr:password@127.0.0.1:5432/testdb
```
:param file name
:returns str or None if exception faile... | f187181c235d2ff4ae639467b6a0f4aa2b47035d | 577,716 |
def legendre_symbol(a, p):
"""
Legendre symbol
Define if a is a quadratic residue modulo odd prime
http://en.wikipedia.org/wiki/Legendre_symbol
"""
ls = pow(a, (p - 1)/2, p)
if ls == p - 1:
return -1
return ls | 4677c54d41172ecc4b6add122bb612448d1f0653 | 577,717 |
def get_mixture_weights_index_tuples(n_mixtures):
"""Index tuples for mixture_weight.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
Returns:
ind_tups (list)
"""
ind_tups = []
for emf in range(n_mixtures):
ind_tups.append(("mixtu... | 03bd80c9ec6d7df1b7e43bde899b199876adacf5 | 577,720 |
def truncate(value,arg):
"""Truncates a string of a given length, adds three dots at the end."""
try:
if len(value) > arg:
return "%s..." % value[0:arg-3]
else:
return value
except ValueError:
pass | a977dfe704e9433fbbb9349da259aee40cbd8e05 | 577,722 |
import click
def select_manual_app_path() -> str:
"""Prompts for path to ide."""
path: str = click.prompt('Enter the path to IDE', type=str)
return path | 82c57804e4880fa2a85b812f82d234991107fa16 | 577,724 |
from pathlib import Path
def _num_times_blocked(log_path: Path):
"""Returns the number of times execution is blocked."""
with log_path.open("r") as log_f:
return sum(1 for line in log_f if "blocked" in line) | 68c0821af6a6f253db5b0979dccd55bbca6a2954 | 577,726 |
from functools import reduce
def return_related(instance, related_field):
"""
This functions works in a similar method to return_attrib but is
meant for related models. Support multiple levels of relationship
using double underscore.
"""
return reduce(getattr, related_field.split('__'), instan... | 155c1d6502fa0dfb3335af5fcbd71d1a5723ed92 | 577,727 |
def IsRemote(path):
""" Check if a given path points to remote (HTTP) or local storage """
return path[0:7] == "http://" | 78ac441f2fae3f777b68eb6ae9ec0550bd6857cd | 577,732 |
def to_seconds(t):
"""
Convert length of time in m:s.d format into seconds
e.g. to_seconds('1:15.2') -> 75.2
"""
m, s = t.split(':')
seconds = int(m) * 60 + float(s)
return seconds | 3b93bf606273f3a43c406d52f3549e612c68888f | 577,739 |
def _element_iterable(el):
"""
Test if a element is iterable
Parameters
----------
el: object
Returns
-------
iterable: boolean
if True then then el is iterable
if Fales then not
"""
try:
el[0]
iterable = True
except (TypeError, IndexError):
... | 844d5192a90a8fae5f557a099f221b446b6d8b8c | 577,741 |
def getPrevRecord(records, index):
"""
Attempts to get the chronologically previous record
:param records: <list[recorder.Record|(str)]> list of records (type doesn't matter)
:param index: <int> index value of starting record (index - 1 should be the previous record)
:return: <recorder.Record|(str) or None> p... | 3e92bbdaaafd9256e047f96245a7208ffc7c0a37 | 577,743 |
import re
def CamelToSnakeCase(input_string):
"""Converts camelCase to snake_case."""
# Prepend every uppercase character with an underscore
# e.g. camelCase -> camel_Case
with_underscores = re.sub(r'([A-Z])', r'_\1', input_string)
# Ensure a name starting with an uppercase letter does not have an undersc... | 9c1109c7213251eb63c4cd777b79528564d4a5ee | 577,749 |
def zenodo_project_download_helper(is_record, project_name, project_helper, files):
"""
Downloads a full project from Zenodo and returns the expected list of dictionaries.
Parameters
----------
is_record : bool
Flag for if the resource is a published record
project_name : str
Th... | 654b65668449c5ad4ea08d96d6709fb631ed8160 | 577,751 |
def CreateGrid(size):
"""Accept a list, create a size by size blank 2-d list"""
#row = a list of the current row being added
#board = the list that corresponds to the board being constructed
board = []
for rows in range(size):
row = []
for cols in range(size):
row.appen... | 4462b98d2d4af6b26f1ebb0fd292eafa94aea0a2 | 577,752 |
from functools import reduce
def balt_to_int(D):
"""
Convert a list of balanced ternary digits to an integer
"""
return reduce(lambda y,x: x + 3 * y,D,0) | cbc054957fee3129881a684a1ce7bf279d8ead14 | 577,757 |
def tree_get_first_column_value(treeview):
"""Find selected first column item name from treeview (PYGTK-specific)."""
(model, pathlist) = treeview.get_selection().get_selected_rows()
# check something was selected
if len(pathlist) == 0:
return
tree_iter = model.get_iter(pathlist[0])
re... | ce6c0e965e92f2a9316e237bd08e30a759908f71 | 577,762 |
def format_duration(milliseconds):
"""Given milliseconds, return human readable duration string such as:
533ms, 2.1s, 4m52s, 34m12s, 1h4m
"""
# under 1 ms
# ex: 0.83ms
# ex: 8.3ms
if milliseconds < 10:
return "{duration}ms".format(duration=round(milliseconds, 2))
# between 10 m... | 46b1f2f5a73af35a5b059c973c0631df6f43d177 | 577,763 |
def count_devices(devices):
"""Count numbers of CUDA devices
Args:
devices (str): comma split string
Returns:
num_gpus (int): numbers of gpus
"""
num_gpus = len(devices.split(","))
return num_gpus | 2dfbe9a3e01c38900e453da2c10fe5cda299570b | 577,767 |
def get_value(keys, dict_, default=None):
"""
Given a list of keys, search in a dict for the first matching keys (case insensitive) and return the value
Note: the search is case insensitive.
:param keys: list of possible keys
:param dict_:
:param default:
:return:
"""
keys = [k.lower... | 5e46f9ed434c284986fb0333ac09d27313918361 | 577,770 |
def beta_to_kelvin(beta):
"""
Convert :math:`\\beta` to Kelvin.
Parameters
----------
beta : float
Inversion temperature.
Returns
-------
T : float
Temperature (K).
"""
kb=8.6173303E-5
ev = 1.0/float(beta)
T = ev/kb
return T | 6f58f248fad6045cf1b9f9e6d29f162f3e01f515 | 577,771 |
def aggregate_metrics(*value_update_tuples):
"""Aggregates the metric value tensors and update ops into two lists.
Args:
*value_update_tuples: a variable number of tuples, each of which contain the
pair of (value_tensor, update_op) from a streaming metric.
Returns:
a list of value tensors and a li... | 0dd7709c749027020c83ebaa5dd76c9567e7680a | 577,777 |
def cobbdouglas(x, par):
""" Cobb douglas utility function for 2 goods.
INPUT:
Parameters
par (alpha) : relative preference for consumption to leisure, 0<alpha<1
Consumption bundle
x : Consumption tuple
x[0] : consumption
x[1] : leisure
OUTPUT... | 44e960e2047f4bf33f39bfe2c4d0f7c0bea5a063 | 577,780 |
def _SumPercent(targets):
"""Sums the percents of the given targets."""
return sum(t.percent for t in targets if t.percent) | 888085c6b3c4659d7c3b08d103e0ff536effcd35 | 577,782 |
def apply_R(R, A):
"""
Apply the rotation on the set of vectors A.
Args:
R (numpy.matrix): a rotation matrix.
A (numpy.matrix): the set of vectors to rotate.
Returns:
(numpy.matrix): the set of vectors, rotated by the matrix.
"""
A2 = R*A.T
A2 = A2.T
return A2 | c2d1d7eeeb2e179588745d629b336f7ebb9c61c7 | 577,784 |
def build_raw_view(lines_layout, stats_human, no_stat_human='-'):
"""Convert the lines_layout to human reading stats list"""
raw = []
for v in lines_layout:
try:
raw.append(v.format(**stats_human))
except KeyError:
raw.append(no_stat_human)
return raw | 6454131f8571bee6c69f57ff6ca129a87727acb4 | 577,790 |
import re
def process_gpu_clblas(stdout):
""" Process the stdout of the SYCLBLAS papre benchmarks.
stdout is a string containing multiple lines.
Example output:
t_copy, 0.000111871
t_axpy, 0.000119333
t_add, 0.00017468
"""
headers = []
values = {}
lines = stdout.splitlines(... | 5f31b5ebb9747cdc7e1865e6c37ec371c53e4e65 | 577,791 |
def removeQuote(str):
"""
Remove the single or double quote. for example: 'abc' --> abc
"""
while len(str) > 2:
if ((str[0] == '"') & (str[-1] == '"')):
str = str[1:-1]
elif ((str[0] == "'") & (str[-1] == "'")):
str = str[1:-1]
else:
break
return str | da5ed26fabf5969a7d651014d6ce67d6456aba61 | 577,795 |
def isSubStringOf(term1, term2):
"""
check if term1 is a substring of term2 on token-level
:param term1:
:param term2:
:return:
"""
if len(term1.strip()) == 0 or len(term2.strip()) == 0:
return False
term1_token_set = set(term1.split(' '))
term2_token_set = set(term2.split('... | 1e8172f5d72ecc1061d71f860558dbbc8472a3f9 | 577,803 |
def order_of_magnitude(x):
"""Returns the nearest power of 10 less than x
x = 0.00345, returns -3, x = 4320.0 returns 3.
x = 5.42e+25, returns 25
"""
stringx = str(float(x))
# if x is in e form, just return the e multiplier
eindex = stringx.find('e')
if not eindex == -1:
return(... | ea8e20c62ab21f1859b2064ecb4739f22b1c2692 | 577,806 |
def read_annotation(annotation_string):
"""
Read the annotation string and return a dictionary with the annotation names as keys and the annotation values as values.
"""
annotation_dict = {}
for annotation in annotation_string:
annotation = annotation.split(':')
annotation_dict[f"{an... | 5ef0d6ad4c6680546a3e0918e21caf929d52cc95 | 577,808 |
import re
def normalize_label_name(label):
"""
Lowercases a label name and replaces all whitespace with hyphens.
"""
label = label.lower()
return re.sub(r'\s+', '-', label) | a94702c1f791de50d6c951c923336e0bbaa50caa | 577,811 |
from typing import Iterable
def as_list(items: Iterable):
"""Convert single item to list"""
if not isinstance(items, list):
items = [items]
return items | 84d915c459fc163bae679bb6b83a2671d28ea2a8 | 577,814 |
def standard_number(input_num: float) -> int:
"""Get the standard number value.
In this project, the standard num is *100000000, and rounding to int.
Args:
input_num: The number you want to standard.
Returns:
The standard num.
"""
if input_num > 0:
return int(input_num... | d4d8c30fdd775774f7387b68f6b9fef4b0797859 | 577,819 |
def receptive_field_size(total_layers, num_cycles, kernel_size,
dilation=lambda x: 2**x):
"""Compute receptive field size
Args:
total_layers (int): total layers
num_cycles (int): cycles
kernel_size (int): kernel size
dilation (lambda): lambda to compute d... | 1de8cc083a5afa0c6cf5022de28a63df1f253280 | 577,822 |
def Kmeans_MStep(X, centroids, labels):
"""
This function performs the Maximization Step of K-means. It computes the new centroids given the current centroid assignment of data points.
K-Means learning is done by iterating the Expectation and Maximization steps until convergence, or until max_iter is reache... | 192ee3f9b4fec237f90ea6a2eee020a8aa240a26 | 577,823 |
def tail(f, nlines, BLOCK_SIZE=32768):
"""
Reads the last nlines of a file.
Args:
f (filehandle):
File handle of file to be read
nlines (int):
Number of lines to be read from end of file
BLOCK_SIZE (int):
Size of block (in bytes) to be read per ... | 5f096da54ffe97701534a2c94a3745a8cc7fc934 | 577,827 |
def recvall(sock):
""" recvall implementation, receives data of whatever size in several chunks
Args:
sock (socket): connected socket
Returns:
[byte]: data received from the socket
"""
BUFF_SIZE = 4096 # 4 KiB, §EDIT buffer size
data = b''
while True:
part = sock.re... | f0b79454d502435c53e6e8cf1c8c84860b437f8b | 577,831 |
def Garen2005(th, cloud_factor):
"""
Cloud correction is based on the relationship in Garen and Marks (2005)
:cite:`Garen&Marks:2005` between the cloud factor and measured long
wave radiation using measurement stations in the Boise River Basin.
.. math::
L_{cloud} = L_{clear} * (1.485 - 0.4... | 4e2b1990a8b94cfa6364ee562fa3a2ad44e12865 | 577,834 |
from typing import Sequence
def my_dot(v0: Sequence[float], v1: Sequence[float]) -> float:
"""
Perform mathematical dot product between two same-length vectors. IE component-wise multiply, then sum.
:param v0: any number of floats
:param v1: same number of floats
:return: single float
"""
dot = 0.0
for (a, b... | 6a4742cbd47395de69ee88f5fe0baf696993b644 | 577,835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.