content stringlengths 42 6.51k |
|---|
def _extract_geojson_srid(obj):
"""
Extracts the SRID code (WKID code) from geojson. If not found, SRID=4326
:returns: Integer
"""
meta_srid = obj.get('meta', {}).get('srid', None)
# Also try to get it from `crs.properties.name`:
crs_srid = obj.get('crs', {}).get('properties', {}).get('name... |
def factorial(n: int) -> int:
"""Computes n!"""
result = 1
for i in range (1, n + 1):
result *= i
return result |
def pretty_cmd(cmd):
"""Print task command in a pretty way."""
string = cmd[0]
for elm in cmd[1:]:
if elm[0] == "-" and elm[1].isalpha():
string += "\n+ {}".format(elm)
elif elm[0] == "-" and elm[1] == "-" and elm[2].isalpha():
string += "\n+ {}".format(elm)
e... |
def total_ordering(cls): # pragma: no cover
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [
('__gt__', lambda self, other: not (self < other or self == other)),
('__le__', lambda self, other: self < other or self == other),
('__ge_... |
def format_relation(
relation_type: str, start_id: str, end_id: str, **properties) -> dict:
"""Formats a relation."""
relation = {
':TYPE': relation_type,
':START_ID': start_id,
':END_ID': end_id,
}
relation.update(properties)
return relation |
def LineStyle(argument):
"""Dictionary for switching the line style argument"""
switcher = {
'Line': '-',
'Dash': '--',
'DashDot': '-.',
'Dotted': ':'
}
return switcher.get(argument, 'k-') |
def _scale_one_value(
value,
scaled_min,
scaled_max,
global_min,
global_max
):
"""Scale value to the range [scaled_min, scaled_max]. The min/max
of the sequence/population that value comes from are global_min and
global_max.
Parameters
----------
... |
def to_bool(string):
"""Convert string value of true/false to bool"""
return string.upper() == "TRUE" |
def TruncateInSpace(labText,maxLenLab):
"""
This truncates a string to a given length but tries to cut
at a space position instead of splitting a word.
"""
if len( labText ) > maxLenLab:
idx = labText.find(" ",maxLenLab)
# sys.stderr.write("idx=%d\n"%idx)
if idx < 0:
idx = maxLenLab
# BEWARE: This mus... |
def make_iterable(values, collection=None):
"""
converts the provided values to iterable.
it returns a collection of values using the given collection type.
:param object | list[object] | tuple[object] | set[object] values: value or values to make
... |
def __pos__(self) :
"""Return self"""
return self; |
def whether_existing(gram, phrase2index, tot_phrase_list):
"""If :
gram not in phrase2index,
Return : not_exist_flag
Else :
Return : index already in phrase2index.
"""
if gram in phrase2index:
index = phrase2index[gram]
return index
else:
index = len(... |
def defval(val, default=None):
"""
Returns val if is not None, default instead
:param val:
:param default:
:return:
"""
return val if val is not None else default |
def initialize_distribution(states, actions):
"""
initialize a distribution memory
:param states: a list of states
:param actions: a list of actions
:return: a dictionary to record values
"""
dist = {}
for i in states:
dist[i] = {}
for j in actions:
dist[i][j... |
def mySortNum(L):
"""Purpose: to sort a list of lists
Parameters: the list in question
Return: A sorted list"""
n = len(L)
if n == 0:
return L
x = L[0]
L1 = []
L2 = []
L3 = []
for i in range(1, n):
if L[i][1] < x[1]:
L1.append(L[i])
... |
def _normalize_number(number, intmax):
""" Return 0.0 <= number <= 1.0 or None if the number is invalid. """
if isinstance(number, float) and 0.0 <= number <= 1.0:
return number
elif isinstance(number, int) and 0 <= number <= intmax:
return number / intmax
return None |
def hex2rgb(hx):
"""
transform 6-digit hex number into [r,g,b] integers
:param hx:
:return:
"""
assert len(hx) == 6
rgb = []
for r in range(3):
ss = "0x" + hx[2 * r: 2 * r + 2]
rr = int(ss, 16)
rgb.append(rr)
return rgb |
def first_non_repeating_letter(string: str) -> str:
"""
A function named first_non_repeating_letter that
takes a string input, and returns the first
character that is not repeated anywhere in the string.
:param string:
:return:
"""
result = ''
string_lower = string.lower()
for i... |
def cnvrt(val: str) -> str:
"""Convert special XML characters into XML entities."""
val = str(val)
val = val.replace("&", "&")
val = val.replace('"', """)
val = val.replace("'", "'")
val = val.replace("<", "<")
val = val.replace(">", ">")
return val |
def quick_sorted(items):
"""Return a list of all items, in non-decreasing order."""
# Base case: the empty list is already sorted.
if items == []:
return []
# Reduction step: take the first item (call it the pivot)
# and put the remaining items in two partitions,
# those smaller or equal... |
def get_move(old_i, new_i):
"""
Returns a string corresponding to the move between two positions of a tile
old_i: a tuple representing the old index of the tile
new_i: a tuple representing the new index of the tile
"""
dx = new_i[0] - old_i[0]
dy = new_i[1] - old_i[1]
... |
def transform_sheet_data(sheet_data):
"""Do anything to change how the data will appear on the spreadsheet. Each key in the dictionary represents a different column"""
try:
transformed = {}
for k, v in sheet_data.items():
transformed[k] = v
return transformed
except Excep... |
def B_0(phi_0, m, om, N):
"""Buoyancy perturbation amplitude. Wavenumber and frequency should be in
angular units."""
return (1j*m*N**2/(N**2 - om**2))*phi_0 |
def chooseSize(string):
"""
Determines appropriate latex size to use so that the string fits in RAVEN-standard lstlisting examples
without flowing over to newline. Could be improved to consider the overall number of lines in the
string as well, so that we don't have multi-page examples very often.
... |
def ResolveSubnetURI(project, region, subnet, resource_parser):
"""Resolves the URI of a subnet."""
if project and region and subnet and resource_parser:
return str(
resource_parser.Parse(
subnet,
collection='compute.subnetworks',
params={
'project': p... |
def parse_magic_invocation(line):
"""
Parses the magic invocation for the commands
As a general rule we want to forward the arguments to sfdx
But we also need to pass the variable to capture the results
%%sfdx:cmd {var?} {...options}
"""
args = {"variable": None, "sfdx_args": ""}
lin... |
def getDivisors(intVal):
"""returns the integer divisors of intVal"""
ret = []
for i in range(1,intVal//2+1):
if(intVal % i == 0):
ret.append(i)
return ret |
def map_or(func, obj):
""" Applies func to obj if it is not None. """
if obj is None:
return obj
return func(obj) |
def get_extension_id(arg):
"""
Return the extension id from the given console argument
:param arg: The console argument
:return: The extension id
"""
if arg.startswith('http://'):
arg = arg.replace('http://', 'https://')
if arg.startswith('https://'):
return arg.split('/')... |
def get_seconds(d=0, h=0, m=0, s=0, ms=0):
"""
Converts inputs to seconds.
:param d: Days.
:param h: Hours.
:param m: Minutes.
:param s: Seconds.
:param ms: Milliseconds.
:return: float representing seconds.
"""
if (d, h, m, s) == (0, 0, 0):
raise Exception("Cannot retu... |
def message_type_to_notification_class(flash_message_category):
"""Map a Flask flash message category to a Bulma notification CSS class.
See https://bulma.io/documentation/elements/notification/ for the list of
Bulma notification states.
"""
return {"info": "is-info", "success": "is-success", "warn... |
def is_number(s):
"""
Check whether string is a number.
Plazy version: 0.1.4+
Parameters
----------
s : str
String to check.
Keyword Arguments
-----------------
Returns
-------
out : bool
Examples
--------
.. code-block:: python
:linenos:
... |
def subclasses_wrapper(klass):
"""Wrapper around __subclass__ as it is not as easy as it should."""
method = getattr(klass, '__subclasses__', None)
if method is None:
return []
try:
return method()
except TypeError:
try:
return method(klass)
except TypeErr... |
def fresnel_t(pol, kz1, kz2, n1, n2):
"""Fresnel transmission coefficient.
Args:
pol (int): polarization (0=TE, 1=TM)
kz1 (float or array): incoming wave's z-wavenumber (k*cos(alpha1))
kz2 (float or array): transmitted wave's z-wavenumber (k*cos(alpha2))
n1 (flo... |
def countIndent(string):
"""
Finds how many spaces are in a string before alpanumeric characters appear
"""
spaces = 0
for c in string:
if c == " ":
spaces += 1
else:
break
return spaces |
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type(
"""
import re
import unicodedata
from six import text_type
value = text_type(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignor... |
def nullish_coalescing(value, default):
"""
nullish coalescing utility call
Provides a return of the provided value unless the value is a ``None``,
which instead the provided default value is returned instead.
Args:
value: the value
default: the default value
Returns:
... |
def coluna_para_num(col):
"""
coluna_para_num: string -> inteiro
Esta funcao recebe uma string que representa uma das tres colunas do
tabuleiro e devolve o numero da coluna, contando da esquerda para a direita.
"""
col_num = {
'a': 1,
'b': 2,
'c': 3
}
... |
def IsLicenseFile(name):
"""Returns true if name looks like a license file."""
return name in ['LICENSE', 'LICENSE.md', 'COPYING', 'COPYING.txt'] |
def append_list_comprehension(n):
"""
>>> append_list_comprehension(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
return [i for i in range(n)] |
def reverse_transform_values(transform_list: list) -> list:
"""Changes the values for all transforms in the list so the result is equal to the reverse transform
:param transform_list: List of transforms to be turned into a flow field, where each transform is expressed as
a list of [transform name, tran... |
def compare_measure_bounding_boxes(self, other):
"""Compares bounding boxes of two measures and returns which one should come first"""
if self['left'] >= other['left'] and self['top'] >= other['top']:
return +1 # self after other
elif self['left'] < other['left'] and self['top'] < other['top']:
... |
def _node_merge_dict(primary_label, primary_key, nodes):
""" Convert a set of :class:`.Node` objects into a dictionary of
:class:`.Node` lists, keyed by a 3-tuple of
(primary_label, primary_key, frozenset(labels)).
:param primary_label:
:param primary_key:
:param nodes:
:return: dict of (p_... |
def to_kwargs_str(in_dict):
"""Transforms a dictionary into a string that can be transformed back
via get_kwargs. All values need to be lists.
Parameters
----------
in_dict : dictionary
Returns
-------
str
Keys and values are separated by colon+space ": " .
List items a... |
def list_services(config_dict):
"""
List available services
Args:
config_dict (dict): configuration dictionary
Returns:
list: list of available services
"""
return list(config_dict.keys()) |
def get_total_counts(counts):
"""counts is a dict of dicts"""
return sum([sum(vals.values()) for vals in counts.values()]) |
def tranche99(filt, cutoff=99.6):
"""
return True if the tranche is below 99.6
VQSRTrancheINDEL90.00to99.00
"""
if filt is None: return True
if filt[:4] != "VQSR": return False
try:
return float(filt.split("to")[1]) < cutoff
except:
return False |
def parse_slurm_job_cpus(cpus):
"""Return number of cores allocated on each node in the allocation.
This method parses value of Slurm's SLURM_JOB_CPUS_PER_NODE variable's value.
Args:
cpus (str): the value of SLURM_JOB_CPUS_PER_NODE
Returns:
list (int): the number of cores on each nod... |
def fair_split(A, B):
"""
>>> fair_split([0, 4, -1, 0, 3], [0, -2, 5, 0, 3])
2
>>> fair_split([2, -2, -3, 3], [0, 0, 4, -4])
1
>>> fair_split([3, 2, 6],[4, 1, 6])
0
>>> fair_split([1, 4, 2, -2, 5], [7, -2, -2, 2, 5])
2
"""
fair_count = 0
for ii in range(1,len(A)):
... |
def get_square(x, y, board):
"""
This function takes a board and returns the value at that square(x,y).
"""
return board[x][y] |
def scoreToReputation(score):
"""
Converts score (in number format) to human readable reputation format
:type score: ``int``
:param score: The score to be formatted (required)
:return: The formatted score
:rtype: ``str``
"""
to_str = {
4: 'Critical',
3: '... |
def calculate_adsorption_energy(adsorbed_energy, slab_energy, n_species,
adsorbant_t):
"""Calculates the adsorption energy in units of eV
Parameters
----------
adsorbed_energy : (:py:attr:`float`):
slab energy of slab and adsorbed species from DFT
slab_energy... |
def parse_options(options):
"""Parse the analysis options field to a dictionary."""
ret = {}
for field in options.split(","):
if "=" not in field:
continue
key, value = field.split("=", 1)
ret[key.strip()] = value.strip()
return ret |
def update_quotes(char, in_single, in_double):
"""
Code adapted from:
https://github.com/jkkummerfeld/text2sql-data/blob/master/tools/canonicaliser.py
"""
if char == '"' and not in_single:
in_double = not in_double
elif char == "'" and not in_double:
in_single = not in_single
... |
def _get_request_header(request, header_name, default=''):
"""Helper method to get header values from a request's META dict, if present."""
if request is not None and hasattr(request, 'META') and header_name in request.META:
return request.META[header_name]
else:
return default |
def clean_string(text):
"""
Function for basic cleaning of cruft from strings.
:param text: string text
:return: cleaned string
"""
replacements = {'&': '&', '<': '<', '>': '>'}
for x, y in replacements.items():
text = text.replace(x, y)
return text |
def make_db_entry(run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes):
"""
Linked to indices above.
"""
return [run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes] |
def mapValues( d, f ):
"""Return a new dict, with each value mapped by the given function"""
return dict([ ( k, f( v ) ) for k, v in d.items() ]) |
def create_masks(degree):
"""
Create masks for taking bits from text bytes and
putting them to image bytes.
:param degree: number of bits from byte that are taken to encode text data in audio
:return: mask for a text and a mask for a sample
"""
text_mask = 0b1111111111111111
sample_mas... |
def InvertDict( aDict ):
"""Return an inverse mapping for the given dictionary"""
assert len( set( aDict.values() ) ) == len( aDict )
return dict( ( v, k ) for k, v in aDict.items() ) |
def converttostr(input_seq, seperator):
"""
Desc:
Function to convert List of strings to a string with a separator
"""
# Join all the strings in list
final_str = seperator.join(input_seq)
return final_str |
def fmt_time(s, minimal=True):
"""
Args:
s: time in seconds (float for fractional)
minimal: Flag, if true, only return strings for times > 0, leave rest outs
Returns: String formatted 99h 59min 59.9s, where elements < 1 are left out optionally.
"""
ms = s-int(s)
s = int(s)
i... |
def wait_screen_load(path):
"""
Waits Nation Selection screen to load
:param path: dominions log path
:return: True if load was complete
"""
valid = False
i = 0
while i < 1000000:
try:
with open(path + 'log.txt') as file:
blurb = file.read()
... |
def get_lonlats(transmitters):
"""
Return a list of longitude-latitude pairs (float pairs) representing the locations of the given transmitters.
If ``transmitters`` is empty, then return the empty list.
INPUT:
- ``transmitters``: a list of transmitters of the form output by :func:`read_transmi... |
def skaff_description_get(short: bool=True) -> str:
"""
Returns the description string of the skaff program.
A concise description will be returned if 'short' is set to True; otherwise
the full version is returned instead.
"""
short_description = "An Extensible Project Scaffolding Tool"
long... |
def unprefix(prefix, d, all=False):
"""
Returns a new dict by removing ``prefix`` from keys.
If ``all`` is ``False`` (default) then drops keys without the prefix,
otherwise keeping them.
"""
d1 = dict(d) if all else {}
d1.update((k[len(prefix):], v) for k, v in d.items() if k.startswith(pref... |
def parse_version_tag(version_tag):
"""
:param str version_tag: the version tag.
:return: Given a version tag, return it as a list of ints
:rtype: list[int]
"""
return [int(x) for x in version_tag.lower().replace('v', '').split('.')] |
def getBit(num, n):
"""
Return the nth bit (0-indexed) of num.
"""
shifted = num >> n
return shifted & 1 |
def set_bit(a, order):
""" Set the value of a bit at index <order> to be 1. """
return a | (1 << order) |
def HexToByte( hexStr ):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join( hexStr.split(" ") )
# return ''.join( [... |
def get_hand(indices, game_lines):
"""Return a subset of the game between the supplied indices."""
hand_start_index, hand_end_index = indices
return game_lines[hand_start_index : hand_end_index + 1] |
def split_fields(fields):
"""
>>> from comma.csv.applications.csv_eval import split_fields
>>> split_fields('')
[]
>>> split_fields('x')
['x']
>>> split_fields('x,y')
['x', 'y']
"""
return fields.split(',') if fields else [] |
def IsFloat(str):
"""
ISFLOAT checks if a given string is a float.
Call - OUTPUT=IsFloat(STR)
INPUT VARIABLE:
STR - A string for checking whether a float or not
OUTPUT VARIABLE:
OUTPUT - A boolean value corresponding to whether STR
is a float (returns TRUE) or not (returns FALSE)
"""
#See if STR is ... |
def isSuffixOf(xs, ys):
"""``isSuffixOf :: Eq a => [a] -> [a] -> Bool``
Returns True if the first list is a suffix of the second. The second list
must be finite.
"""
return xs == ys[-len(xs):] |
def beta(temp, optimum=295.65, tmin=278.15, tmax=313.15, k=0.003265):
"""Calculate the environment parameter beta. This is like a birth rate
that reaches a maximum at an optimal temperature, and a range of birth
rates is specified by a parabolic width parameter of k=0.003265.
1 - k*(temp-optimum)**2
... |
def kwh_to_gwh(kwh):
""""Conversion of MW to GWh
Arguments
---------
kwh : float
Kilowatthours
Return
------
gwh : float
Gigawatthours
"""
gwh = kwh * 0.000001
return gwh |
def upcase(val: str) -> str:
"""Make all characters in a string upper case."""
return val.upper() |
def find_line_starting_with_seq(the_list, seq, from_index=0, to_index=-1):
"""
Returns index of line in the document that starts with specified char sequence. Or -1 if sequence not found.
:param the_list: list of strings
:param seq: char sequence to find;
:param from_index: index in the list;
:p... |
def post_process_headways(avg_headway, number_of_trips_per_hour, trip_per_hr_threshold=.5,
reset_headway_if_low_trip_count=180):
"""Used to adjust headways if there are low trips per hour observed in the GTFS dataset.
If the number of trips per hour is below the trip frequency interval... |
def prime_factors(n: int) -> list:
"""
Returns all prime factors of n
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
if len(factors) == 1 and factors[0] == ... |
def gen_resource_arr(search_results: dict):
""" Generates an array which contains only the names of the current selected resources
Args:
search_results (dict): The output of searcher.py
Returns:
list: All resource keys that show up in the search_results dict.
"""
resources = []
... |
def fam2hogid(fam_id):
"""
For use with OMA HOGs
Get hog id given fam
:param fam_id: fam
:return: hog id
"""
hog_id = "HOG:" + (7-len(str(fam_id))) * '0' + str(fam_id)
return hog_id |
def check_duplicates_in_tag_tuple(tagtuple):
"""Check if there is duplicate in a tag tuple, case sensitive
Args:
tagTuple (tuple) : the tag tuple to check
"""
_dup = -1
for _i, _k in enumerate(tagtuple):
if _k in tagtuple[:_i]:
_dup = _i
break
return _dup |
def area_square(side_length: float) -> float:
"""
Calculate the area of a square.
>>> area_square(10)
100
>>> area_square(-1)
Traceback (most recent call last):
...
ValueError: area_square() only accepts non-negative values
"""
if side_length < 0:
raise V... |
def int_to_en(num):
"""Given an int32 number, print it in English."""
d = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
... |
def get_shard(org):
"""
Gets the org shard to build and return the API URL
:param org: organization dictionary
:return: base url with correct shard
"""
urlLength = org['url'].find('com') + 3
orgShard = org['url'][8:urlLength]
base_url = 'https://' + orgShard + '/api/v1'
return base_... |
def coerce_to_int(val, default=0xDEADBEEF):
"""
Attempts to cast given value to an integer, return the original value if
failed or the default if one provided.
"""
try:
return int(val)
except (TypeError, ValueError):
if default != 0xDEADBEEF:
return default
re... |
def is_sequence_like(x):
"""
Returns True if x exposes a sequence-like interface.
"""
required_attrs = (
'__len__',
'__getitem__'
)
return all(hasattr(x, attr) for attr in required_attrs) |
def pColorCC( color ):
""" returns the likelihood of observing
host galaxy with the given rest-frame
B-K color, assuming the SN is a CC
RETURNS : P(B-K|CC)
"""
if color < 3 : return( 0.484, 0.05, 0.05 )
elif color < 4 : return( 0.485, 0.05, 0.05 )
else : return( 0.032, 0... |
def decode_channel_parameters(channel):
"""Decode a channel object's parameters into human-readable format."""
channel_types = {
1: 'device',
5: 'static',
6: 'user input',
7: 'system'
}
io_options = {
0: 'readonly',
1: 'readwrite'
}
datatype_opti... |
def intersperse(lst, item):
"""
Adds the item between each item in the list.
:param lst:
:param item:
:return:
"""
result = [item] * (len(lst) * 2 - 1)
result[0::2] = lst
return result |
def bounds1D(full_width, step_size):
"""
Return the bbox coordinates for a single dimension given
the size of the chunked dimension and the size of each box
"""
assert step_size > 0, "invalid step_size: {}".format(step_size)
assert full_width > 0, "invalid volume_width: {}".format(full_width)
... |
def is_x_power_of_2(x):
"""return if x is a power of 2 in O(1)"""
# drops the lowest bit and checks if it's zero
# power of 2 comes in the form: 1, 10, 100, 1000 etc. exactly 1 bit set
return x & (x - 1) == 0 |
def get_domain_name_for(host_string):
"""
Replaces namespace:serviceName syntax with serviceName.namespace one,
appending default as namespace if None exists
"""
return ".".join(
reversed(
("%s%s" % (("" if ":" in host_string else "default:"), host_string)).split(
... |
def _single_list_check_str(X):
"""
If type is string, return string in list
"""
if(type(X) == str):
X = [X]
return X |
def parse_args_tags(args_tag, to='dict'):
""" parse argument string of tags 'tag:value tag:value'
into a dictionary.
Args:
args_tag (str): tags in string format 'tag:value tag:value'
to (str): Make a 'list' or 'dict' (default)
Returns:
(list(str) or dict(str)):
"""
if t... |
def iindex(x, iterable):
"""Like list.index, but for a general iterable.
Note that just like ``x in iterable``, this will not terminate if ``iterable``
is infinite, and ``x`` is not in it.
Note that as usual when working with general iterables, the iterable will
be consumed, so this only makes sen... |
def get_nested_item(d, list_of_keys):
"""Returns the item from a nested dictionary. Each key in list_of_keys is
accessed in order.
Args:
d: dictionary
list_of_keys: list of keys
Returns: item in d[list_of_keys[0]][list_of_keys[1]]...
"""
dct = d
for i, k in enumerate(list_o... |
def set_nreg(reg):
"""
Set number of extra parameters due to regularization
"""
if reg is not None:
if reg == 'Tikhonov':
N = 1
elif reg == 'GP':
N = 3
elif reg == 'GP2':
N = 2
else:
print("%s is not a valid regularization m... |
def toTable(config):
"""Transforms a two-level dictionary of configuration options into a
list-of-dictionaries, each with the following fields:
* section
* field
* value
"""
table = []
for section in config.keys():
for k, v in config[section].items():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.