content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def count_char(char, word):
"""Counts the characters in word"""
return word.count(char)
# If you want to do it manually try a for loop | 363222f4876c5a574a84fe14214760c505e920b0 | 0 |
def getItemSize(dataType):
"""
Gets the size of an object depending on its data type name
Args:
dataType (String): Data type of the object
Returns:
(Integer): Size of the object
"""
# If it's a vector 6, its size is 6
if dataType.startswith("VECTOR6"):
return 6
# If it,s a vector 3, its size is 6
elif dataType.startswith("VECTOR3"):
return 3
# Else its size is only 1
return 1 | 2ab9c83bef56cd8dbe56c558d123e24c9da6eb0e | 5 |
def CleanGrant(grant):
"""Returns a "cleaned" grant by rounding properly the internal data.
This insures that 2 grants coming from 2 different sources are actually
identical, irrespective of the logging/storage precision used.
"""
return grant._replace(latitude=round(grant.latitude, 6),
longitude=round(grant.longitude, 6),
height_agl=round(grant.height_agl, 2),
max_eirp=round(grant.max_eirp, 3)) | 648bb0a76f9a7cfe355ee8ffced324eb6ceb601e | 8 |
def trim(str):
"""Remove multiple spaces"""
return ' '.join(str.strip().split()) | ed98f521c1cea24552959aa334ffb0c314b9f112 | 9 |
import torch
def get_optimizer(lr):
"""
Specify an optimizer and its parameters.
Returns
-------
tuple(torch.optim.Optimizer, dict)
The optimizer class and the dictionary of kwargs that should
be passed in to the optimizer constructor.
"""
return (torch.optim.SGD,
{"lr": lr, "weight_decay": 1e-6, "momentum": 0.9}) | 213090258414059f7a01bd40ecd7ef04158d60e5 | 10 |
def merge(intervals: list[list[int]]) -> list[list[int]]:
"""Generate a new schedule with non-overlapping intervals by merging intervals which overlap
Complexity:
n = len(intervals)
Time: O(nlogn) for the initial sort
Space: O(n) for the worst case of no overlapping intervals
Examples:
>>> merge(intervals=[[1,3],[2,6],[8,10],[15,18]])
[[1, 6], [8, 10], [15, 18]]
>>> merge(intervals=[[1,4],[4,5]])
[[1, 5]]
>>> merge(intervals=[[1,4]])
[[1, 4]]
"""
## EDGE CASES ##
if len(intervals) <= 1:
return intervals
"""ALGORITHM"""
## INITIALIZE VARS ##
intervals.sort(key=lambda k: k[0]) # sort on start times
# DS's/res
merged_intervals = []
# MERGE INTERVALS
prev_interval, remaining_intervals = intervals[0], intervals[1:]
for curr_interval in remaining_intervals:
# if prev interval end >= curr interval start
if prev_interval[1] >= curr_interval[0]:
# adjust new prev interval
prev_interval[1] = max(prev_interval[1], curr_interval[1])
else:
merged_intervals.append(prev_interval)
prev_interval = curr_interval
merged_intervals.append(prev_interval)
return merged_intervals | 49a9d7d461ba67ec3b5f839331c2a13d9fc068d0 | 13 |
def rsquared_adj(r, nobs, df_res, has_constant=True):
"""
Compute the adjusted R^2, coefficient of determination.
Args:
r (float): rsquared value
nobs (int): number of observations the model was fit on
df_res (int): degrees of freedom of the residuals (nobs - number of model params)
has_constant (bool): whether the fitted model included a constant (intercept)
Returns:
float: adjusted coefficient of determination
"""
if has_constant:
return 1.0 - (nobs - 1) / df_res * (1.0 - r)
else:
return 1.0 - nobs / df_res * (1.0 - r) | 8d466437db7ec9de9bc7ee1d9d50a3355479209d | 17 |
def map_string(affix_string: str, punctuation: str, whitespace_only: bool = False) -> str:
"""Turn affix string into type char representation. Types are 'w' for non-whitespace char,
and 's' for whitespace char.
:param affix_string: a string
:type: str
:param punctuation: the set of characters to treat as punctuation
:type punctuation: str
:param whitespace_only: whether to treat only whitespace as word boundary or also include (some) punctuation
:type whitespace_only: bool
:return: the type char representation
:rtype: str
"""
if whitespace_only:
return "".join(["s" if char == " " else "w" for char in affix_string])
else:
return "".join(["s" if char == " " or char in punctuation else "w" for char in affix_string]) | 6258f9e57a9081a1c791ec7c22f855079a99cdfb | 21 |
import re
def extract_digits_from_end_of_string(input_string):
"""
Gets digits at the end of a string
:param input_string: str
:return: int
"""
result = re.search(r'(\d+)$', input_string)
if result is not None:
return int(result.group(0)) | aae771a051a228c53c36062437de65ae4aa15d44 | 23 |
import torch
def move_bdim_to_front(x, result_ndim=None):
"""
Returns a tensor with a batch dimension at the front. If a batch
dimension already exists, move it. Otherwise, create a new batch
dimension at the front. If `result_ndim` is not None, ensure that the
resulting tensor has rank equal to `result_ndim`.
"""
x_dim = len(x.shape)
x_bdim = x.bdim
if x_bdim is None:
x = torch.unsqueeze(x, 0)
else:
x = torch.movedim(x, x_bdim, 0)
if result_ndim is None:
return x
diff = result_ndim - x_dim - (x_bdim is None)
for _ in range(diff):
x = torch.unsqueeze(x, 1)
return x | 313a1837b6c3b451cebacaa7815f2631dfa387e5 | 24 |
from typing import OrderedDict
def build_pathmatcher(name, defaultServiceUrl):
"""
This builds and returns a full pathMatcher entry, for appending to an existing URL map.
Parameters:
name: The name of the pathMatcher.
defaultServiceUrl: Denotes the URL requests should go to if none of the path patterns match.
"""
matcher = OrderedDict()
matcher['defaultService'] = defaultServiceUrl
matcher['name'] = name
return matcher | e21a79d51b41bd393a8fa2e254c6db7cf61bd441 | 38 |
import re
def add_whitespace(c_fn):
""" Add two spaces between all tokens of a C function
"""
tok = re.compile(r'[a-zA-Z0-9_]+|\*|\(|\)|\,|\[|\]')
return ' ' + ' '.join(tok.findall(c_fn)) + ' ' | 57d59a5956c3914fa01587b6262e7d4348d77446 | 39 |
def check_min_sample_periods(X, time_column, min_sample_periods):
"""
Check if all periods contained in a dataframe for a certain time_column
contain at least min_sample_periods examples.
"""
return (X[time_column].value_counts() >= min_sample_periods).prod() | 074c196a169d65582dbb32cc57c86c82ce4cb9c9 | 41 |
def webpage_attribute_getter(attr):
""" Helper function for defining getters for web_page attributes, e.g.
``get_foo_enabled = webpage_attribute_getter("foo")`` returns
a value of ``webpage.foo`` attribute.
"""
def _getter(self):
return getattr(self.web_page, attr)
return _getter | 3626f8e2d8c6fb7fbb490dc72f796599cdbc874e | 43 |
import uuid
def make_uuid(value):
"""Converts a value into a python uuid object."""
if isinstance(value, uuid.UUID):
return value
return uuid.UUID(value) | b65b5739151d84bedd39bc994441d1daa33d1b51 | 46 |
import re
from pathlib import Path
import json
def parse_json_with_comments(pathlike):
"""
Parse a JSON file after removing any comments.
Comments can use either ``//`` for single-line
comments or or ``/* ... */`` for multi-line comments.
The input filepath can be a string or ``pathlib.Path``.
Parameters
----------
filename : str or os.PathLike
Path to the input JSON file either as a string
or as a ``pathlib.Path`` object.
Returns
-------
obj : dict
JSON object representing the input file.
Note
----
This code was adapted from:
https://web.archive.org/web/20150520154859/http://www.lifl.fr/~riquetd/parse-a-json-file-with-comments.html
"""
# Regular expression to identify comments
comment_re = re.compile(r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE)
# if we passed in a string, convert it to a Path
if isinstance(pathlike, str):
pathlike = Path(pathlike)
with open(pathlike, 'r') as file_buff:
content = ''.join(file_buff.readlines())
# Looking for comments
match = comment_re.search(content)
while match:
# single line comment
content = content[:match.start()] + content[match.end():]
match = comment_re.search(content)
# Return JSON object
config = json.loads(content)
return config | e79a461c210879d66b699fe49e84d0d2c58a964b | 47 |
def get_school_total_students(school_id, aug_school_info):
"""
Gets total number of students associated with a school.
Args:
district_id (str): NCES ID of target district (e.g. '0100005').
aug_school_info (pandas.DataFrame): Target augmented school information
(as formatted by `auxiliary.data_handler.DataHandler`).
Returns:
int: Single number comprising school-level data.
"""
return int(aug_school_info.loc[school_id]["total_students"]) | d0d2ea36a2e3f4b47992aea9cc0c18c5ba7e0ff3 | 51 |
import uuid
def get_uuid_from_str(input_id: str) -> str:
"""
Returns an uuid3 string representation generated from an input string.
:param input_id:
:return: uuid3 string representation
"""
return str(uuid.uuid3(uuid.NAMESPACE_DNS, input_id)) | 51ce9ceab7c4f9d63d45fbee93286711bcba3093 | 53 |
def createList(value, n):
"""
@param value: value to initialize the list
@param n: list size to be created
@return: size n list initialized to value
"""
return [value for i in range (n)] | ff419e6c816f9b916a156e21c68fd66b36de9cfb | 54 |
def heur(puzzle, item_total_calc, total_calc):
"""
Heuristic template that provides the current and target position for each number and the
total function.
Parameters:
puzzle - the puzzle
item_total_calc - takes 4 parameters: current row, target row, current col, target col.
Returns int.
total_calc - takes 1 parameter, the sum of item_total_calc over all entries, and returns int.
This is the value of the heuristic function
"""
t = 0
for row in range(3):
for col in range(3):
val = puzzle.peek(row, col) - 1
target_col = val % 3
target_row = val / 3
# account for 0 as blank
if target_row < 0:
target_row = 2
t += item_total_calc(row, target_row, col, target_col)
return total_calc(t) | bed67110858733a20b89bc1aacd6c5dc3ea04e13 | 56 |
def make_argparse_help_safe(s):
"""Make strings safe for argparse's help.
Argparse supports %{} - templates. This is sometimes not needed.
Make user supplied strings safe for this.
"""
return s.replace('%', '%%').replace('%%%', '%%') | 3a1e6e072a8307df884e39b5b3a0218678d08462 | 57 |
from typing import Tuple
def decimal_to_boolean_list(num: int, padding: int = 0) -> Tuple[bool, ...]:
"""
Convert a decimal number into a tuple of booleans, representing its binary value.
"""
# Convert the decimal into binary
binary = bin(num).replace('0b', '').zfill(padding)
# Return a tuple of booleans, one for each element of the binary number (it's either '0' or '1' so we can convert
# directly to boolean)
return tuple(char == '1' for char in binary) | c13831214faece847960089f781cc1c6442205ec | 62 |
def tpack(text, width=100):
"""Pack a list of words into lines, so long as each line (including
intervening spaces) is no longer than _width_"""
lines = [text[0]]
for word in text[1:]:
if len(lines[-1]) + 1 + len(word) <= width:
lines[-1] += (' ' + word)
else:
lines += [word]
return lines | e1b1b54a528c8dc2142a750156d3db1f754b4268 | 63 |
def is_palindrome(s: str) -> bool:
"""Return whether a string is a palindrome
This is as efficient as you can get when computing whether a string is a
palindrome. It runs in O(n) time and O(1) space.
"""
if len(s) <= 1:
return True
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True | 6d3001486fe3603a17e72861e3bdea495cd675c1 | 68 |
def reverse(password, position_x, position_y):
"""Reverse from position_x to position_y in password."""
password_slice = password[position_x:position_y + 1]
password[position_x:position_y + 1] = password_slice[::-1]
return password | 46fec2c6b9c02d8efa71d53451974e46cbe68102 | 70 |
def GetBoolValueFromString(s):
"""Returns True for true/1 strings, and False for false/0, None otherwise."""
if s and s.lower() == 'true' or s == '1':
return True
elif s and s.lower() == 'false' or s == '0':
return False
else:
return None | d6ef53e837fc825a32e073e3a86185093dd1d037 | 71 |
def get_typical_qualifications(cfg):
"""
create qualification list to filter just workers with:
- + 98% approval rate
- + 500 or more accepted HIT
- Location USA
:param cfg:
:return:
"""
if not cfg['hit_type'].getboolean('apply_qualification'):
return []
qualification_requirements=[
{
# Worker_NumberHITsApproved
'QualificationTypeId': '00000000000000000040',
'Comparator': 'GreaterThanOrEqualTo',
'IntegerValues': [
500,
],
'RequiredToPreview': False,
'ActionsGuarded': 'Accept'
}, {
# Worker_PercentAssignmentsApproved
'QualificationTypeId': '000000000000000000L0',
'Comparator': 'GreaterThanOrEqualTo',
'IntegerValues': [
98,
],
'RequiredToPreview': False,
'ActionsGuarded': 'Accept'
}, {
# Worker_Locale
'QualificationTypeId': '00000000000000000071',
'Comparator': 'EqualTo',
'LocaleValues': [
{
'Country':"US"
}
],
'RequiredToPreview': False,
'ActionsGuarded': 'Accept'
},
]
return qualification_requirements | 4cfad92d7c2587e2fce1caeac032a69f87c70c01 | 73 |
def _tear_down_response(data):
"""Helper function to extract header, payload and end from received response
data."""
response_header = data[2:17]
# Below is actually not used
response_payload_size = data[18]
response_payload = data[19:-2]
response_end = data[-2:]
return response_header, response_payload, response_end | 0c9684c2c054beaff018f85a6775d46202d0095a | 81 |
def isText(node):
"""
Returns True if the supplied node is free text.
"""
return node.nodeType == node.TEXT_NODE | 150efc016028d0fab4630ad5e754ebaeed0c82c0 | 83 |
def scale_y_values(y_data, y_reference, y_max):
"""
Scale the plot in y direction, to prevent extreme values.
:param y_data: the y data of the plot
:param y_reference: the maximum value of the plot series (e.g. Normal force), which will be scaled to y_max
:param y_max: the maximum y value for the plot (e.g. if y_max=1, no y value in the plot will be greater than 1)
"""
multipl_factor = y_max / y_reference
for i in range(len(y_data)):
y_data[i] = y_data[i] * multipl_factor
return y_data, multipl_factor | b3b22b0f868ce46926a4eecfc1c5d0ac2a7c1f7e | 87 |
def set_heating_contribution(agent, pv_power):
""" If the water tank is currently in use, compute and return the part of the pv_power used for heating the water"""
pv_power_to_heating = 0
if agent.water_tank.is_active():
pv_power_to_heating = pv_power * agent.pv_panel.heating_contribution
return pv_power_to_heating | ece29b7f0fbbe10907ada8fd1450919f01ab74c3 | 88 |
def deep_len(lnk):
""" Returns the deep length of a possibly deep linked list.
>>> deep_len(Link(1, Link(2, Link(3))))
3
>>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4))))
4
>>> levels = Link(Link(Link(1, Link(2)), \
Link(3)), Link(Link(4), Link(5)))
>>> print(levels)
<<<1 2> 3> <4> 5>
>>> deep_len(levels)
5
"""
if not lnk:
return 0
if type(lnk.first) == int:
return 1 + deep_len(lnk.rest)
return deep_len(lnk.first) + deep_len(lnk.rest) | d8a33600085e51b181752b2dd81d5bcdae7aaff9 | 95 |
import math
def pixel_distance(A, B):
"""
In 9th grade I sat in geometry class wondering "when then hell am I
ever going to use this?"...today is that day.
Return the distance between two pixels
"""
(col_A, row_A) = A
(col_B, row_B) = B
return math.sqrt(math.pow(col_B - col_A, 2) + math.pow(row_B - row_A, 2)) | 64853c44400428c8040ae47d1cc2cca17aed0a5f | 101 |
def match_piecewise(candidates: set, symbol: str, sep: str='::') -> set:
"""
Match the requested symbol reverse piecewise (split on ``::``) against the candidates.
This allows you to under-specify the base namespace so that ``"MyClass"`` can match ``my_namespace::MyClass``
Args:
candidates: set of possible matches for symbol
symbol: the symbol to match against
sep: the separator between identifier elements
Returns:
set of matches
"""
piecewise_list = set()
for item in candidates:
split_symbol = symbol.split(sep)
split_item = item.split(sep)
split_symbol.reverse()
split_item.reverse()
min_length = len(split_symbol)
split_item = split_item[:min_length]
if split_symbol == split_item:
piecewise_list.add(item)
return piecewise_list | 1c6d7240365ef22f753aa4195cfb5e879fc453e0 | 105 |
def kev_to_wavelength(kev):
"""Calculate the wavelength from kev"""
lamda = 12.3984 / kev #keV to Angstrom
return lamda | cfb3126e56bc0890dd8cf2caa50a240b380dad56 | 107 |
def CalculateOSNames(os_name, os_variants):
"""Calculates all the names an OS can be called, according to its variants.
@type os_name: string
@param os_name: base name of the os
@type os_variants: list or None
@param os_variants: list of supported variants
@rtype: list
@return: list of valid names
"""
if os_variants:
return ["%s+%s" % (os_name, v) for v in os_variants]
else:
return [os_name] | 5689ed7da55cec929045e95344c60e7a06af711d | 108 |
def pad(data, pad_id):
""" Pad all lists in data to the same length. """
width = max(len(d) for d in data)
return [d + [pad_id] * (width - len(d)) for d in data] | a0951f4332879600d25c061cf1c553126d6df8d2 | 109 |
def dropannotation(annotation_list):
"""
Drop out the annotation contained in annotation_list
"""
target = ""
for c in annotation_list:
if not c == "#":
target += c
else:
return target
return target | 9f4a695eaf80f79dce943f2f91926d9c823483b6 | 111 |
def read_test_case(file_path):
"""
reads one test case from file.
returns contents of test case
Parameters
----------
file_path : str
the path of the test case file to read.
Returns
-------
list
a list of contents of the test case.
"""
file = open(file_path, "r")
number = int(file.readline().strip())
case = list()
for i in range(number):
case.append(file.readline().strip())
file.close()
return case | 6a87ff979d0b1ccf838ebef56401a48760711541 | 114 |
import torch
def accuracy4batch(model, testloader, criterion):
"""save a model checkpoint
INPUT:
model: pytorch nn model.
testloader: DataLoader. test data set
criterion: criterion. loss criterion
device: torch.device. device on which model/data is based
OUTPUT:
accuracy: float in [0:1]. percenct proportion of correct classifications in testloader
test_loss: float. absolute error
"""
test_loss = 0
accuracy = 0
model.eval()
with torch.no_grad():
for inputs, labels in testloader:
inputs, labels = inputs.to(model.device), labels.to(model.device)
logps = model.forward(inputs)
batch_loss = criterion(logps, labels)
test_loss += batch_loss.item()
# Calculate accuracy
ps = torch.exp(logps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
accuracy = accuracy/len(testloader)
return accuracy, test_loss | 2005984b94f17bf601034953bbea3dca6542143d | 115 |
def clean_string(s: str) -> str:
"""Cleans and returns an input string
>>> clean_string(" xYz ")
'XYZ'
"""
return str(s).strip().upper() | c97281505492ded5b9167076312959c5eee41a6c | 124 |
def XOR(v1, v2):
"""
XOR operation element by element from 2 lists
:param v1: [1, 0, 1, 0, 0, 1]
:param v2: [1, 1, 0, 0, 1, 1]
:return: [0, 1, 1, 0, 1, 0]
"""
return [a ^ b for a, b in zip(v1, v2)] | e3b94b35ccf4e1dd99cc51f32c70f96c5fe99795 | 125 |
def get_dayofweek(date):
"""
Returns day of week in string format from date parameter (in datetime format).
"""
return date.strftime("%A") | 4a0f728733870998331ea6f796b167b9dd3276ab | 126 |
import re
def sortRules(ruleList):
"""Return sorted list of rules.
Rules should be in a tab-delimited format: 'rule\t\t[four letter negation tag]'
Sorts list of rules descending based on length of the rule,
splits each rule into components, converts pattern to regular expression,
and appends it to the end of the rule. """
ruleList.sort(key = len, reverse = True)
sortedList = []
for rule in ruleList:
s = rule.strip().split('\t')
splitTrig = s[0].split()
trig = r'\s+'.join(splitTrig)
pattern = r'\b(' + trig + r')\b'
s.append(re.compile(pattern, re.IGNORECASE))
sortedList.append(s)
return sortedList | 5b98903fd48f562d22e0ce269aa55e52963fa4a9 | 132 |
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(4, True),
(5, None),
(6, None),
(7, False),
(8, False),
(9, False),
]
"""
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
else:
lines.append((prev_lineno, None))
lines.append((lineno, status))
prev_lineno = lineno
prev_status = status
return lines | e7685359f570ae979f2421c3a64513409b9df352 | 140 |
def extract_mesh_descriptor_id(descriptor_id_str: str) -> int:
""" Converts descriptor ID strings (e.g. 'D000016') into a number ID (e.g. 16). """
if len(descriptor_id_str) == 0:
raise Exception("Empty descriptor ID")
if descriptor_id_str[0] != "D":
raise Exception("Expected descriptor ID to start with 'D', {}".format(descriptor_id_str))
return int(descriptor_id_str[1:]) | 9f013eadee9a149b9617e4a1c058bbe67c6dd8ba | 141 |
def lerp(x0, x1, t):
""" Linear interpolation """
return (1.0 - t) * x0 + t * x1 | 82d9ce36dd5879c7aab64dc5615a2fb298471383 | 143 |
from typing import Optional
from typing import List
def _check_str_input(var, input_name: str, valid_options: Optional[List[str]] = None) -> str:
"""
_check_str_input
Convenience function to check if an input is a string. If argument valid_options is given, this
function will also check that var is a valid option from the valid_options specified.
Parameters
----------
var
the input variable to check
input_name : str
the name of the variable to include if an error is raised
valid_options: List[str], optional
a list of valid options for var
Returns
-------
str
the input var after lowering ans stripping the string
"""
if not isinstance(var, str):
raise ValueError("Invalid input {0} for {1}. Input {1} must be a string.".format(
var, input_name))
var = var.strip().lower()
if valid_options is not None:
valid_options = [option.strip().lower() for option in valid_options]
if var not in valid_options:
raise ValueError("Invalid input {0} for {1}. Input {1} must be one of the following "
"options: {2}.".format(var, input_name, valid_options))
return var | 357a8516fe65dddb35b7799ddc68b892da75ea02 | 147 |
def ps(s):
"""Process String: convert a string into a list of lowercased words."""
return s.lower().split() | 9bf25b31d00544d96f96564ce67ff5def9a16348 | 156 |
from typing import Optional
def binary_search(pool: list, target) -> Optional[int]:
"""Search for a target in a list, using binary search.
Args:
pool (list): a pool of all elements being searched.
target: the target being searched.
Returns:
int: the index of the target.
"""
sorted_pool = sorted(pool)
low = 0
high = len(sorted_pool) - 1
while low + 1 != high:
mid = (low + high) // 2
if sorted_pool[mid] == target:
return mid
if sorted_pool[mid] < target:
low = mid
else:
high = mid
return None | 7e7ef70126e02b3dc706b3b88bd950aa6322904e | 158 |
def is_rotation(first, second):
"""Given two strings, is one a rotation of the other."""
if len(first) != len(second):
return False
double_second = second + second
return first in double_second | f02576761014e1dc395f88f937dfdd0de15508d2 | 159 |
def bin_entities(uri_set, delimiter="/", splitpos=-1):
""" Takes iteratable elemts and splits them according to the position
(splitpos) of the delimiter. The first part is used as a key,
whereas the second appended to a list connected to the former key.
return: dict {key1: [id11, id12, id13, …], key2: […}}
"""
ent_dict = dict()
for res in uri_set:
# split entity up to splitpos using delimiter
entity = delimiter.join(res.split(delimiter)[:splitpos])
# id_ is the remainder
id_ = delimiter.join(res.split(delimiter)[splitpos:])
if entity in ent_dict:
ent_dict[entity].append(id_)
else:
ent_dict[entity] = [id_]
return ent_dict | fcbcddbff909d74fe14fe7cb3a21560c8ca9549a | 160 |
def display_timestamp(num_seconds):
"""get a string to conveniently display a timestamp"""
seconds = num_seconds % 60
minutes = int(num_seconds / 60) % 60
hrs = int(num_seconds / 3600)
return "{}:{}:{}".format(hrs, minutes, seconds) | bdcc34ade38855df910d5005f6dac9b5e826f543 | 161 |
def filename(config, key, ext = '.h5', set = ''):
"""
Get the real file name by looking up the key in the config and suffixing.
:param key: key to use in the config
:type key: str
:param ext: extension to use
:type ext: str
:param set: set name
:type set: str
:return: filepath
:rtype: str
"""
name = config[key] + '_'
if set:
name += set + '_'
name += str(config['multiplier']) + '_' + str(config['height']) + 'x' + str(config['width']) + 'x' + str(config['depth'])\
if ext:
name += ext
return name | f389a48e7e06a31722423857814149f474e46316 | 162 |
def get_urls(page_links):
"""Insert page links, return list of url addresses of the json"""
urls = []
for link in page_links:
link1 = link.replace('v3', 'VV')
game_id = ''.join([char for char in link1 if char in list(map(str, list(range(10))))])
json_url = f'http://www.afa.com.ar/deposito/html/v3/htmlCenter/data/deportes/futbol/primeraa/events/{game_id}.json'
urls.append(json_url)
return urls | 68c6796ad5a77676674252a0060776eabc4fb8e0 | 166 |
def Weekday(datetime):
"""Returns a weekday for display e.g. Mon."""
return datetime.strftime('%a') | bae413f0fa86f9e27bd6d7f6ee4480a6ddd564e7 | 168 |
def FlowBalance_rule(model, node):
"""Ensures that flows into and out of a node are equal
"""
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.NodesIn[node]) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.NodesOut[node]) \
== 0 | 628e8e2bb6967c9114dfcb8ea449d760180ab206 | 170 |
def rrange(x, y = 0):
""" Creates a reversed range (from x - 1 down to y).
Example:
>>> rrange(10, 0) # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
"""
return range(x - 1, y - 1, -1) | 37c41673dab3fca797f4f6f0ab2f8160e7650248 | 172 |
import math
def col_round(x):
"""
As Python 3 rounds 0.5 fraction to closest even,
floor and cell round methods used here to round 0.5
up to next digit and 0.4 down back to previos.
"""
frac = x - math.floor(x)
if frac < 0.5:
return math.floor(x)
return math.ceil(x) | 3f21a6dcc525daebf78c9adfd6afee9ba865399b | 175 |
def get_best_response_actions_as_string(best_response_actions):
"""Turns a dict<bytes, int> into a bytestring compatible with C++.
i.e. the bytestring can be copy-pasted as the brace initialization for a
{std::unordered_,std::,absl::flat_hash_}map<std::string, int>.
Args:
best_response_actions: A dict mapping bytes to ints.
Returns:
A bytestring that can be copy-pasted to brace-initialize a C++
std::map<std::string, T>.
"""
best_response_keys = sorted(best_response_actions.keys())
best_response_strings = [
"%s: %i" % (k, best_response_actions[k]) for k in best_response_keys
]
return "{%s}" % (", ".join(best_response_strings)) | cf2b475d6bb76d262c17dc7753f1624e38cc69f4 | 178 |
def build_genome(tree, genome):
"""
Goes through a tree and builds a genome from all codons in the subtree.
:param tree: An individual's derivation tree.
:param genome: The list of all codons in a subtree.
:return: The fully built genome of a subtree.
"""
if tree.codon:
# If the current node has a codon, append it to the genome.
genome.append(tree.codon)
for child in tree.children:
# Recurse on all children.
genome = child.build_genome(genome)
return genome | 67fd7a23a9ca812717bde5d3e35affc5cc7474f4 | 179 |
def diff_pf_potential(phi):
""" Derivative of the phase field potential. """
return phi**3-phi | c22af096d27cf817ffee683453ecafb4e5c61cdc | 186 |
def resolve_alias(term: str) -> str:
"""
Resolves search term aliases (e.g., 'loc' for 'locations').
"""
if term in ("loc", "location"):
return "locations"
elif term == "kw":
return "keywords"
elif term == "setting":
return "setting"
elif term == "character":
return "characters"
else:
return term | 8080d6ffb73457fd61aeca610b30b18695ec01bd | 188 |
def add_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standadized_layers."""
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparams.mode
# hparams.hidden_size
# Pre-post processing flags
# hparams.layer_preprocess_sequence
# hparams.layer_postprocess_sequence
# hparams.layer_prepostprocess_dropout
# hparams.norm_type
# hparams.norm_epsilon
# Mixture-of-Expert flags
# hparams.moe_hidden_sizes
# hparams.moe_num_experts
# hparams.moe_k
# hparams.moe_loss_coef
# Attention layers flags
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("attention_key_channels", 0)
hparams.add_hparam("attention_value_channels", 0)
hparams.add_hparam("attention_dropout", 0.0)
# Attention: Local
hparams.add_hparam("attention_loc_block_length", 256)
# Attention: Local (unmasked only): How much to look left.
hparams.add_hparam("attention_loc_block_width", 128)
# Attention: Memory-compressed
hparams.add_hparam("attention_red_factor", 3)
hparams.add_hparam("attention_red_type", "conv")
hparams.add_hparam("attention_red_nonlinearity", "none")
# Fully connected layers flags
# To be more consistent, should use filter_size to also control the MOE
# size if moe_hidden_sizes not set.
hparams.add_hparam("filter_size", 2048)
hparams.add_hparam("relu_dropout", 0.0)
return hparams | de9f1a3b30a105a89d3400ca0b36e4c747f1ab46 | 198 |
def Storeligandnames(csv_file):
"""It identifies the names of the ligands in the csv file
PARAMETERS
----------
csv_file : filename of the csv file with the ligands
RETURNS
-------
lig_list : list of ligand names (list of strings)
"""
Lig = open(csv_file,"rt")
lig_aux = []
for ligand in Lig:
lig_aux.append(ligand.replace(" ","_").replace("\n","").lower())
return lig_aux | dc4510a4ea946eaf00152cb445acdc7535ce0379 | 199 |
import requests
import logging
def upload(filename, url, token=None):
"""
Upload a file to a URL
"""
headers = {}
if token:
headers['X-Auth-Token'] = token
try:
with open(filename, 'rb') as file_obj:
response = requests.put(url, data=file_obj, timeout=120, headers=headers, verify=False)
except requests.exceptions.RequestException as err:
logging.warning('RequestException when trying to upload file %s: %s', filename, err)
return None
except IOError as err:
logging.warning('IOError when trying to upload file %s: %s', filename, err)
return None
if response.status_code == 200 or response.status_code == 201:
return True
return None | eb8a8060294322bd9df187c8076d8f66b4dc775c | 202 |
def flatmap(fn, seq):
"""
Map the fn to each element of seq and append the results of the
sublists to a resulting list.
"""
result = []
for lst in map(fn, seq):
for elt in lst:
result.append(elt)
return result | c42d07f712a29ece76cd2d4cec4f91ec2562a1c0 | 203 |
def DefaultTo(default_value, msg=None):
"""Sets a value to default_value if none provided.
>>> s = Schema(DefaultTo(42))
>>> s(None)
42
"""
def f(v):
if v is None:
v = default_value
return v
return f | 10401d7214d15c2b0bf28f52430ef71b5df0a116 | 207 |
import re
from typing import Literal
def extract_text(
pattern: re.Pattern[str] | str,
source_text: str,
) -> str | Literal[False]:
"""Match the given pattern and extract the matched text as a string."""
match = re.search(pattern, source_text)
if not match:
return False
match_text = match.groups()[0] if match.groups() else match.group()
return match_text | a6f762cfd26dd1231db4b6e88247e2566d186212 | 208 |
import torch
def rotate_tensor(l: torch.Tensor, n: int = 1) -> torch.Tensor:
"""Roate tensor by n positions to the right
Args:
l (torch.Tensor): input tensor
n (int, optional): positions to rotate. Defaults to 1.
Returns:
torch.Tensor: rotated tensor
"""
return torch.cat((l[n:], l[:n])) | 9cdaa7be718f0676ad85e05b01ee918459697c60 | 210 |
def grelha_nr_colunas(g):
"""
grelha_nr_colunas: grelha --> inteiro positivo
grelha_nr_colunas(g) devolve o numero de colunas da grelha g.
"""
return len(g[0]) | 740b06c186ad1455aecadfaf112f253fb434d5ff | 214 |
def readFile(sFile, sMode = 'rb'):
"""
Reads the entire file.
"""
oFile = open(sFile, sMode);
sRet = oFile.read();
oFile.close();
return sRet; | d44e8217ae7dcab1c826ccbbe80e066d76db31b5 | 215 |
import re
def clean_text_from_multiple_consecutive_whitespaces(text):
"""Cleans the text from multiple consecutive whitespaces, by replacing these with a single whitespace."""
multi_space_regex = re.compile(r"\s+", re.IGNORECASE)
return re.sub(multi_space_regex, ' ', text) | f25b27da070d6a984012a4cb5b1ae4a477713033 | 220 |
def plasma_parameter(N_particles, N_grid, dx):
"""
Estimates the plasma parameter as the number of particles per step.
Parameters
----------
N_particles : int, float
Number of physical particles
N_grid : int
Number of grid cells
dx : float
grid step size
"""
return (N_particles / N_grid) * dx | 51d3b96ccba2689db461fd6117cb5c2961dc3812 | 224 |
import bz2
import gzip
import json
def load_json(filename):
"""
Load a JSON file that may be .bz2 or .gz compressed
"""
if '.bz2' in filename:
with bz2.open(filename, 'rt') as infile:
return json.load(infile)
elif '.gz' in filename:
with gzip.open(filename, 'rt') as infile:
return json.load(infile)
else:
with open(filename, 'rt') as infile:
return json.load(infile) | 1b985db386e85c3b8e87911d89a7652133bfee7b | 228 |
def rescale(img, thresholds):
"""
Linear stretch of image between two threshold values.
"""
return img.subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) | 76d5f56384f408e57161848ded85142e68296258 | 235 |
def transform(nodes, fxn, *args, **kwargs):
"""
Apply an arbitrary function to an array of node coordinates.
Parameters
----------
nodes : numpy.ndarray
An N x M array of individual node coordinates (i.e., the
x-coords or the y-coords only)
fxn : callable
The transformation to be applied to the whole ``nodes`` array
args, kwargs
Additional positional and keyword arguments that are passed to
``fxn``. The final call will be ``fxn(nodes, *args, **kwargs)``.
Returns
-------
transformed : numpy.ndarray
The transformed array.
"""
return fxn(nodes, *args, **kwargs) | edc487b7f1b83f750f868ee446ecf2676365a214 | 238 |
from typing import Dict
from typing import Any
import yaml
def as_yaml(config: Dict[str, Any], **yaml_args: Any) -> str:
"""Use PyYAML library to write YAML file"""
return yaml.dump(config, **yaml_args) | 28c792504d7a6ccd7dbf040d516343e44e072b16 | 240 |
def prepend_with_baseurl(files, base_url):
"""prepend url to beginning of each file
Parameters
------
files (list): list of files
base_url (str): base url
Returns
------
list: a list of files with base url pre-pended
"""
return [base_url + file for file in files] | 4c29b3e9230239c1ff8856c707253608ce2503cd | 247 |
def get_bounding_box(dataframe, dataIdentifier):
"""Returns the rectangle in a format (min_lat, max_lat, min_lon, max_lon)
which bounds all the points of the ´dataframe´.
Parameters
----------
dataframe : pandas.DataFrame
the dataframe with the data
dataIdentifier : DataIdentifier
the identifier of the dataframe to be used
"""
b_box = (getattr(dataframe, dataIdentifier.latitude).min(),
getattr(dataframe, dataIdentifier.latitude).max(),
getattr(dataframe, dataIdentifier.longitude).min(),
getattr(dataframe, dataIdentifier.longitude).max())
return b_box | 6989118af8db36cc38fd670f5cd7506859d2150e | 249 |
def stat_cleaner(stat: str) -> int:
"""Cleans and converts single stat.
Used for the tweets, followers, following, and likes count sections.
Args:
stat: Stat to be cleaned.
Returns:
A stat with commas removed and converted to int.
"""
return int(stat.replace(",", "")) | cb6b6035ab21871ca5c00d5d39d9efe87e0acc89 | 250 |
def module_for_category( category ):
"""Return the OpenGL.GL.x module for the given category name"""
if category.startswith( 'VERSION_' ):
name = 'OpenGL.GL'
else:
owner,name = category.split( '_',1)
if owner.startswith( '3' ):
owner = owner[1:]
name = 'OpenGL.GL.%s.%s'%( owner,name )
return __import__( name, {}, {}, name.split( '.' )) | 0e88467a1dd7f5b132d46a9bdc99765c274f69f3 | 255 |
import shutil
def cp_dir(src_dir, dest_dir):
"""Function: cp_dir
Description: Copies a directory from source to destination.
Arguments:
(input) src_dir -> Source directory.
(input) dest_dir -> Destination directory.
(output) status -> True|False - True if copy was successful.
(output) err_msg -> Error message from copytree exception or None.
"""
status = True
err_msg = None
try:
shutil.copytree(src_dir, dest_dir)
# Directory permission error.
except shutil.Error as err:
err_msg = "Directory not copied. Perms Error Message: %s" % (err)
status = False
# Directory does not exist.
except OSError as err:
err_msg = "Directory not copied. Exist Error Message: %s" % (err)
status = False
return status, err_msg | 13f82a485fb46e102780c2462f0ab092f0d62df1 | 256 |
def index_wrap(data, index):
"""
Description: Select an index from an array data
:param data: array data
:param index: index (e.g. 1,2,3, account_data,..)
:return: Data inside the position index
"""
return data[index] | 42b53f1d9edf237b904f822c15ad1f1b930aa69c | 268 |
import unicodedata
def simplify_name(name):
"""Converts the `name` to lower-case ASCII for fuzzy comparisons."""
return unicodedata.normalize('NFKD',
name.lower()).encode('ascii', 'ignore') | a7c01471245e738fce8ab441e3a23cc0a67c71be | 270 |
def values(df, varname):
"""Values and counts in index order.
df: DataFrame
varname: strign column name
returns: Series that maps from value to frequency
"""
return df[varname].value_counts().sort_index() | ea548afc8e0b030e441baa54abad32318c9c007f | 273 |
def is_seq(x, step=1):
"""Checks if the elements in a list-like object are increasing by step
Parameters
----------
x: list-like
step
Returns
-------
True if elements increase by step, else false and the index at which the condition is violated.
"""
for i in range(1, len(x)):
if not x[i] == (x[i - 1] + step):
print('Not seq at: ', i)
return False
return True | 032e12b86aa7e50dfba2ddccd244475f58d70b29 | 278 |
def ecio_quality_rating(value, unit):
"""
ECIO (Ec/Io) - Energy to Interference Ratio (3G, CDMA/UMTS/EV-DO)
"""
if unit != "dBm":
raise ValueError("Unsupported unit '{:}'".format(unit))
rating = 0
if value > -2:
rating = 4
elif -2 >= value > -5:
rating = 3
elif -5 >= value > -10:
rating = 2
elif value <= -10:
rating = 1
return rating | 4cc21012464b8476d026f9dfbc35b8b1ea3c2d85 | 279 |
def template_check(value):
"""Check if a rendered template string equals true.
If value is not a string, return value as is.
"""
if isinstance(value, str):
return value.lower() == "true"
return value | 3733db5c107068e815bac079fdef1a450f7acdc9 | 280 |
def return_npc(mcc, mnc):
"""
Format MCC and MNC into a NPC.
:param mcc: Country code.
:type mcc: int
:param mnc: Network code.
:type mnc: int
"""
return "{0}{1}30".format(str(mcc).zfill(3), str(mnc).zfill(3)) | 0ae5952fd7b026c2c90c72046f63ca4d08dacf06 | 281 |
from typing import Callable
import click
def with_input(func: Callable) -> Callable:
"""
Attaches a "source" argument to the command.
"""
return click.argument(
"source", type=click.Path(exists=True), required=True
)(func) | 3117f183ac4e4d459a718b59fc9a3ba00b36e291 | 287 |
def check_loop_validity(inst_list):
""" Given a list of instructions, check whether they can form a valid loop.
This means, checking for anything that could create an infinite loop.
We are also disallowing double loops right now"""
for i, c in enumerate(inst_list):
if c in [5, 6, 16, 25]:
return False, i
return True, -1 | a58923e014947d1406165a831a57b73fcb9ab226 | 288 |
def calc_high_outlier(values) -> float:
"""Calculates the high outlier from a pandas Series"""
q1, q3 = [values.quantile(x, 'midpoint') for x in (0.25, 0.75)]
return q3 + 1.5 * (q3 - q1) | 8ee929aec1cb4af9a90d04893f8f94444d00ad22 | 289 |
from typing import Union
from typing import Dict
from typing import Tuple
from typing import Any
def serialize_framework_build_config(dict_: Union[Dict[str, str], str]) -> Tuple[Any, ...]:
"""Serialize a dict to a hashable tuple.
Parameters
----------
dict_: Dict[str, str]
Returns
-------
hashable_tuple: Tuple[Any, ...]
A hashable tuple.
"""
if isinstance(dict_, dict):
return tuple(sorted(list(dict_.items())))
return (dict_,) | 365b413ff21bf4fb7f5d153dbe74801ee125108f | 291 |
def get_confidence(imgfilename):
"""
1003_c60.jpg -> c6
"""
if not imgfilename:
return ''
return 'c' + imgfilename.split('/')[-1][0:1] | 7c98f2abd2119b41d7e2501823985a894da5a1a1 | 292 |
def min_max_median(lst):
""" a function that takes a simple list of numbers lst as a parameter and returns a list with the min, max, and the median of lst. """
s = sorted(lst)
n = len(s)
return [ s[0], s[-1], s[n//2] if n % 2 == 1 else (s[n//2 - 1] + s[n//2]) / 2] | 59b1ceef5796d77cc039a42593ddb3d1d2244bd7 | 293 |
def _enzyme_path_to_sequence(path, graph, enzymes_sites):
"""Converts a path of successive enzymes into a sequence."""
return "".join(
[enzymes_sites[path[0]]]
+ [graph[(n1, n2)]["diff"] for n1, n2 in zip(path, path[1:])]
) | a3de9de5dc37df641e36d09d07b49c402fa17fd1 | 295 |
import string
def simple_caesar(txt, rot=7):
"""Caesar cipher through ASCII manipulation, lowercase only."""
alphabet = string.ascii_lowercase # pick alphabet
shifted_alphabet = alphabet[rot:] + alphabet[:rot] # shift it
table = str.maketrans(alphabet, shifted_alphabet) # create mapping table
return txt.lower().translate(table) # apply | eb8d86d37d8a8902663ff68e095b3b822225859c | 296 |
def _is_url_without_path_query_or_fragment(url_parts):
"""
Determines if a URL has a blank path, query string and fragment.
:param url_parts: A URL.
:type url_parts: :class:`urlparse.ParseResult`
"""
return url_parts.path.strip('/') in ['', 'search'] and url_parts.query == '' \
and url_parts.fragment == '' | 4bad1f230adfa77df019519db276a181d57682dd | 299 |
def get_colours_extend(graph_size, start_set, end_set, source, target, reachable=None):
"""
Get colours for nodes including source and target nodes.
Blue nodes are those in the source set.
Orange nodes are those in the start set, not in the source set.
Green nodes are those reachable from the source that are in target.
Red nodes are those in target that are not reachable from the source.
All other nodes are grey.
"""
# Setup the colours
c = []
if reachable is None:
reachable = end_set
for acc_val in range(graph_size):
if acc_val in start_set:
if acc_val in source:
c.append("dodgerblue")
else:
c.append("darkorange")
elif acc_val in target:
if acc_val in reachable:
c.append("g")
else:
c.append("r")
else:
c.append("gray")
return c | d366ed6c4c387d0b4de4440d34d358d5a142661a | 301 |
End of preview. Expand
in Dataset Viewer.
Seed dataset utilized for StarCoder2-Instruct's self-alignment pipeline.
- Downloads last month
- 41