content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
from typing import Union
from typing import List
def str_to_list(text: Union[str, None]) -> Union[List, None]:
"""Split string by comma and return list"""
return text.split(",") if isinstance(text, str) else text
|
a032383dea16c6594893dcd7f1507a73657958ac
| 224,361 |
def extract_version(package_name):
"""
Extracts the version from the package_name.
The version is defined as one of the following:
-3245s
-ab434
-1.1-343s
-2.3-4
-134-minimal-24
but not:
-ab-13
-ab-ab
-m14-m16
The leading "-" is discarded.
Example:
>>> extract_version("jinja-2.5")
'2.5'
"""
def numeric(c):
if c in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
return True
return False
first_dash = package_name.find("-")
last_dash = package_name.rfind("-")
if first_dash == last_dash:
return package_name[first_dash+1:]
while not numeric(package_name[first_dash + 1]):
package_name = package_name[first_dash+1:]
first_dash = package_name.find("-")
last_dash = package_name.rfind("-")
if first_dash == last_dash:
return package_name[first_dash+1:]
return package_name[first_dash + 1:]
|
d0f5686f9b9e81654a6c9a8004c6c549fb49ac62
| 264,427 |
def resize_halo_datasets(halos_dset, new_size, write_halo_props_cont, dtype):
"""
Resizes the halo datasets
Parameters
-----------
halos_dset: dictionary, required
new_size: scalar integer, required
write_halo_props_cont: boolean, required
Controls if the individual halo properties are written as distinct
datasets such that any given property for ALL halos is written
contiguously (structure of arrays, SOA).
dtype: numpy datatype
Returns
-------
Returns ``True`` on successful completion
"""
if write_halo_props_cont:
for name in dtype.names:
dset = halos_dset[name]
dset.resize((new_size, ))
else:
halos_dset.resize((new_size, ))
return True
|
a5461a776a0991eda04fc5d0e1d2a2a14e6e1f5f
| 24,780 |
def bind_ack(data):
"""
Ensure the data is a bind ack and that the
"""
# packet type == bind ack (12)?
if data[2] != b"\x0c":
return False
# ack result == acceptance?
if data[36:38] != b"\x00\x00":
return False
return True
|
0ce51d3b9611cca24116815d282bd2b3df2e43d0
| 363,284 |
def get_invite_account_id(event):
"""Return account id for invite account events."""
return event["detail"]["requestParameters"]["target"]["id"]
|
9eb49305920d7cdd7cd61005592a4569404be770
| 136,295 |
import re
def _quantity_to_bytes(quantity):
"""Return a quantity with a unit converted into a number of bytes.
Examples:
>>> quantity_to_bytes('42Gi')
45097156608
>>> quantity_to_bytes('100M')
100000000
>>> quantity_to_bytes('1024')
1024
Args:
quantity (str): a quantity, composed of a count and an optional unit
Returns:
int: the capacity (in bytes)
"""
UNIT_FACTOR = {
None: 1,
'Ki': 2 ** 10,
'Mi': 2 ** 20,
'Gi': 2 ** 30,
'Ti': 2 ** 40,
'Pi': 2 ** 50,
'k': 10 ** 3,
'M': 10 ** 6,
'G': 10 ** 9,
'T': 10 ** 12,
'P': 10 ** 15,
}
size_regex = r'^(?P<size>[1-9][0-9]*)(?P<unit>[kKMGTP]i?)?$'
match = re.match(size_regex, quantity)
assert match is not None, 'invalid resource.Quantity value'
size = int(match.groupdict()['size'])
unit = match.groupdict().get('unit')
return size * UNIT_FACTOR[unit]
|
2ddfc61bf02772110e5b0e675b415285319f6747
| 453,571 |
from typing import List
def get_stuff_class_ids(num_thing_stuff_classes: int,
thing_class_ids: List[int],
void_label: int) -> List[int]:
"""Computes stuff_class_ids.
The stuff_class_ids are computed from the num_thing_stuff_classes, the
thing_class_ids and the void_label.
Args:
num_thing_stuff_classes: An integer specifying the number of stuff and thing
classes, not including `void` class.
thing_class_ids: A List of integers of length [num_thing_classes] containing
thing class indices.
void_label: An integer specifying the void label.
Returns:
stuff_class_ids: A sorted List of integers of shape [num_stuff_classes]
containing stuff class indices.
"""
if void_label >= num_thing_stuff_classes:
thing_stuff_class_ids = list(range(num_thing_stuff_classes))
else:
thing_stuff_class_ids = [_ for _ in range(num_thing_stuff_classes + 1)
if _ is not void_label]
return sorted(set(thing_stuff_class_ids) - set(thing_class_ids))
|
89e1ffa143d70c03d49cfab1603bdd85af2533be
| 185,074 |
import math
def calc_angle_between_two_locs(lon1_deg, lat1_deg, lon2_deg, lat2_deg):
"""
This function reads in two coordinates (in degrees) on the surface of a
sphere and calculates the angle (in degrees) between them.
"""
# Import modules ...
# Convert to radians ...
lon1_rad = math.radians(lon1_deg) # [rad]
lat1_rad = math.radians(lat1_deg) # [rad]
lon2_rad = math.radians(lon2_deg) # [rad]
lat2_rad = math.radians(lat2_deg) # [rad]
# Calculate angle in radians ...
distance_rad = 2.0 * math.asin(
math.hypot(
math.sin((lat1_rad - lat2_rad) / 2.0),
math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin((lon1_rad - lon2_rad) / 2.0)
)
) # [rad]
# Return angle ...
return math.degrees(distance_rad)
|
1ffa72e64696fc800de3fbf93bfb01a13ce14d22
| 60,709 |
def apply_first(seq):
"""Call the first item in a sequence with the remaining
sequence as positional arguments."""
f, *args = seq
return f(*args)
|
0f7353b66ea677e4b4090dc2824556952daaa7c9
| 658,980 |
def path(service):
""" Return path — or route pattern — for the given REST service. """
return '/-/{0}'.format(service.lower())
|
8f5386ee6c0b43c0692920ac91182c03b9429ea3
| 308,881 |
import re
def re_find(s, r, pos=0, endpos=9223372036854775807):
"""
Returns the match of the first occurrence of the regular expression
`r` in string (or byte-sequence) `s`. This is essentially a wrapper
for `re.finditer()` to avoid a try-catch StopIteration block.
If `r` cannot be found, `None` will be returned.
"""
if isinstance(r, (str, bytes)):
if (pos, endpos) != (0, 9223372036854775807):
rx = re.compile(r)
else:
try:
m = next(re.finditer(r, s))
return m
except StopIteration:
return None
elif r:
try:
m = next(r.finditer(s, pos, endpos))
return m
except StopIteration:
return None
|
cb726156d009956e20576757cad24fe8a6fa9279
| 513,510 |
def count_object(network, class_ids, scores, bounding_boxes, object_label, threshold=0.75):
"""
Counts objects of a given type that are predicted by the network.
:param network: object detection network
:type network: mx.gluon.nn.Block
:param class_ids: predicted object class indexes (e.g. 123)
:type class_ids: mx.nd.NDArrays
:param scores: predicted object confidence
:type scores: mx.nd.NDArrays
:param bounding_boxes: predicted object locations
:type bounding_boxes: mx.nd.NDArrays
:param object_label: object to be counted (e.g. "person")
:type object_label: str
:param threshold: required confidence for object to be counted
:type threshold: float
:return: number of objects that are predicted by the network.
:rtype: int
"""
detected_objects=0
while(scores[0][detected_objects]>threshold):
detected_objects+=1
count=0
reqd_idx = network.classes.index(object_label)
for idx in class_ids[0][:detected_objects]:
if (idx==reqd_idx):
count+=1
return count
|
31dd31319a6d579d98929ec9a57892a560b058f3
| 626,060 |
def get_attr_resolver(obj_type, model_attr):
"""
In order to support field renaming via `ORMField.model_attr`,
we need to define resolver functions for each field.
:param SQLAlchemyObjectType obj_type:
:param str model_attr: the name of the SQLAlchemy attribute
:rtype: Callable
"""
return lambda root, _info: getattr(root, model_attr, None)
|
23376addb0b5a3ab600e251e512f9174a27a66b6
| 650,766 |
def impedance(vp, rho):
"""
Compute acoustic impedance.
"""
return vp * rho
|
6be115c3d92b394a5b98cbf502d2bc753522a8a6
| 67,309 |
def make_matrix(num_rows, num_columns, entry_fn):
"""
creates a num_rows * num_columns matrix whose (i,j) entry is an entry_fn
"""
return [[entry_fn(i, j) for j in range(num_columns)] for i in range(num_rows)]
|
a1dccfe0d5d62bb58c956d56e691d1898e275134
| 184,441 |
def partial_fittable_instance(obj, name=None, **kwargs):
"""Asserts that obj has a partial_fit, and instantiates it with **kwargs if obj is given as a type"""
if name is None:
if isinstance(obj, type):
name = obj.__name__
else:
name = type(obj).__name__
assert hasattr(obj, 'partial_fit'), f"{name} doesn't have a partial_fit: {obj} "
if isinstance(obj, type):
obj = obj(**kwargs)
return obj
|
2dc94bccd3dca4710ca1ee0d732fe9f98485a46c
| 339,615 |
def map_file_to_plot_id(file_path: str, season_id: str, seasons: list) -> str:
"""Find the plot that is associated with the file
Arguments:
file_path: the path to the file
season_id: the ID of the season associated with the file
seasons: the list of seasons
Return:
Returns the found plot ID
Exceptions:
Raises RuntimeError if the plot ID isn't found
"""
found_plot_id = None
file_parts = file_path.split('/')
for one_season in seasons:
if 'id' not in one_season or 'sites' not in one_season or not one_season['id'] == season_id:
continue
for one_site in one_season['sites']:
if 'site' not in one_site or 'sitename' not in one_site['site']:
continue
if one_site['site']['sitename'] in file_parts:
found_plot_id = one_site['site']['id']
break
if found_plot_id is None:
raise RuntimeError("Unable to find plot ID for file %s" % file_path)
return found_plot_id
|
7f5d955ee130835724a1f56ae66252fa264bde29
| 289,683 |
import json
def from_json(value):
""" Decodes a JSON string into an object.
:param str value: String to decode
:returns: Decoded JSON object
"""
return json.loads(value)
|
8ab44eb73063fce49dbcc5f1ad51768f27620a41
| 645,349 |
def computechangesetcopies(ctx):
"""return the copies data for a changeset
The copies data are returned as a pair of dictionnary (p1copies, p2copies).
Each dictionnary are in the form: `{newname: oldname}`
"""
p1copies = {}
p2copies = {}
p1 = ctx.p1()
p2 = ctx.p2()
narrowmatch = ctx._repo.narrowmatch()
for dst in ctx.files():
if not narrowmatch(dst) or dst not in ctx:
continue
copied = ctx[dst].renamed()
if not copied:
continue
src, srcnode = copied
if src in p1 and p1[src].filenode() == srcnode:
p1copies[dst] = src
elif src in p2 and p2[src].filenode() == srcnode:
p2copies[dst] = src
return p1copies, p2copies
|
c1e0cd4df1fff9bea2d5184fe7dab78fc37695ee
| 385,052 |
def get_id(id_):
"""Allow specifying old or new style IDs and convert old style to new style IDs
Old style: 123-the-slug
New style: 123 or the-slug-123
"""
if isinstance(id_, int):
return id_
elif "-" in id_:
front = id_.split("-", 1)[0]
if front.isdigit():
return front
back = id_.rsplit("-", 1)[-1]
if back.isdigit():
return back
return id_
|
1d895bd7d96b52e3772c4a34a5630ffc9a06b7d2
| 523,296 |
def binomial_coefficient(n, r):
"""
Find binomial coefficient using pascals triangle.
>>> binomial_coefficient(10, 5)
252
"""
C = [0 for i in range(r + 1)]
# nc0 = 1
C[0] = 1
for i in range(1, n + 1):
# to compute current row from previous row.
j = min(i, r)
while j > 0:
C[j] += C[j - 1]
j -= 1
return C[r]
|
6a3e88cf757535b03c59a6e482e0b432adaec0db
| 121,923 |
def find_subsequence(iterable, predicate):
"""
find the subsequence in iterable which predicted return true
for example:
>>> find_subsequence([1, 10, 2, 3, 5, 8, 9], lambda x: x in [1, 0, 2, 3, 4, 5, 8, 9])
[[1], [2, 3, 5, 8, 9]]
>>> find_subsequence([1, 10, 2, 3, 5, 8, 9], lambda x: x not in [1, 0, 2, 3, 4, 5, 8, 9])
[[10]]
"""
seqs = []
seq = []
continuous = False
for i in iterable:
if predicate(i):
if continuous:
seq.append(i)
else:
seq = [i]
continuous = True
elif continuous:
seqs.append(seq)
seq = []
continuous = False
if len(seq):
seqs.append(seq)
return seqs
|
784e509b742643fbee1a32226da1d0fb9ec3bd21
| 144,379 |
def fmt_option_key(key, value):
"""Format a single keyword option."""
if value is None:
return ""
return f"{key}={value}"
|
271519544ac6b10840898782bb74904e03a16197
| 317,480 |
def get_case_form_ids(couch_case):
"""Get the set of form ids that touched the given couch case object"""
form_ids = set(couch_case.xform_ids)
for action in couch_case.actions:
if action.xform_id:
form_ids.add(action.xform_id)
return form_ids
|
f3e5822f5be0822808719fa184fdc263ceb73d62
| 182,662 |
import re
def youtube_url_validator(url):
"""
## youtube_url_validator
Validates & extracts Youtube video ID from URL.
Parameters:
url (string): inputs URL.
**Returns:** A valid Youtube video string ID.
"""
youtube_regex = (
r"(?:http:|https:)*?\/\/(?:www\.|)(?:youtube\.com|m\.youtube\.com|youtu\.|youtube-nocookie\.com).*"
r"(?:v=|v%3D|v\/|(?:a|p)\/(?:a|u)\/\d.*\/|watch\?|vi(?:=|\/)|\/embed\/|oembed\?|be\/|e\/)([^&?%#\/\n]*)"
)
matched = re.search(youtube_regex, url)
# check for None-type
if not (matched is None):
return matched.groups()[0]
else:
return ""
|
ff2779844ed1cb74125cac285e197ef23bfb8f11
| 240,079 |
def is_prime(nb: int) -> bool:
"""Check if a number is a prime number or not
:param nb: the number to check
:return: True if prime, False otherwise
"""
# even numbers are not prime
if nb % 2 == 0 and nb > 2:
return False
# checking all numbers up to the square root of the number
# full explanation:
# https://stackoverflow.com/questions/18833759/python-prime-number-checker/18833870#18833870
return all(nb % i for i in range(3, int(nb ** .5) + 1, 2))
|
4368fd20eadd4d773d5f5af06f8717ef633d48b8
| 698,329 |
def _is_public(name: str) -> bool:
"""Return true if the name is not private, i.e. is public.
:param name: name of an attribute
"""
return not name.startswith('_')
|
280bd1636ad3a08d51c95165ac15e7a6e75b745b
| 320,336 |
def count_parameters(model, tunable_only: bool = True) -> int:
""" Count the number of parameters in the given model.
Parameters
----------
model : torch.nn.Module
PyTorch model (deep network)
tunable_only : bool, optional
Count only tunable network parameters
References
----------
https://stackoverflow.com/questions/49201236/check-the-total-number-of-parameters-in-a-pytorch-model
"""
if tunable_only:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
else:
return sum(p.numel() for p in model.parameters())
|
ef825fab61760d7d5e5778f6c85c33fddf4db5d5
| 431,880 |
def transform_optional(node, **kwargs):
"""Sets the optional flag.
"""
return "optional"
|
229ad2e6911c714b17bbfe295a964b3438b7f377
| 243,848 |
import math
def sum_digits_factorial(n):
"""
Compute sum of factorials of each digit in the number n
"""
sum_fact = 0
while n > 0:
sum_fact += math.factorial(n % 10)
n //= 10
return sum_fact
|
994878df3e8337c482f46f0ae6a7419f4454bf04
| 436,746 |
def remove_non_latin(input_string, also_keep=None):
"""Remove non-Latin characters.
`also_keep` should be a list which will add chars (e.g. punctuation)
that will not be filtered.
"""
if also_keep:
also_keep += [' ']
else:
also_keep = [' ']
latin_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
latin_chars += latin_chars.lower()
latin_chars += ''.join(also_keep)
no_latin = "".join([char for char in input_string if char in latin_chars])
return no_latin
|
d29d3928e128fba5d6a773a11746fe6fc6b0b7a2
| 310,589 |
def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
""" Checks whether the given directed joint degree input is realizable
Parameters
----------
in_degrees : list of integers
in degree sequence contains the in degrees of nodes.
out_degrees : list of integers
out degree sequence contains the out degrees of nodes.
nkk : dictionary of dictionary of integers
directed joint degree dictionary. for nodes of out degree k (first
level of dict) and nodes of in degree l (seconnd level of dict)
describes the number of edges.
Returns
-------
boolean
returns true if given input is realizable, else returns false.
Notes
-----
Here is the list of conditions that the inputs (in/out degree sequences,
nkk) need to satisfy for simple directed graph realizability:
- Condition 0: in_degrees and out_degrees have the same length
- Condition 1: nkk[k][l] is integer for all k,l
- Condition 2: sum(nkk[k])/k = number of nodes with partition id k, is an
integer and matching degree sequence
- Condition 3: number of edges and non-chords between k and l cannot exceed
maximum possible number of edges
References
----------
[1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
"Construction of Directed 2K Graphs". In Proc. of KDD 2017.
"""
V = {} # number of nodes with in/out degree.
forbidden = {}
if len(in_degrees) != len(out_degrees):
return False
for idx in range(0, len(in_degrees)):
i = in_degrees[idx]
o = out_degrees[idx]
V[(i, 0)] = V.get((i, 0), 0) + 1
V[(o, 1)] = V.get((o, 1), 0) + 1
forbidden[(o, i)] = forbidden.get((o, i), 0) + 1
S = {} # number of edges going from in/out degree nodes.
for k in nkk:
for l in nkk[k]:
val = nkk[k][l]
if not float(val).is_integer(): # condition 1
return False
if val > 0:
S[(k, 1)] = S.get((k, 1), 0) + val
S[(l, 0)] = S.get((l, 0), 0) + val
# condition 3
if val + forbidden.get((k, l), 0) > V[(k, 1)] * V[(l, 0)]:
return False
for s in S:
if not float(S[s]) / s[0] == V[s]: # condition 2
return False
# if all conditions abive have been satisfied then the input nkk is
# realizable as a simple graph.
return True
|
c144816f286894e6e4df9adb107d02be630576f2
| 104,367 |
def get_gb_acc_id(year, case_index):
"""
Returns global accident id for GB, year and index of accident.
GB ids will be in form 2200700000001234
2 at the beginning means it is from Great Britain
2007 means the year
1234 means the case ID as in original data
"""
try:
acc_id = 2000000000000000
acc_id += year * 100000000000
acc_id += case_index
except KeyError:
raise ValueError("Country code incorrect")
return acc_id
|
a4e919866018635c7de0a8a3b66b8e3a16c61fc5
| 177,509 |
def get_source_url(j):
"""
return URL for source file for the latest version
return "" in errors
"""
v = j["info"]["version"]
rs = j["releases"][v]
for r in rs:
if r["packagetype"] == "sdist":
return r["url"]
return ""
|
c9a44fe7829a908772611d60884b402ef9452e67
| 155,657 |
import logging
def remediate_iam_policy(sa_iam_policy, sa_resource_name, risky_roles):
"""Remove risky IAM roles from the service account IAM policy.
Args:
sa_iam_policy ([dict]): The IAM policy attached to the sa_resource_name.
sa_resource_name ([str]): The GCP service account full resource name.
risky_roles ([list]): A list of risky roles to check current attached roles against.
Returns:
[dict]: An updated non-risky IAM policy. All risky roles removed.
"""
# We iterate in reverse due to removing entries
for binding in reversed(sa_iam_policy["bindings"]):
if binding["role"] in risky_roles:
role = binding["role"]
logging.info(
f"Removing risky role: {role} from {sa_resource_name}"
)
sa_iam_policy["bindings"].remove(binding)
else:
logging.info(f"IAM binding: {binding} does not contain risky role.")
return sa_iam_policy
|
f5de29116a4f25dd49c2a8b48a64e44b9cdb9794
| 606,338 |
def create_mapping(dict_times):
"""
If times are not integers, transform them into integers.
:param dict_times: Dict where keys are times.
:return: A mapping which is a dictionary maps from current names of time stamps to integers (by their index)
"""
keys = list(dict_times.keys())
mapping = {}
for i in range(len(keys)):
mapping.update({keys[i]: i})
return mapping
|
75893a6419b61d86bc0d4d0693bbc1b25f111a75
| 32,512 |
from typing import Union
from typing import Callable
import torch
def get_activation(fn: Union[Callable, str]):
"""Get a PyTorch activation function, specified either directly or as a string.
This function simplifies allowing users to specify activation functions by name.
If a function is provided, it is simply returned unchanged. If a string is provided,
the corresponding function in torch.nn.functional is returned.
"""
if isinstance(fn, str):
return getattr(torch.nn.functional, fn)
return fn
|
af66502925599653e7f7c577c7754e0323ee93d7
| 125,441 |
def rain(walls):
"""
walls is a list of non-negative integers.
Return: Integer indicating total amount of rainwater retained.
Assume that the ends of the list (before index 0 and after index
walls[-1]) are not walls, meaning they will not retain water.
If the list is empty return 0.
"""
n = len(walls)
wtr = 0
for i in range(1, n - 1):
lft = walls[i]
for j in range(i):
lft = max(lft, walls[j])
rgt = walls[i]
for j in range(i + 1, n):
rgt = max(rgt, walls[j])
wtr = wtr + (min(lft, rgt) - walls[i])
return wtr
|
e26b22f09823f4a09b8f209780152ed739bf78bd
| 635,099 |
def _ensureListOfLists(iterable):
"""
Given an iterable, make sure it is at least a 2D array (i.e. list of lists):
>>> _ensureListOfLists([[1, 2], [3, 4], [5, 6]])
[[1, 2], [3, 4], [5, 6]]
>>> _ensureListOfLists([1, 2])
[[1, 2]]
>>> _ensureListOfLists(1)
[[1]]
:param iterable: The iterable of which to make sure it is 2D
:return: A guaranteed 2D version of ``iterable``
"""
try:
if len(iterable) > 0:
try:
if len(iterable[0]) > 0:
return iterable
except TypeError:
return [iterable]
except TypeError:
return [[iterable]]
|
7600d2d1bdbe20addf86a39d3d20dc8ab30586c0
| 365,711 |
import torch
import math
def compute_particle_xyz_from_internal(particle_1_xyz,
particle_2_xyz,
particle_3_xyz,
bond, angle, dihedral):
""" Compute the Cartesian coordinate of a particle based on its internal
coordinate with respect to three other particles and the Cartesian
coordinates of these three particles. This function runs a batch mode, which
mean that it compute the Cartensian coordinates of a batch of particles based
on a batch of three other particles.
Parameters:
-----------
particle_1_xyz: torch.Tensor
the Cartesian coordinate of atom 1.
particle_2_xyz: torch.Tensor
the Cartesian coordinate of atom 2.
particle_3_xyz: torch.Tensor
the Cartesian coordinate of atom 3.
Note particle_1_xyz, particle_2_xyz and particle_3_xyz should the same size: [batch_size, 3].
bond: torch.Tensor
the length of the bond between atom 3 and atom 4
angle: torch.Tensor
the value of the angle between atom 2, atom 3 and atom 4
dihedral: torch.Tensor
the value of the dihedral angle between atom 1, atom 2, atom3 and atom 4
Note bond, angle and dihedral have the same size: [batch_size]
Returns:
--------
particle_4_xyz: torch.Tensor
the Cartensian coordiante of atom 4. Its size is [batch_size, 3]
logabsdet: the logarithm of the absolute value of the determinant of
the transformation from the internal coordinates of particle 4
to its Cartesian coordinates
"""
## calculate the coordinate of the forth atom
wi, wj, wk = particle_1_xyz, particle_2_xyz, particle_3_xyz
e1 = wk - wj
e1 = e1 / torch.norm(e1, dim = -1, keepdim = True)
e3 = torch.cross(e1, wj - wi, dim = -1)
e3 = e3 / torch.norm(e3, dim = -1, keepdim = True)
e2 = torch.cross(e3, e1, dim = -1)
bond = torch.unsqueeze(bond, -1)
angle = torch.unsqueeze(angle, -1)
dihedral = torch.unsqueeze(dihedral, -1)
dw = torch.cos(math.pi-angle)*e1 + \
(-1)*torch.sin(math.pi-angle)*torch.cos(dihedral)*e2 + \
(-1)*torch.sin(math.pi-angle)*torch.sin(dihedral)*e3
wl = wk + bond*dw
particle_4_xyz = wl
## calculate the Jacobian of the transform
logabsdet = torch.log(torch.abs(bond**2*torch.sin(math.pi - angle)))
logabsdet = torch.squeeze(logabsdet)
return particle_4_xyz, logabsdet
|
9a3b59d5c29a0c8ac9c5f498925698b8ab29bd16
| 572,388 |
from pathlib import Path
def new_name_if_exists(file: Path):
"""Make a new filename that avoids name collisions.
example: filename(xx).ext where xx is incremented until
unused filename is created.
Args:
file (Path): proposed unique filename.
Returns:
Path_obj: Guaranteed unique filename.
"""
new_name = file
i = 1
while True:
if not new_name.is_file():
return new_name
else:
new_name = file.with_name(f"{file.stem}({i}){file.suffix}")
i += 1
|
89f639e2a5ef12941c8d50b8a4313f71cf1dbe94
| 357,979 |
import math
def calc_overlap(params):
"""
Function to calculate the number of pixels requires in overlap, based on chunk_size and overlap percentage,
if provided in the config file
:param params: (dict) Parameters found in the yaml config file.
:return: (int) number of pixel required for overlap
"""
chunk_size = 512
overlap = 10
if params['inference']['chunk_size']:
chunk_size = int(params['inference']['chunk_size'])
if params['inference']['overlap']:
overlap = int(params['inference']['overlap'])
nbr_pix_overlap = int(math.floor(overlap / 100 * chunk_size))
return chunk_size, nbr_pix_overlap
|
f6dd348cf2299100d30e12c1ebf71c84d5f80183
| 278,512 |
def number_of_short_term_peaks(n, t, t_st):
"""
Estimate the number of peaks in a specified period.
Parameters
----------
n : int
Number of peaks in analyzed timeseries.
t : float
Length of time of analyzed timeseries.
t_st: float
Short-term period for which to estimate the number of peaks.
Returns
-------
n_st : float
Number of peaks in short term period.
"""
assert isinstance(n, int), 'n must be of type int'
assert isinstance(t, float), 't must be of type float'
assert isinstance(t_st, float), 't_st must be of type float'
return n * t_st / t
|
4118409bd4d330e68f41bf1e51d3940478a7f76e
| 365,943 |
def onBoard(top, left=0):
"""Simplifies a lot of logic to tell if the coords are within the board"""
return 0 <= top <= 9 and 0 <= left <= 9
|
2b2007ae2e3acdbb9c04c3df1397cffce97c6717
| 10,247 |
import torch
def haschildren(obj):
"""Check if the object has children
Arguments:
obj {object} -- the object to check
Returns:
bool -- True if the object has children
"""
ommit_type = [torch.nn.parameter.Parameter, torch.Tensor]
if type(obj) in ommit_type:
return False
else:
return hasattr(obj, '__dict__') or hasattr(obj, 'keys')
|
03ef8ef009565a437a99beed4f1f6076ac6ffa1a
| 604,067 |
def addon(options):
"""
This function constructs a command line invocation that needs to be passed for invoking for a sub workflow.
Only a certain subset of options are propogated to the sub workflow invocations if passed.
"""
cmd_line_args = ""
if options.recurse_mode:
cmd_line_args += "--recurse "
if options.quiet_mode:
cmd_line_args += "--quiet "
if options.summary_mode:
cmd_line_args += "--summary "
if options.use_files:
cmd_line_args += "--files "
new_indent = 1
if options.indent_length is not None:
new_indent = options.indent_length + 1
cmd_line_args += "--indent " + str(new_indent) + " "
return cmd_line_args
|
41e556f2d34d71cb09f0f7db4b5a3aa2b99a9a11
| 295,044 |
import struct
import pickle
async def read_and_unserialize_socket_msg(reader):
"""
Read and unserialize the message bytestream received from ScrubCam.
Parameters
----------
reader : asyncio.StreamReader
A reader object that provides APIs to read data from the IO
stream
Returns
-------
msg : str or int or bool or list
The object representation of the bytestream message. This could be
a message header, timestamp, flag, lbox list, or filter class
list.
"""
# Read size of msg bytestream
msg_struct = await reader.read(struct.calcsize('<L'))
msg_size = struct.unpack('<L', msg_struct)[0]
# Read in msg bytestream
msg_bytes = await reader.readexactly(msg_size)
msg = pickle.loads(msg_bytes)
return msg
|
7d549c847d98897d65caeb0b720b07b2580bb6d9
| 405,271 |
from typing import List
def linvectors_list(
pitches: List,
) -> List:
"""Returns the linvectors of a list of MIDI pitches.
"""
result = []
first_linvector = [pitches[0]]
result.append(first_linvector)
for pitch in pitches[1:]:
next_linvector = []
for element in result[-1]:
if abs(pitch-element) <= 2:
pass
else:
next_linvector.append(element)
next_linvector.append(pitch)
result.append(next_linvector)
return result
|
ee92d979427f55b161517422ecee79d5c633b834
| 200,002 |
import torch
def my_l1(x, x_recon):
"""Calculate l1 loss
Parameters
----------
x : torch.cuda.FloatTensor or torch.FloatTensor
Input data
x_recon : torch.cuda.FloatTensor or torch.FloatTensor
Reconstructed input
Returns
-------
torch.cuda.FloatTensor or torch.FloatTensor
"""
return torch.mean(torch.abs(x-x_recon))
|
a7736bd2d4160546176520a6adbd1c218dc5cc14
| 689,723 |
def time_to_seconds(timestring):
"""
Transform (D-)HH:MM:SS time format to seconds.
Parameters
----------
timestring: str or None
Time in format (D-)HH:MM:SS
Returns
-------
Seconds that correspond to (D-)HH:MM:SS
"""
if timestring is None:
timestring = "00:00:00"
if "-" in timestring:
# Day is also specified (D-)HH:MM:SS
days, hhmmss = timestring.split("-")
hours, minutes, seconds = hhmmss.split(":")
return (
int(days) * 24 * 3600 + int(hours) * 3600 + int(minutes) * 60 + int(seconds)
)
split_time = timestring.split(":")
if len(split_time) == 2:
# MM:SS
minutes, seconds = split_time
hours = 0
elif len(split_time) == 3:
# HH:MM:SS
hours, minutes, seconds = split_time
else:
raise ValueError("Time format not recognized.")
return int(hours) * 3600 + int(minutes) * 60 + int(seconds)
|
60ba0e0a78e4eff1ae443923da7b22fccc695576
| 456,439 |
def read_column_tagged_file(filename: str, tag_col: int = -1):
"""Reads column tagged (CONLL) style file (tab separated and token per line)
tag_col is the column number to use as tag of the token (defualts to the last in line)
return format :
[ ['token', 'TAG'], ['token', 'TAG2'],... ]
"""
data = []
sentence = []
labels = []
with open(filename) as fp:
for line in fp:
line = line.strip()
if len(line) == 0:
if len(sentence) > 0:
data.append((sentence, labels))
sentence = []
labels = []
continue
splits = line.split()
sentence.append(splits[0])
labels.append(splits[tag_col])
if len(sentence) > 0:
data.append((sentence, labels))
return data
|
3143548e3df1258b743faa65ccf4bb727846f5e4
| 190,537 |
from typing import List
from typing import Any
from typing import Iterable
def as_list(item_or_sequence) -> List[Any]:
"""Turns an arbitrary sequence or a single item into a list. In case of
a single item, the list contains this element as its sole item."""
if isinstance(item_or_sequence, Iterable):
return list(item_or_sequence)
return [item_or_sequence]
|
2edf2d9adb03c0efb16e59a507a918149fdae524
| 39,727 |
import random
def random_class_ids(lower, upper):
"""
Get two random integers that are not equal.
Note: In some cases (such as there being only one sample of a class) there may be an endless loop here. This
will only happen on fairly exotic datasets though. May have to address in future.
:param lower: Lower limit inclusive of the random integer.
:param upper: Upper limit inclusive of the random integer. Need to use -1 for random indices.
:return: Tuple of (integer, integer)
"""
int_1 = random.randint(lower, upper)
int_2 = random.randint(lower, upper)
while int_1 == int_2:
int_1 = random.randint(lower, upper)
int_2 = random.randint(lower, upper)
return int_1, int_2
|
dcb351efbf772f2408213b362b9a5af4bfabc8cb
| 651,651 |
def vector_subtract(u, v):
"""returns the difference (vector) of vectors u and v"""
return (u[0]-v[0], u[1]-v[1], u[2]-v[2])
|
034c07a1e459725744112b51933c2c0c73c60f68
| 663,204 |
def head_table(rule):
"""Table name of the head of a rule"""
return rule.head.table
|
aaf0bc25382ad0192de8c826a3cbfc5da4535b27
| 333,011 |
def callMultiF(f,n,cache):
"""
Try to get n unique results by calling f() multiple times
>>> import random
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set())
[9, 8, 4, 2, 5, 3, 6, 10]
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set([8,9,10]))
[4, 2, 5, 3, 6, 7]
"""
rs = []
rs_s = set()
if cache:
for c in cache: rs_s.add(c)
for _ in range(n):
c = f()
c_iter = 0
while c in rs_s and c_iter < 3:
c_iter += 1
c = f()
if c not in rs_s:
rs_s.add(c)
rs.append(c)
assert len(rs) <= n
return rs
|
ce38fe79c311c60753432b2606216bdd47c8db41
| 535,727 |
def prep_sub_id(sub_id_input):
"""Processes subscription ID
Args:
sub_id_input: raw subscription id
Returns:
Processed subscription id
"""
if not isinstance(sub_id_input, str):
return ""
if len(sub_id_input) == 0:
return ""
return "{" + sub_id_input.strip().upper() + "}"
|
719693c2a11d1e8611fceec80b34b07a157e91ad
| 676,067 |
def read_file(filename: str) -> str:
"""Reads contents of given file"""
with open(filename, "r") as content_file:
return content_file.read()
|
b2989f88849ac9f77a38435b8bdba497d7d9699a
| 296,628 |
def blocks_table_m() -> dict[int, int]:
"""The table is the number of blocks for the correction level M.
Returns:
dict[int, int]: Dictionary of the form {version: number of blocks}
"""
table = {
1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 4, 7: 4, 8: 4, 9: 5, 10: 5, 11: 5,
12: 8, 13: 9, 14: 9, 15: 10, 16: 10, 17: 11, 18: 13, 19: 14, 20: 16,
21: 17, 22: 17, 23: 18, 24: 20, 25: 21, 26: 23, 27: 25, 28: 26, 29: 28,
30: 29, 31: 31, 32: 33, 33: 35, 34: 37, 35: 38, 36: 40, 37: 43, 38: 45,
39: 47, 40: 49
}
return table
|
a964fc403146bf8078659c898226f8b86bb230fd
| 348,041 |
def validate_move(move, turn, board):
"""
Determine if the next move is valid for the current player
:param move:
:param turn:
:param board:
:return: boolean flag for if the move is valid as well as the current gamestate dictionary
"""
if turn == 1:
piece = 'X'
else:
piece = 'O'
try:
if board[move[:-1]][move] not in ('X', 'O'):
board[move[:-1]][move] = piece
return True, board
else:
return False, board
except KeyError:
return False, board
|
b3117e72a8377aaceb5ee8c887a272bcb15ea553
| 690,518 |
import uuid
def generate_dtids(registry: str, number: int) -> list:
"""
Generate a list of DTIDs.
Args:
number: The number of generated DTIDs.
registry: Base URL of the DTID registry.
Returns:
List of DTIDs
"""
dtids = []
for _ in range(number):
dtids.append(registry + str(uuid.uuid4()))
return dtids
|
3efcc7dd8ab4bd6edd4b3256c7e973df8f15e7fc
| 108,357 |
def photon_generation(wave_len, energy):
"""Determine number of photons in a bundle
Parameters
----------
wave_len : float
Wavelength associated with a particular bundle
energy : float
Energy in a bundle
Returns
-------
nphoton : float
Number of photons in a bundle as a function of wavelength
Notes
-----
"""
nphoton = 0
h = 6.626e-34 # [joule*s] planck's constant
c = 2.998e8 # [m/s] speed of light
ephoton = (h*c)/(wave_len*1e-9) # find energy in a photon
if wave_len <= 1107:
nphoton = energy/ephoton
return nphoton
|
c0b1aa263ec81e16b37314b9506b0a2456aa8dfa
| 580,082 |
import pkg_resources
def get_config(package=__name__, externals=None, api_version=None):
"""Returns a string containing the configuration information for the given ``package`` name.
By default, it returns the configuration of this package.
This function can be reused by other packages.
If these packages have external C or C++ dependencies, the ``externals`` dictionary can be specified.
Also, if the package provides an API version, it can be specified.
**Keyword parameters:**
package : *str*
The name of the package to get the configuration information from.
Usually, the ``__name__`` of the package.
externals : *{dep: description}*
A dictionary of external C or C++ dependencies, with the ``dep``endent package name as key, and a free ``description`` as value.
api_version : *int* (usually in hexadecimal)
The API version of the ``package``, if any.
"""
packages = pkg_resources.require(package)
this = packages[0]
deps = packages[1:]
if api_version is not None:
retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version, api_version, this.location)
else:
retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
if externals is not None:
retval += "* C/C++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
if len(deps):
retval += "* Python dependencies:\n"
# sort python dependencies and make them unique
deps_dict = {}
for d in deps: deps_dict[d.key] = d
for k in sorted(deps_dict):
retval += " - %s: %s (%s)\n" % (deps_dict[k].key, deps_dict[k].version, deps_dict[k].location)
return retval.strip()
|
8d8c95ea4b10cc29bcd7831d2dbdc8f7ad05ff89
| 533,928 |
from typing import List
def _add_docstring_to_top_level_func(line: str, docstring: str) -> str:
"""
Add docstring to the top-level function line string.
Parameters
----------
line : str
Target function line string.
e.g., `def sample_func(a: int) -> None:`
docstring : str
A doctring to add.
Returns
-------
line : str
Docstring added line str.
"""
line += '\n """'
docstring_lines: List[str] = docstring.splitlines()
for docstring_line in docstring_lines:
if docstring_line == '':
line += '\n'
continue
if not docstring_line.startswith(' '):
docstring_line = f' {docstring_line}'
line += f'\n{docstring_line}'
line += '\n """'
return line
|
e4fcee2a5ac3bae9508174315884aea128dabf93
| 620,490 |
def format_time_filter(start, stop, field):
"""Formats a time filter for a given endpoint type.
Args:
start (str): An ISO date string, e.g. 2020-04-20.
stop (str): An ISO date string, e.g. 2021-04-20.
field (str): The time field to filter by.
"""
start_date = start.split('-')
end_date = stop.split('-')
y1, m1, d1 = start_date[0], start_date[1], start_date[2]
y2, m2, d2 = end_date[0], end_date[1], end_date[2]
return f'?f_{field}1={m1}%2F{d1}%2F{y1}&f_{field}2={m2}%2F{d2}%2F{y2}'
|
6c21bb1ff6f90002d0f7f50d2c82fd081db89213
| 676,601 |
def make_good_url(url=None, addition="/"):
"""Appends addition to url, ensuring the right number of slashes
exist and the path doesn't get clobbered.
>>> make_good_url('http://www.server.com/anywhere', 'else')
'http://www.server.com/anywhere/else'
>>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/')
'http://test.com/somewhere/over/the/rainbow/'
>>> make_good_url('None')
'None/'
>>> make_good_url()
>>> make_good_url({})
>>> make_good_url(addition='{}')
:param url: URL
:param addition: Something to add to the URL
:return: New URL with addition"""
if url is None:
return None
if isinstance(url, str) and isinstance(addition, str):
return "%s/%s" % (url.rstrip('/'), addition.lstrip('/'))
else:
return None
|
bc22f403d6e3c999f2b5cf6c9bbaf57e53e67e0b
| 541,037 |
def all_true (seq) :
"""Returns True if all elements of `seq` are true,
otherwise returns first non-true element.
"""
for e in seq :
if not e :
return e
else :
return True
|
26ad964d3c9f53aec547e29e703bf97c8e646219
| 422,976 |
import torch
def binary_accuracy(preds, y):
"""
Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
"""
rounded_preds = torch.round(torch.sigmoid(preds))
correct = (rounded_preds == y).float() #convert into float for division
acc = correct.sum() / len(correct)
return acc
|
8d3cc42eec8b9fa2f6b2a905bb840abe9e7e5252
| 531,209 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Returns
-------
:list: list with spaxels
"""
spx = [[(x, y) for x in range(spectrum.flux.shape[0])]
for y in range(spectrum.flux.shape[1])]
spaxels = [item for sublist in spx for item in sublist]
return spaxels
|
9d4b5339f18022607f349c326dc83e319a690a26
| 8,488 |
def query_mission(id):
"""
Build the Query for a single mission
"""
query = f'''
{{
mission(id:"{id}") {{
id
name
manufacturers
description
website
}}
}}
'''
return query
|
60d0fdf2bbea4307b901e6b2f3917a5dda7aa7a4
| 589,654 |
from datetime import datetime
def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str):
"""
Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time.
:param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS
:return: Time (float64) in seconds from epoch 01-01-1900.
"""
timestamp = datetime.strptime(timestamp_str, "%d %b %Y %H:%M:%S")
return (timestamp - datetime(1900, 1, 1)).total_seconds()
|
bf2239de21973ae537cee94022e9d2781f7cbd52
| 681,251 |
def wgan_d_loss(scores_real, scores_fake):
"""
Input:
- scores_real: Tensor of shape (N,) giving scores for real samples
- scores_fake: Tensor of shape (N,) giving scores for fake samples
Output:
- loss: Tensor of shape (,) giving WGAN discriminator loss
"""
return scores_fake.mean() - scores_real.mean()
|
df305b008f6e0e92e917c7f1705cf11e4d78c9f6
| 556,409 |
def _extract_variants(address, variants_str):
"""Return the variants (if any) represented by the given variants_str.
:returns: The variants or else `None` if there are none.
:rtype: tuple of tuples (key, value) strings
"""
def entries():
for entry in variants_str.split(','):
key, _, value = entry.partition('=')
if not key or not value:
raise ValueError('Invalid variants after the @ in: {}'.format(address))
yield (key, value)
return tuple(entries())
|
1644b10ec44e04b565b5b2a1bd67062e57750873
| 505,618 |
def extended_gcd(a, b):
"""Find the solution of ax + by = gcd(x, y), returns (x, y, gcd(x, y))"""
if b == 0:
return 1, 0, a
x, y, gcd = extended_gcd(b, a % b)
return y, x - (a // b) * y, gcd
|
f3dbc95e3b13d89079916948bf76ddba5184d6c6
| 185,565 |
def _slice_datetime_repr_prefix(obj_repr):
"""Takes a default "datetime", "date", or "timedelta" repr and
returns it with the module prefix sliced-off::
>>> _slice_datetime_repr_prefix('datetime.date(2020, 12, 25)')
'date(2020, 12, 25)'
"""
# The following implementation (using "startswith" and "[9:]")
# may look clumsy but it can run up to 10 times faster than a
# more concise "re.compile()" and "regex.sub()" approach. In
# some situations, this function can get called many, many
# times. DON'T GET CLEVER--KEEP THIS FUNCTION FAST.
if obj_repr.startswith('datetime.datetime(') \
or obj_repr.startswith('datetime.date(') \
or obj_repr.startswith('datetime.timedelta('):
return obj_repr[9:]
return obj_repr
|
fa4778ab00caa1996041ad650baecb7b0db47b3b
| 419,868 |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b))
|
e3fa9e013f5794ec44d739282d98f72b8b601ed2
| 679,808 |
def comb(N,P):
"""
Calculates the combinations of the integers [0,N-1] taken P at a time.
The output is a list of lists of integers where the inner lists are
the different combinations. Each combination is sorted in ascending
order.
"""
def rloop(n,p,combs,comb):
if p:
for i in range(n):
newcomb = comb+[i]
np = p-1
rloop(i,np,combs,newcomb)
else:
combs.append(comb)
combs = []
rloop(N,P,combs,[])
for comb in combs:
comb.sort()
return(combs)
|
b3d6e1e2556ae951a0951c485a691cdb51095070
| 336,583 |
from datetime import datetime
def _parse_publishing_date(string):
"""
Parses the publishing date string and returns the publishing date
as datetime.
Input example (without quotes): "Wed, 09 Nov 2016 17:11:56 +0100"
"""
return datetime.strptime(string,"%a, %d %b %Y %H:%M:%S +0100")
|
e0ddc6da2a8acb90cceb4649f0d8491531408fcb
| 689,821 |
import textwrap
def _dedent_under_first_line(text: str) -> str:
"""
Apply textwrap.dedent ignoring the first line.
"""
lines = text.splitlines()
other_lines = "\n".join(lines[1:])
if other_lines:
return f"{lines[0]}\n{textwrap.dedent(other_lines)}"
return text
|
4abe7db2f67455d3d6453218022c144317936476
| 273,761 |
from typing import List
def erase_overlap_intervals(intervals: List[List[int]]):
"""
a variant for LeetCode 435
Given a list of intervals, remove minimal intervals to make the rest of the intervals non-overlapping.
注意:剩余列表中允许打乱原列表的顺序。如果要求保持原顺序,则需要在排序前先记录index。
Examples:
1. intervals: [[1, 2], [2, 3], [3, 4], [1, 3]], return: [[1, 2], [2, 3], [3, 4]], [[1, 3]]
2. intervals: [1, 2], [1, 2], [1, 2]], return: [[1, 2]], [[1, 2], [1, 2]]
:param intervals:
:return:
left_intervals: List[List[int]]
remove_intervals: List[List[int]]
"""
l = len(intervals)
if l <= 1:
return l, []
intervals = sorted(intervals, key=lambda x: x[1])
left, remove = [], []
interval = intervals[0]
end = interval[1]
for x in intervals[1:]:
if x[0] >= end:
left.append(interval)
interval = x
end = x[1]
else:
remove.append(x)
left.append(interval)
return left, remove
|
8ff2bdf43bff7ce5ff6c90f40474557b79f26acc
| 204,869 |
def get_file_extension(filename: str) -> str:
"""
Finds the extension of a file given its full name.
:param filename: Complete filename.
:return: The extension file type of the file.
"""
return filename.split('.')[-1]
|
740b4345e73d8b7b94a15b2aa2ab338fa4feeab5
| 483,020 |
def collect_solution_pool(m, T, n_hat_prime, a_hat_prime):
"""
This function collect the result (list of repaired nodes and arcs) for all feasible solutions in the solution pool
Parameters
----------
m : gurobi.Model
The object containing the solved optimization problem.
T : int
Number of time steps in the optimization (T=1 for iINDP, and T>=1 for td-INDP).
n_hat_prime : list
List of damaged nodes in controlled network.
a_hat_prime : list
List of damaged arcs in controlled network.
Returns
-------
sol_pool_results : dict
A dictionary containing one dictionary per solution that contain list of repaired node and arcs in the solution.
"""
sol_pool_results = {}
current_sol_count = 0
for sol in range(m.SolCount):
m.setParam('SolutionNumber', sol)
# print(m.PoolObjVal)
sol_pool_results[sol] = {'nodes': [], 'arcs': []}
for t in range(T):
# Record node recovery actions.
for n, d in n_hat_prime:
node_var = 'w_tilde_' + str(n) + "," + str(t)
if T == 1:
node_var = 'w_' + str(n) + "," + str(t)
if round(m.getVarByName(node_var).xn) == 1:
sol_pool_results[sol]['nodes'].append(n)
# Record edge recovery actions.
for u, v, a in a_hat_prime:
arc_var = 'y_tilde_' + str(u) + "," + str(v) + "," + str(t)
if T == 1:
arc_var = 'y_' + str(u) + "," + str(v) + "," + str(t)
if round(m.getVarByName(arc_var).x) == 1:
sol_pool_results[sol]['arcs'].append((u, v))
if sol > 0 and sol_pool_results[sol] == sol_pool_results[current_sol_count]:
del sol_pool_results[sol]
elif sol > 0:
current_sol_count = sol
return sol_pool_results
|
5eaf9bede69c4c29e412c0311eab74ce1a8bf812
| 492,157 |
def calcPv(r, freq, periods, value):
"""
Parameters
----------
r:
discount rate;
the expected rate of return if every coupon payment was
invested at a fixed interest rate until the bond matures
freq:
frequency
periods:
periods to maturity
value:
future value / value at maturity
Returns
-------
present_value
"""
tmp = (1 + r / freq) ** periods
return value / tmp
|
f4ee0a34051a66b46f0d1652ea2c5f3d4d3aae1c
| 442,563 |
def get_data_science_bookmarks(bookmarks):
"""Function to select the top level data science folder of bookmarks.
Returns the first element of bookmarks where 'Data Science' is one of the keys.
"""
for item in bookmarks:
if type(item) is dict:
if 'Data Science' in item.keys():
return item
|
ae8eb873e4775c030e67c49dd693fc9ee1fb902e
| 649,983 |
import getpass
def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:rtype: string
:return: A username.
"""
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % (prompt, env_user))
if user == '':
user = env_user
return user
|
fc392cfacc931ee915bb218a80e5db46245f2a1f
| 11,108 |
def parse_lookup_table(lookupfile):
"""Parse the lookup table that contains AB genotypes."""
ab_geno = {}
with open(lookupfile, 'r') as l:
for line in l:
tmp = line.strip().split(',')
snp = tmp[0]
# add the line to ab_geno
ab_geno[snp] = tmp
return(ab_geno)
|
693b4b11a24b1e57fdfb863c84339bedf6e95883
| 500,325 |
def to_http_url(list):
"""convert [hostname, port] to a http url"""
str = ''
str = "http://%s:%s" % (list[0], list[1])
return str
|
021ecc3a32b1646b0dbe0ecf150d91b55d323523
| 518,223 |
def get_instance_ids(instances):
"""
Returns a list of instance ids extract from the output of get_instances()
"""
return [i["Instances"][0]["InstanceId"] for i in instances]
|
69720ddf16ccbbee1bb44a780d793ea8b5af60cf
| 375,174 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary Release on Backward Equations for the
Functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS
Industrial Formulation 1997 for the Thermodynamic Properties of Water and
Steam, http://www.iapws.org/relguide/Supp-Tv%28ph,ps%293-2014.pdf, Eq 6
Examples
--------
>>> _Backward3a_T_Ps(20,3.8)
628.2959869
>>> _Backward3a_T_Ps(100,4)
705.6880237
"""
I = [-12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -6, -6, -5, -5, -5,
-4, -4, -4, -2, -2, -1, -1, 0, 0, 0, 1, 2, 2, 3, 8, 8, 10]
J = [28, 32, 4, 10, 12, 14, 5, 7, 8, 28, 2, 6, 32, 0, 14, 32, 6, 10, 36, 1,
4, 1, 6, 0, 1, 4, 0, 0, 3, 2, 0, 1, 2]
n = [0.150042008263875e10, -0.159397258480424e12, 0.502181140217975e-3,
-0.672057767855466e2, 0.145058545404456e4, -0.823889534888890e4,
-0.154852214233853, 0.112305046746695e2, -0.297000213482822e2,
0.438565132635495e11, 0.137837838635464e-2, -0.297478527157462e1,
0.971777947349413e13, -0.571527767052398e-4, 0.288307949778420e5,
-0.744428289262703e14, 0.128017324848921e2, -0.368275545889071e3,
0.664768904779177e16, 0.449359251958880e-1, -0.422897836099655e1,
-0.240614376434179, -0.474341365254924e1, 0.724093999126110,
0.923874349695897, 0.399043655281015e1, 0.384066651868009e-1,
-0.359344365571848e-2, -0.735196448821653, 0.188367048396131,
0.141064266818704e-3, -0.257418501496337e-2, 0.123220024851555e-2]
Pr = P/100
sigma = s/4.4
suma = 0
for i, j, ni in zip(I, J, n):
suma += ni * (Pr+0.240)**i * (sigma-0.703)**j
return 760*suma
|
cb0b9b55106cf771e95505c00043e5772faaef40
| 2,748 |
import re
def re_find(txt: str, regexp: str, i: int = 0) -> str:
"""Utility: search string txt for a regexp and return i-th group
(i.e. parenthesis) if match succeds. Default is whole match."""
match = re.search(regexp, txt)
if match:
return match.group(i)
return ''
|
9bc087852a4fffb226505813304db2c4f0617c13
| 379,370 |
def _backslashreplace_backport(ex):
"""Replace byte sequences that failed to decode with character escapes.
Does the same thing as errors="backslashreplace" from Python 3. Python 2
lacks this functionality out of the box, so we need to backport it.
Parameters
----------
ex: UnicodeDecodeError
contains arguments of the string and start/end indexes of the bad portion.
Returns
-------
text: unicode
The Unicode string corresponding to the decoding of the bad section.
end: int
The index from which to continue decoding.
Note
----
Works on Py2 only. Py3 already has backslashreplace built-in.
"""
#
# Based on:
# https://stackoverflow.com/questions/42860186/exact-equivalent-of-b-decodeutf-8-backslashreplace-in-python-2
#
bstr, start, end = ex.object, ex.start, ex.end
text = u''.join('\\x{:02x}'.format(ord(c)) for c in bstr[start:end])
return text, end
|
f1100d986e3fabd169bf2e0a387621c900e2428c
| 540,957 |
import requests
import re
def collect_metrics(website, pattern=None):
"""Retrieve metrics (response time, status code) from a given website.
Optionally, search for a regex pattern. Then publish to a Kafka topic.
Arguments:
website (str): URL of website to collect metrics from
pattern (str, optional): Regex pattern to look for
Returns:
data (dict): Key-value object with desired metrics
"""
r = requests.get(website)
# Try searching for regex pattern if provided
match = None
if pattern and r.status_code == 200:
match = True if re.search(pattern, r.text) else False
data = {
'url': website,
'response_time': r.elapsed.total_seconds(),
'status_code': r.status_code,
'regex_found': match
}
return data
|
35206802c9af165b7154db3a38207a2d6b438e83
| 145,538 |
def descale(data, data_max, data_min):
"""Reverse normalization
Args:
data (np.array): Normalized data
data_max (float): max value before normalization
data_min (float): min value before normalization
Returns:
[np.array]: Reverse-Normalized data
"""
data_descaled = data*(data_max-data_min)+data_min
return data_descaled
|
e078dc5eb9613a9106dd2210f467011525dcb646
| 98,977 |
def should_skip_build(metadata_tuples):
"""Takes the output of render_recipe as input and evaluates if this
recipe's build should be skipped."""
return all(m[0].skip() for m in metadata_tuples)
|
0c4c54349bbea32733e9b0459fdfab9466dfdba8
| 604,147 |
def determine_scaling_factor(money_endowment: int) -> float:
"""
Compute the scaling factor based on the money amount.
:param money_endowment: the endowment of money for the agent
:return: the scaling factor
"""
scaling_factor = 10.0 ** (len(str(money_endowment)) - 1)
return scaling_factor
|
fed7d4598ee771ac857917010301df2d3722a0cb
| 254,697 |
def fitAlgorithm(classifier, trainingData, trainingTarget):
"""
Fits a given classifier / pipeline
"""
#train the model
return classifier.fit(trainingData, trainingTarget)
|
ddc6a7b2f5c42e07e212c2a48fd1d35b1c77dab2
| 71,473 |
def wien(t):
"""The peak wavelength of a blackbody. Input in Kelvins, output in nm"""
return 2.9e6 / t
|
b40e6d295a373536d93268d8f7ea90c7b97b824a
| 469,814 |
def makeSafeXML( someString:str ) -> str:
"""
Replaces special characters in a string to make it for XML.
"""
return someString.replace('&','&').replace('"','"').replace('<','<').replace('>','>')
|
44b526c5e9e66cef747024f8eddd12cc4fc06cf5
| 496,319 |
def as_formatted_lines(lines):
"""
Return a text formatted for use in a Debian control file with proper
continuation for multilines.
"""
if not lines:
return ''
formatted = []
for line in lines:
stripped = line.strip()
if stripped:
formatted.append(' ' + line)
else:
formatted.append(' .')
return '\n'.join(formatted).strip()
|
ba313e3041a971d3756ab7811ffdc23f31bfe8b1
| 419,325 |
def get_obj_in_list(obj_name, obj_list):
"""
Gets an object out of a list (obj_list) whos name matches obj_name.
"""
for o in obj_list:
if o.name == obj_name:
return o
print("Unable to find object by the name of %s in list:\n%s" %
(obj_name, map(lambda o: o.name, obj_list)))
exit(1)
|
42c575087e2148722a48a9735558bbf5ba30ddf7
| 556,257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.