content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_attribute_element(attributes, element: str, enum):
"""
Constructs an Emum object of a given attribute
:rtype: FastEnum
:type enum: FastEnum
:type attributes: XML attributes
:param attributes: XML attributes of a certain XML node
:param elment: A String
:param enum: The Enum objec... | b88bc30bd5c0e2433d72d58f06277fdd84f8e8b2 | 631,805 |
def normalise(value: float, current_min: float, current_max: float, intended_min: float, intended_max: float) -> float:
"""
Function used to normalise a value to fit within a given range, knowing its actual range.
Uses standard MinMax normalisation.
:param value: Value to be normalised
:param curr... | a13aed0fd15043dcc976f69448702295c6ed2659 | 631,806 |
def _patched_computation_module(module, compute_list, compute_fn):
"""
Patch the module to compute a module's parameters, like FLOPs.
Calls compute_fn and appends the results to compute_list.
"""
ty = type(module)
typestring = module.__repr__()
class ComputeModule(ty):
orig_type = ... | 6b436276ca61fcc2984098e2252b0cef75253d0f | 631,807 |
def is_letter(c):
"""
Checks if the given character is a letter.
:param c: The character to test.
:return: True if the character is a letter, False otherwise.
"""
return 'A' <= c <= 'Z' or 'a' <= c <= 'z' | c6e029ad5e0d80e21b9a44080cc5031ecc5146e2 | 631,813 |
def convert_timedelta(duration):
"""converts date.timedelta object into hours and minutes string format HH:MM"""
seconds = duration.seconds
hours = seconds // 3600
if hours < 10:
hours = "0" + str(hours)
else:
hours = str(hours)
minutes = (seconds % 3600) // 60
if minutes < 1... | 27320025b2f0d70582492faeace8f0a95eda57e1 | 631,816 |
def get_combined_domain(X1, X2):
"""
Returns a list of the unique elements in two list-like objects. Note that
there's a lot of ways to make this function, but given how the rest of the
rank-turbulence divergence function is structured, it's nice to have this
self-contained version.
Parameters
... | 047c653e479709971f69a0071ce59332ea16ee41 | 631,817 |
def get_unique_from_list(source_list, compare_list):
"""
Extract unique entries from list.
Compare source_list to compare_list and return entries from source_list
and not in compare_list.
Parameters
----------
source_list : list
Input list to compare to base list
compare_list :... | 2cd4006021e1fef5276f334874411ac58ad9ce0b | 631,818 |
def guess_encoding(path):
"""Sample a file, seeing if the platform-dependent encoding works, and
trying latin_1 if it doesn't.
A more robust solution would be to use the chardet library,
but we want to try and keep this dependency-free."""
try:
e = None
with open(path, new... | ec9807c41d70f7d2141be27af8388eb28232aa53 | 631,819 |
import math
def crowding_replacement(random, population, parents, offspring, args):
"""Performs crowding replacement as a form of niching.
This function performs crowding replacement, which means that
the members of the population are replaced one-at-a-time with
each of the offspring. A random sa... | fa12202d5588b0827f9840ae2a008d881fac5029 | 631,820 |
import math
def my_log(num):
"""
Floors the log function
:param num: the number
:return: log(num) floored to a very low number
"""
if num == 0.0:
return -9999999999
return math.log(num) | e420a883833b5d5a1f9d0dd65c30ff72cbf25ee6 | 631,823 |
def get_name(node):
"""Return name of node."""
return node.get('name') | 0564bd4d4f095145ab0dc1fd344e7e41dc577e6f | 631,828 |
import jinja2
def render_template(path: str, data: dict) -> str:
"""
Renders a template with given data.
Parameters
----------
path: str
Path to the template
data:
The provided data for rendering
Returns
-------
template: str
Rendered template
"""
... | 0af0e93d940715cad2d7bb1588ef13260fffa060 | 631,833 |
import shutil
def _termsize(fallback=(80, 24)):
""" Returns the terminal size, or the fallback if it can't be retrieved"""
try:
columns, rows = shutil.get_terminal_size(fallback=fallback)
except:
return fallback
return columns, rows | c1d93d1a622976140cb5208803c5eedcd44058ed | 631,838 |
import re
def format_companies(company):
"""
Format the selected company so that the API can find relevant articles.
"""
# Remove junk at the end of the names
if company[-6:] == ", Inc.":
return re.sub(r' ', "-", company[:-6])
if company[-5:] == ", Inc":
return re.sub(r' ', "-... | 76b1e7a108c982f9bc17dc9e3299a20e3887829d | 631,844 |
def prop_finally(printer, ast):
"""Prints a finally property "<> ..."."""
prop_str = printer.ast_to_string(ast["prop"])
return f'<>{prop_str}' | 21a728d370b02954a8c1c6eb84f9195ea1cfb4d8 | 631,845 |
from typing import Tuple
def _find_start_indices(starts_with_peak: bool) -> Tuple[int, int]:
"""Find start indices for peaks and valleys.
Args:
starts_with_peak: bool indicating whether or not a peak rather than a valley comes first
Returns:
peak_idx: peak start index
valley_idx:... | 726e60a19485a4e54af1fb30efb317d64ecee595 | 631,848 |
from typing import Set
import ipaddress
def parse_ipa4(data: str) -> Set[str]:
"""
parse 'ip -o -4 a' output
"""
res = set()
# 26: eth0 inet 169.254.207.170/16
for line in data.split("\n"):
line = line.strip()
if line:
_, dev, _, ip_sz, *_ = line.split()
... | 8d3ce38e1d166755a1bae4518e37601286ad7508 | 631,849 |
def mag_zeropoint(filter_name):
"""
Given a filter name, return the number of photons per square centimeter per second
which a star of zero'th magnitude would produce above the atmosphere. We assume that the star
has a spectrum like Vega's.
The numbers are pre-calculated and we just pick the approp... | bf91067e878419f535ab04a0b3b13ba499b42306 | 631,853 |
def bibser2bibstr(bib=u'', ser=u''):
"""Return a valid bib.series string."""
ret = bib
if ser != u'':
ret += u'.' + ser
return ret | 508dde6621597547cc3dcda26d558a58c061ffb5 | 631,854 |
from typing import List
def strseq_startswith(seq_a: List[str], seq_b: List[str], start_index: int, case_insensitive=True) -> bool:
"""Test if seqA is starts with seqB"""
if len(seq_a) - start_index < len(seq_b):
return False
if case_insensitive:
for i in range(len(seq_b)):
if... | f4fbd072cf8f724f4d59d1ee644da6786f673570 | 631,858 |
def is_whitespace(char):
"""
Checks if the character is a whitespace
Parameters
--------------
char: str
A single character string to check
"""
# ord() returns unicode and 0x202F is the unicode for whitespace
if char == " " or char == "\t" or char == "\r" or char == "\n" or or... | 1bf573219dd36347025305046bb6eade38c847a9 | 631,862 |
def pass_sources_list_filter(incident, sources_list):
"""Checks whether the event sources of the incident contains at least one of the sources in the sources list.
Args:
incident (dict): The incident to check
sources_list (list): The list of sources from the customer
Returns:
bool.... | 9bda8cc28a61fc70ccd2df62b05095582de40cab | 631,864 |
def custom_sort(str_list, alphabet):
"""
Sort a list of strings by a specified alphabetical order.
Params
------
str_list: list[str]
List of strings to be sorted.
alphabet: str
Case sensitive alphabetical order for sort.
Returns
-------
Sorted list[str] acco... | 316d1e91bccc7930ccc1ed384e4a610dd06f2cdd | 631,868 |
def check_compatibility(selected_usb_size: int, iso_rec_size: str) -> bool:
"""
Function to test whether or not the usb is large enough for selected ISO
:param:string: selected_usb_size pointer to selected usb device size
:param:int: iso_rec_size recommended size selected ISO needs
:return: true if ... | c8a823b11b78be50e088feb4198af166d0b0ffdc | 631,870 |
def chart_title(statistic, chat, start_date, end_date):
"""Return title for chart displaying statistic (given as string)."""
return '{statistic} in "{subject}" ({start_date} - {end_date})'.format(
statistic=statistic,
subject=chat.subject,
start_date=start_date.Format('%d/%m/%Y'),
... | 2ba51c36fd2ea36eea194b878dd1a19f34f2b69c | 631,876 |
def greatest_common_divisor(a, b):
"""[
Summary:
Returns the largest number which divides
integers 'a' and 'b'. If 'b' is equal to 0 then
'a' is returned. Arguments calculated as absolute value.
Implements Euclid's algorithm;
https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations]... | c8aceea1968d4c96f8430baebe08e9ca569aca85 | 631,878 |
def find_base_style(masters):
"""Find a base style shared between all masters.
Return empty string if none is found.
"""
if not masters:
return ""
base_style = (masters[0].name or "").split()
for master in masters:
style = master.name.split()
base_style = [s for s in styl... | dbaacbaa0d984550b4d07ded15a116c2dd075a43 | 631,879 |
def isalphadigit_(s):
"""
Return ``True`` if ``s`` is a non-empty string of alphabetic characters
or a non-empty string of digits or just a single ``_``
EXAMPLES::
sage: from sage.repl.preparse import isalphadigit_
sage: isalphadigit_('abc')
True
sage: isalphadigit_('12... | 4745d8cac5abed644c754918b3f0bd640afced42 | 631,880 |
def is_music(f):
"""
returns if path, f, is a music file
"""
music_exts = ['mp3','flac','wav','ogg','wma','aiff','aac','ra','dsd','dsf']
return f.split('.')[-1] in music_exts | e05fa2654630d7072cca86b78b7205ae475fa795 | 631,881 |
def _get_paths(config_dict):
"""Return a list of all paths referenced by the config dict."""
return_list = [
config_dict["diag_table"],
config_dict["data_table"],
config_dict["forcing"],
config_dict["initial_conditions"],
]
patch_files = config_dict.get("patch_files", [])... | ed714938b58358c0405fc7dfcd1257e65dfd7b77 | 631,886 |
def df_has_data(data) -> bool:
"""Return True if `data` DataFrame has data."""
return data is not None and not data.empty | 97a75e2ec0b5cc020b789dc0d0738213436c8abb | 631,888 |
def get_shap_values(model_manager, direct_id, target=None):
"""Get the SHAP values of features.
Args:
model_manager: ModelManager, an object containing all prediction models
direct_id: the identifier of the patient's related entry in the target entity
(e.g., the admission id).
... | 201ecc08c87262f7dd3aa34f7b2164b6489de405 | 631,890 |
import torch
def cross_entropy(log_probs, classes, reduce='mean'):
"""
Computes the categorical cross-entropy loss.
Args:
log_probs: tensor, shape(n_samples, n_classes)
log probabilities over possible classes for each sample.
classes: tensor of int, shape(n_classes)
... | e91e6dea318107c55763f4afbcb539a28f49f865 | 631,891 |
def to_float(value):
"""Transforms the Crystal-specific float notation into a floating point
number.
"""
base, exponent = value.split("**")
base = int(base)
exponent = int("".join(exponent.split()))
return pow(base, exponent) | 01f467c0ac66cb3f282ab5f1a7400b89ac8d841a | 631,892 |
def get_cmd(chk):
"""
Assemble the correct "packet-tracer" command based on the "proto"
value. TCP/UDP use source/destination ports, ICMP uses type/code,
and other protocols use neither. Returns a valid "packet-tracker"
command that can be issued to an ASA without further modification.
"""
... | 9d0dd51d0f2f264d0c165dd8d80cb06ccf33fa03 | 631,893 |
def corr_naam(name):
"""convert name used in program to model name and back
Note: all names must be unique!
"""
names = (("techtaak", 'techtask'), ("programma", 'procproc'))
for name1, name2 in names:
if name == name1:
return name2
if name == name2:
return na... | 7c2262ca9e24c1fb4a02e33c1ae35b62ee33dfbf | 631,895 |
def no_nulls_test(df):
"""Checks that all elements are not null"""
return df.isnull().values.sum() == 0 | 257dc8fb596de800ea9cdb5864c7492ce9f98527 | 631,899 |
from typing import Callable
from typing import Dict
import inspect
def get_input_type_dict(func: Callable) -> Dict[str, type]:
"""
Returns a dict like {argname: type} for given function inputs
Examples:
>>> @dataclass
>>> class Base:
>>> ...
>>> @dataclass
>>> c... | d15298d087fe2e20b3e291dfef497b7d1cd5f5b2 | 631,903 |
def polynomial(coefficients):
"""
Create a polynomial from the given list of coefficients.
For example, if the coefficients are [1, 0, 3, 5], then
the polynomial returned is
P(t) = t^3 + 3t + 5
If the coefficients are [3, 2, -2, 9, 4, 0, 1, 0], then
the polynomial returned is
P(t) = 3t^7 + 2t^6 - 2t^5 + 9t^... | 6b17b1cd32b56c46ea6244e5666330d84fc5d310 | 631,907 |
import copy
def regularize(l):
"""
If necessary mix in a small prior for regularization.
"""
epsilon=1e-3
l=copy.copy(l)
for i in range(0,len(l)):
if l[i]==0:
l[i]=epsilon
return l | cde50c63fef8b22e800daeecda29998e62813850 | 631,913 |
def get_dim(edgelist):
"""Given an adjacency list for a graph, returns the number of nodes in
the graph.
"""
node_dict = {}
node_count = 0
for edge in edgelist:
p, q = edge[ :2]
if p not in node_dict:
node_dict[p] = True
node_count += 1
if q not in... | 6a85b68f0afddc1ba05e5a43d0cb52e5031da118 | 631,919 |
async def root():
"""Basic Hello World."""
return {"message": "Hello Hello World"} | f4476bf4eea014e1525ae0ca4ed8aaddb1625266 | 631,920 |
import math
def angle_on_plane(plane, vec1, vec2):
""" Return the angle between two vectors projected onto a plane.
"""
plane.normalize()
vec1 = vec1 - (plane * (vec1.dot(plane)))
vec2 = vec2 - (plane * (vec2.dot(plane)))
vec1.normalize()
vec2.normalize()
# Determine the angle
ang... | 8e724343bf38fa2aed7572e09f8f13c8d840323c | 631,921 |
import socket
def target_encrypted(target_ip: str) -> bool:
"""
Checks if the target is using encryption
:param target_ip: Target IP running the server
:type target_ip: str
:return: True or false
:rtype: bool
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((tar... | dbf2220df923867aeca85acd9db551c76959bdee | 631,922 |
def binboolflip(item):
"""
Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
... | 854bd142dee085c5126d3dce38b1b13a6443386c | 631,924 |
def get_way_points(relation):
"""
Get way points of OSM relation.
@param relation: OSM relation as dictionary.
@return: List of way points (OSM node ids).
>>> relation_id = 660162
>>> relation = get_relation_by_id(relation_id)
>>> way_points = get_way_points(relation)
"""
return [... | bb689b947069f3ec8ed22763c247010cd0b64748 | 631,928 |
import string
def strip_punctuation(headline):
"""
Remove all punctuation from a headline to return only the words.
:param headline: raw headline
:return: parsed headline
"""
table = headline.maketrans({key: None for key in string.punctuation})
headline = headline.translate(table)
ret... | 2bf02d615178c1f25f7684d51f79a585dc2a6389 | 631,933 |
def select_scan_no_qc(scans_meta):
"""Select a scan from available scans in case there is not an available QC.
Args:
scans_meta: DataFrame containing the metadata for images to choose among
Returns:
DataFrame row containing selected scan
"""
# We choose the first scan (not containi... | cdeb34c727ea4976db977f349a54d6b21c86f26a | 631,936 |
def pad_sentence(sentence, window_len, lsl, rsl, mask):
"""
:param sentence: Sentence to pad
:param window_len: The ammount of tokens in the desired sentence
:param lsl: (left-side length) The current token count to the left of the central token
:param rsl: (right-side length) The current token coun... | d31f4ed77dd23b84d5a1b822f641f863ab3b8e61 | 631,937 |
def create_file(repo, path, message, content):
"""Create a file in a github repository using Github's content create API:
https://developer.github.com/v3/repos/contents/#create-a-file
Will create the file at the specified path under a given repo and use the
provided commit message. Content should be ... | 09c609aedba0d63c179ecec6573450de8c78be2e | 631,938 |
def get_published_branch_id(database):
"""Return the IDs of the published-branch courses."""
collection = 'modulestore.active_versions'
projection = {'versions.published-branch': 1, '_id': 0}
cursor = database[collection].find({}, projection)
published_branch_ids = []
for result in cursor:
... | ea83b272be5a02c92ecd3859f25e1b3f04c566a3 | 631,941 |
def longest_consecutive_sequence(seq: str, char: str) -> int:
"""Return length of the longest consecutive sequence of `char` characters
in string `seq`."""
assert len(char) == 1
longest = 0
current_streak = 0
for c in seq:
if c == char:
current_streak += 1
else:
... | 08e8e0aebccc8681f7d2df4e7e6d8a2df911451b | 631,942 |
def status(category, values, suffix=""):
"""Return status in human-readable format."""
size = len(values)
pluralization = "" if size == 1 else "s"
return "* Found {} {}{} {}.".format(size, category, pluralization, suffix) | 934b7160e36a467c4e553b7904974a9fa81a2db9 | 631,946 |
def index_to_alg(cnt):
""" Convert a bit index to algebraic notation """
column = "abcdefgh" [int(cnt % 8)]
rank = "12345678" [int(cnt // 8)]
return column + rank | e2fde3811f6488ddafa81ffe4b6ed8cc1c8703a2 | 631,947 |
import csv
def get_file_entry_names(path):
"""Get the names of all entries in the food dictionary or a log file.
:param path: A string of the food dictionary or log file pathname.
:returns: A list of the entry names associated with each entry in the food dictionary or a log file.
"""
entry_names... | de75a82755c7a93b5a94a266ee149d544bc40973 | 631,950 |
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters
Output: tuple (dist, idx1, idx2) where dist is distance between
cluster_l... | ef2275a741b40befc19065bee5568d3e13eea319 | 631,952 |
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x += cropLeft
y += cropTop
w ... | e3532c0a9a2d031843a322d5f071ba371574bbcf | 631,955 |
def Rels_attach(self, rel):
"""
Inserts *rel* into *self*, performing additional necessary bindings.
Return value: *rel.target_part* (or *rel.target_ref*, if *rel.is_external*).
"""
self[rel.rId] = rel
if rel.is_external:
return rel.target_ref
target = rel.target_part
self._target_parts_by_rId[rel... | 329b6e748384b8859fefcdbc398b398937aa0acb | 631,959 |
def get_columns_to_drop(year):
"""
Returns a list of strings indicating which columns to drop for the data
in the given year
:param year: the year of the data
:return: a list of which columns to drop for the given year; "us" is always
dropped
"""
cols_to_drop = ["us"] # Always drop "us"... | 58c5e0916768355a77c245e9e7a93e5edc9d540d | 631,961 |
from typing import Any
def is_chars(obj: Any) -> bool:
"""Check if an object is one of the built-in character types.
The built-in data types representing characters in Python 3 are:
str, bytes, bytearray
Arguments:
obj: object to be checked
Returns:
True if the object is an ... | d501a8326205896893f14a8a381e8f4579f36e69 | 631,963 |
def is_top_down(lines):
"""
Return `True` if dates in the given lines go in an ascending order, or `False` if they go in a descending order. If
no order can be determined, return `None`. The given `lines` must be a list of lines, ie.
:class:`~taxi.timesheet.lines.TextLine`, :class:`taxi.timesheet.lines.... | 7251ad73478cd85e0faaa229e84060bbc9c649e8 | 631,966 |
def _get_quote_indices(line, escaped):
"""
Provides the indices of the next two quotes in the given content.
:param str line: content to be parsed
:param bool escaped: unescapes the string
:returns: **tuple** of two ints, indices being -1 if a quote doesn't exist
"""
indices, quote_index = [], -1
fo... | 7bc8019af99730de306062389ad6c24b582f3ebf | 631,977 |
import random
import itertools
def random_tuple_list(lst1, lst2, lb=1):
"""
Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2
"""
len_lst1 = len(lst1)
len_lst2 = len(lst2)
k = random.randint(lb,max(len_lst1,len_lst2))
return random.sample(list(itertools.product... | bb70477ba997694f464ad1757067be1f5815d18a | 631,980 |
def create_email_field_dict(field_name,
field_type,
field_value,
field_displayed_text,
is_allow_create_indicator,
is_href,
is_editable,
... | fd7844bd040f61703d4f36d572ee097f60009090 | 631,982 |
def inflate(size, margin, mul=1):
"""
Increase size (a size or rect) by mul multiples of margin
margin's items are interpreted as those of a CSS margin. If size is a
4-tuple, its "sides" are moved outwards by the corresponding items of
margin; if it is a 2-tuple, it is treated as if it were a rect ... | 709cc5d4e2609e5f5a49e78656117278e8812ae4 | 631,983 |
from typing import TextIO
import csv
def parse_chanjo_sexcheck(handle: TextIO):
"""Parse Chanjo sex-check output."""
samples = csv.DictReader(handle, delimiter='\t')
for sample in samples:
return {
'predicted_sex': sample['sex'],
'x_coverage': float(sample['#X_coverage']),
... | 5d0360aa41fa01cfb550ea6cdcfd16d623d03401 | 631,987 |
import socket
def bind(port, socket_type, socket_proto):
"""Try to bind to a socket of the specified type, protocol, and port.
This is primarily a helper function for PickUnusedPort, used to see
if a particular port number is available.
For the port to be considered available, the kernel must support ... | b2700e7589bff8ae4b51c309fd90b119478e7ce0 | 631,989 |
def count_occurances(comment, word):
"""
A helper function to get the number of words in a comment.
"""
comment = comment.replace('?', ' ')
comment = comment.replace('.', ' ')
comment = comment.replace('-', ' ')
comment = comment.replace('/', ' ')
a = comment.split(" ")
count = 0
... | b4c5c5e0a7792e29811937a1e77161196bd9856c | 631,990 |
import random
def choose_random_elements(_list, num_elements=5000):
"""
Choose a certain number of elements from given list randomly and return the
original list without the chosen elements as well as a list of the chosen
elements.
:param _list: list with elements to be chosen from
:param num_... | 1ebe29cc7d4a784d4805c762feca523d8ee4c293 | 631,991 |
import json
def get_secret_dict(service_client, arn, stage, token=None):
"""Gets the secret dictionary corresponding for the secret arn, stage, and token
This helper function gets credentials for the arn and stage passed in and returns the dictionary by parsing the JSON string
Args:
service_clie... | 330c5ccb70e5c117d14efb6908865fdf4dcc3a26 | 631,995 |
def assertVolumesEqual(test, first, second):
"""
Assert that two filesystems have the same contents.
:param TestCase test: A ``TestCase`` that will be the context for this
operation.
:param Volume first: First volume.
:param Volume second: Second volume.
"""
first = first.get_filesy... | 34b21ff42a350e151e6a7b824d24a5897eec7073 | 631,996 |
import pickle
def read_pkl(pkl_filename):
"""Loads pickle file."""
with open(pkl_filename, "rb") as pkl_file:
return pickle.load(pkl_file) | 4c62d14e47ebb78c9aefe23c0f0bc488f21d5500 | 631,997 |
import math
def AMS(s, b, br=10.0):
""" Approximate Median Significance defined as:
AMS = sqrt(
2 { (s + b + b_r) log[1 + (s/(b+b_r))] - s}
)
where b_r = 10, b = background, s = signal, log is natural logarithm """
radicand = 2 *( (s+b+br) * math.log (1.0... | a8ff6697d0e3ffc83ce1b74b289c291c96e47dd5 | 631,998 |
from pathlib import Path
def relative_path_for(provided_path: Path, root_path: Path) -> Path:
"""
Return relative path to root is provided path is on root_path, If not return the provided path
Parameters
----------
provided_path : Path
absolute or relative path
root_path : Path
... | 363939399830c507a292247c45f611cdf8e6dccb | 632,001 |
def download_file(s, url, data_dir):
"""
Download the provided file and place it in data_dir
"""
local_filename = data_dir + url.split('/')[-1]
# NOTE the stream=True parameter
req = s.get(url, stream=True)
with open(local_filename, 'wb') as local_f:
for chunk in req.iter_content(chu... | 1dc6de0cab26d9bb603888e8c7ed0730a4ba941b | 632,003 |
def vsstd(a, s=0.1):
"""Normalize the image range for visualization."""
return (a - a.mean()) / max(a.std(), 1e-4) * s + 0.5 | 46cb71073d743d43ce29d1eca75cfa03be1fa33b | 632,005 |
def has_file(conn, path, mirror_id):
"""check if file 'path' exists on mirror 'mirror_id'
by looking at the database.
path can contain wildcards, which will result in a LIKE match.
"""
if path.find('*') >= 0 or path.find('%') >= 0:
oprtr = 'like'
path = path.replace('*', '%')
... | ae68cd1adfad092b554e2df3dfcad622983d4e93 | 632,006 |
import random
def get_random_block_from_data(data, batch_size):
"""Randomly select batch_size number of contiguous samples."""
start_index = random.randint(0, data.shape[0] - batch_size)
return data[start_index:(start_index + batch_size)] | 36281d986c24a83eb19af65367d8bd652879e1d0 | 632,007 |
def GetNextQtnodeBounds(qtnode, x, y, size):
"""Calculate next level boundary for qtnode.
If the qtnode has further precision, call this routine
recursively.
Args:
qtnode: The remaining string of the qtnode.
x: Current left of the qtnode (degrees).
y: Current bottom of the qtnode (degrees).
si... | f3b1bea59f68ad4d3e7b05ad65fe856172547f44 | 632,009 |
from typing import Any
from typing import Dict
from typing import List
def get_data_list_from_timeseries(data: Any) -> Dict[str, List[float]]:
"""Constructs a Dict as keys are the container names and
values are a list of data taken from given timeseries data."""
if data['status'] != 'success':
rai... | 6084188f57e5dc9bd85c36ac3e38c853e45b0584 | 632,010 |
from typing import OrderedDict
def find_overlaps(orfs_found):
"""Associates overlapping ORFs based on their start-stop intervals"""
# initialize dictionary to store associations for each ORF
overlaps_found = { i : [] for i in range(1, len(orfs_found)+1) }
processed_orfs = []
# sort ORFs by asce... | c638e9896dda1015ef3ff22d3fcf76fb91280e6b | 632,012 |
def getDate(year, month, day):
""" Get date string from year month and day"""
return str(year)+'%02d' %month+'%02d' %day | a10f17f6fcec17adb259ad170479db8cb15bb013 | 632,016 |
def mutate_individual(logger, ind):
"""
Simply calls the mutate function of the given individual.
Args:
logger (:obj:`logging.Logger`): A logger to log with
ind (:obj:`actions.strategy.Strategy`): A strategy individual to mutate
Returns:
:obj:`actions.strategy.Strategy`: Mutate... | a2d3fdc6f04549c81777cf8a45f0ea799b58dc76 | 632,017 |
def boolean_bitarray_get(integer, index):
"""The index-th-lowest bit of the integer, as a boolean."""
return bool((integer >> index) & 0x01) | 0504743080583bc03fc75214d1ffb01f0f6371cf | 632,019 |
def ExtractUnits(hf,k):
"""
Returns all the data for a single key (column) in a given HDF5 file.
Parameters
----------
hf : File
The HDF5 where the data is stored.
Example:
HDF5_File = h5py.File(filename, 'r')
k : str
the name of the column that is to be extr... | 94d4533710b8dd35b3f26b52accf9d89fe074b22 | 632,021 |
def _get_columns(x):
""" retrieve the columns of something if it exists """
if hasattr(x, "columns"):
return list(x.columns)
else:
return None | 9b62a7fb4856c35ff8f6a2ce6d948c01b47a6871 | 632,022 |
import hashlib
def branch_hash_worktree_path_builder(branch):
"""Returns a relative path for a worktree based on the hash of the branch
name.
"""
return hashlib.md5(branch.encode("utf-8")).hexdigest() | 7b01cba489cd58e87459c8fc33a06193c1bafdd0 | 632,025 |
def from_gca_linestring(gca_obj):
"""
Converts LineString GCA to an EGF string.
Returns
-------
egf_str : str
LineString GCA as an EGF string
"""
if gca_obj.geometry_type != "LS":
raise ValueError(f"Expected geometry type to be 'LS' and got '{gca_obj.geometry_type}' instea... | 976b59d1cfd8d3ae4620416fcddf5104f8de83ba | 632,026 |
def rm_additional_rots_and_trans(results):
"""
Removes the first 6 rotations and translations, to leave
the required 3N vibrations.
"""
for key, value in results.items():
results[key] = value[6:]
return results | 64974127141dbbae44056d25c1ca0042b97a3fb6 | 632,027 |
def get_tableau_values(data):
"""
Tableau's data lists all the values used throughout the view in a single
place, and the display information about each chart references these values
by data type (int, cstring, etc.) and index.
Return a simplified version of this: a dict mapping data types to lists... | c2f0f4c501a95e42add883ff7de63df28162ee93 | 632,029 |
from typing import Tuple
def generate_command_parameters(command: str) -> Tuple[str, int]:
"""Helper function to generate parameters from commands passed as string.
A command string is converted to a (action: str, step: int) tuple.
Pattern is:
command is an "action step" string than we can split ... | d30664e808ec03f29e8835698145dcf75072d1d9 | 632,030 |
def get_adjusted_price(price, currency, currency_data):
"""Return adjusted price and name of company the label is referring to.
If a user wants the price value in a currency different from the dollar
this function computes the stock value in such currency.
:param price: The price of the stock of the c... | bb7cd9b0180a77415329959a6f4178cf6448a507 | 632,035 |
def wrapTex(tex):
""" Wrap string in the Tex delimeter `$` """
return r"$ %s $" % tex | d85184194746b7806f2fe5b4ee214b6f5ea67dbc | 632,039 |
def split_geolocation_string(config, geolocation_string):
"""Fields of type 'geolocation' are represented in the CSV file using a
structured string, specifically lat,lng, e.g. "49.16667, -123.93333".
This function takes one of those strings (optionally with a multivalue
subdelimiter) and return... | d3b50c2a9a6d26f1e65ea5245d576bbcd65e104d | 632,040 |
import random
def raffle(tickets, lots):
"""Run a raffle, producing a list of randomly selected winners.
Arguments:
tickets -- a list containing (name, number of tickets purchased) tuples
lots -- a list of lots available to be won
Each ticket can only win once, but people purchasing multiple tic... | 25a6254e6e74a208874d946579798eb7c89d2b8c | 632,042 |
def fix_projection(shape, axes, limits):
"""Fix the axes and limits for data with dimension sizes of 1.
If the shape contains dimensions of size 1, they need to be added
back to the list of axis dimensions and slice limits before calling
the original NXdata 'project' function.
Parameters
... | b2308c7f398a19b5caf3f853ba47c1d254a5332d | 632,043 |
def macaddr_pack(data, bytes = bytes):
"""
Pack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c, and PGSQL Manual types
"""
# Accept all possible PGSQL Macaddr formats as in manual
# Oh for sscanf() as we could just copy PGSQL C in src/util/adt/mac.c
colon_parts = data.split(':')
dash_parts = d... | 3a2cb426e0f86516cc34feb52e4e13f9227127e2 | 632,045 |
def constraint_class(kind):
"""
The convention is that name of the class implementing the constraint
has a simple relationship to the constraint kind, namely that
a constraint whose kind is 'this_kind' is implemented by a class
called ThisKindConstraint.
So:
``min`` --> ``MinConst... | d4542f2a4ec6bb86efe26139ab513e0f0930181c | 632,051 |
def coerce_int(obj):
"""Return string converted to integer.
.. Usage::
>>> coerce_int(49)
49
>>> coerce_int('49')
49
>>> coerce_int(43.22)
43
"""
try:
return int(obj) if obj else obj
except ValueError:
return 0 | 47ff1a15c78786e9b29a7e9eb80bd1cbe8b0be45 | 632,053 |
from typing import Tuple
from typing import Optional
def split_module(path: str) -> Tuple[Optional[str], Optional[str]]:
"""Split module and system path."""
if not path.startswith('@'):
return None, path
index = path.find('/')
if index == -1:
return path[1:], None
else:
re... | 7e3a1c127c41e428fe118d2e024e2a21eeba29cf | 632,059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.